blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
4ccea86036dd235f91c3c02531a8cef753637972
4aeec3f6db28fe3ab4337777a19a50151bf58394
/rd_framework_cpp/src/main/base/ext/RdExtBase.cpp
c54310595ef30a9673f22b469c41a5fbb0832f03
[]
no_license
operasfantom/rd_cpp
11053df1e8e309db70d72d1167048747caaf2cba
ce38dd043727784901748814c1d40ff65b2e1752
refs/heads/master
2021-07-18T07:47:46.421402
2018-11-14T16:16:34
2018-11-14T16:16:34
140,456,027
2
0
null
null
null
null
UTF-8
C++
false
false
3,182
cpp
// // Created by jetbrains on 24.07.2018. // #include "Lifetime.h" #include "RdPropertyBase.h" #include "RdExtBase.h" #include "Protocol.h" const IProtocol *const RdExtBase::get_protocol() const { return extProtocol ? extProtocol.get() : RdReactiveBase::get_protocol(); } void RdExtBase::init(Lifetime lifetime) const { // Protocol.initializationLogger.traceMe { "binding" } auto parentProtocol = RdReactiveBase::get_protocol(); std::shared_ptr<IWire> parentWire = parentProtocol->wire; // serializersOwner.registry(parentProtocol.serializers); auto sc = parentProtocol->scheduler; extWire->realWire = parentWire.get(); lifetime->bracket( [&]() { extProtocol = std::make_shared<Protocol>(parentProtocol->identity, sc, std::dynamic_pointer_cast<IWire>(extWire)); }, [this]() { extProtocol = nullptr; } ); parentWire->advise(lifetime, this); //it's critical to advise before 'Ready' is sent because we advise on SynchronousScheduler lifetime->bracket( [this, parentWire]() { sendState(*parentWire, ExtState::Ready); }, [this, parentWire]() { sendState(*parentWire, ExtState::Disconnected); } ); //todo make it smarter for (auto const &[name, child] : this->bindableChildren) { bindPolymorphic(*child, lifetime, this, name); } traceMe(Protocol::initializationLogger, "created and bound :: ${printToString()}"); } void RdExtBase::on_wire_received(Buffer buffer) const { ExtState remoteState = buffer.readEnum<ExtState>(); traceMe(logReceived, "remote: " + to_string(remoteState)); switch (remoteState) { case ExtState::Ready : { sendState(*extWire->realWire, ExtState::ReceivedCounterpart); extWire->connected.set(true); break; } case ExtState::ReceivedCounterpart : { extWire->connected.set(true); //don't set anything if already set break; } case ExtState::Disconnected : { extWire->connected.set(false); break; } } int64_t counterpartSerializationHash = buffer.read_pod<int64_t>(); /*if (serializationHash != counterpartSerializationHash) { //need to queue since outOfSyncModels is not synchronized RdReactiveBase::get_protocol()->scheduler->queue([this](){ RdReactiveBase::get_protocol().outOfSyncModels.add(this) }); // error("serializationHash of ext '$location' doesn't match to counterpart: maybe you forgot to generate models?") }*/ } void RdExtBase::sendState(IWire const &wire, RdExtBase::ExtState state) const { wire.send(rdid, [&](Buffer const &buffer) { // logSend.traceMe(state); buffer.writeEnum<ExtState>(state); buffer.write_pod<int64_t>(serializationHash); }); } void RdExtBase::traceMe(const Logger &logger, std::string const &message) const { logger.trace("ext " + location.toString() + " " + rdid.toString() + ":: " + message); }
[ "operasfantom@gmail.com" ]
operasfantom@gmail.com
0fcb76d4b76e147be51dd24556e601c8df73a921
f24fddf2415ed31237068039f9db992832ff0bf7
/lib/DHParam/src/DHParam.h
d51fffbe1cf4010517a12400213e88266f2a49d5
[]
no_license
boernworst/6dof_robot_arm-self
bf93a124efd602ac0aa33baad8499f7eb41a70c9
4e82329e2ea779e7c9cd4b2c9e6e8d745854bfa1
refs/heads/master
2022-11-21T20:50:44.163926
2020-07-15T00:03:49
2020-07-15T00:03:49
279,721,949
0
0
null
null
null
null
UTF-8
C++
false
false
615
h
/*   DHParam.h - Library for implementing Denavit-Hartenberg Parameters.   Created by Nathan Rukavina, July 17, 2017.   Released into the public domain. */ #ifndef DHParam_h #define DHParam_h #include "Arduino.h" class DHParam { public: DHParam(float theta_, float a_, float d_, float alpha_); void getTransformation(float arr[4][4], DHParam from); void setTheta(float theta_); void setA(float a_); void setD(float d_); void setAlpha(float alpha_); float getTheta(); float getA(); float getD(); float getAlpha(); private: float theta; float a; float d; float alpha; }; #endif
[ "basjfellinger@gmail.com" ]
basjfellinger@gmail.com
61021ed6e3f00e2ab524d28a7e9cf1363c2c673e
e969be9b8a0067e6e7a9e84974d79b4aa68f1dec
/code/aoce/media/MediaHelper.hpp
c2bdb459d06811b83670d92b263ed51b4f8da52e
[ "MIT" ]
permissive
sandman555/aoce
479850e2c04505289bab32a2c4ca02d3cdc7dc40
c1895d7ecc784354744886fb6db4174f211d81d1
refs/heads/master
2023-08-15T19:06:57.094702
2021-10-13T15:14:47
2021-10-13T15:14:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
186
hpp
#pragma once #include "../Aoce.hpp" namespace aoce { ACOE_EXPORT MediaSourceType getMediaType(const std::string& str); ACOE_EXPORT std::string getAvformat(const std::string& uri); }
[ "mfjt55@163.com" ]
mfjt55@163.com
c768240383e45bc9d0f47970677b707cf145b666
a90020def1ea505bfb3a2fc152f853997cf5ca4a
/RangeQueries/dynamic_min.cpp
ce095e2a276fefe7c74d4ef90f5671894cb29059
[]
no_license
AYUSHNSUT/CSES
43f9d5d9fb9d027294cac6fb03ee66420462e710
e7cebbb65f8ee6214ca58fa80ec9ea2c9a3bac40
refs/heads/master
2023-05-27T19:08:15.622538
2021-06-07T11:31:16
2021-06-07T11:31:16
296,012,570
0
0
null
null
null
null
UTF-8
C++
false
false
3,877
cpp
#include<bits/stdc++.h> using namespace std; #define DEBUG(x) cerr << '>' << #x << ':' << x << endl; #define REP(i,n) for(int i=0;i<(n);i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) #define all(c) c.begin(),c.end() #define M 1000000007 typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<string, string> pss; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<pii> vii; typedef vector<ll> vl; typedef vector<vl> vvl; #define mp make_pair #define pb push_back inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; } inline int two(int n) { return 1 << n; } inline int test(int n, int b) { return (n>>b)&1; } inline void set_bit(int & n, int b) { n |= two(b); } inline void unset_bit(int & n, int b) { n &= ~two(b); } inline int last_bit(int n) { return n & (-n); } inline int ones(int n) { int res = 0; while(n && ++res) n-=n&(-n); return res; } template<class T> void chmax(T & a, const T & b) { a = max(a, b); } template<class T> void chmin(T & a, const T & b) { a = min(a, b); } #define fast_cin() std::ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// class segmentMin{ ll n; vl t; void makeTree(vl &a , ll v, ll tl , ll tr){ if(tl > tr) return; if(tl == tr){ // DEBUG(v); // DEBUG(tl); // DEBUG(a[tl]); t[v] = a[tl]; return; } ll tm = (tl + tr) / 2; makeTree(a,2*v, tl, tm); makeTree(a,2*v + 1, tm + 1, tr); t[v] = min(t[2*v], t[2*v + 1]); // DEBUG(v); // DEBUG(t[v]); // DEBUG(tl); // DEBUG(tr); } ll findMin(ll v, ll tl , ll tr, ll a, ll b){ if(a>b || tl > b || tr < a){ return LLONG_MAX; } if(a== tl && b == tr){ return t[v]; } ll tm = (tl + tr) / 2; return min(findMin(2*v,tl, tm , a, min(b, tm)),findMin(2*v+1,tm+1, tr , max(a,tm+1), b) ); } void updateNodez(ll v, ll tl, ll tr, ll pos, ll newVal){ if(tl > tr) return; if(tl == tr){ t[v] = newVal; return; } ll tm = (tl + tr) / 2; if(pos <= tm){ updateNodez(2*v, tl, tm, pos,newVal); } else{ updateNodez(2*v + 1, tm + 1, tr, pos,newVal); } t[v] = min(t[2*v], t[2*v+1]); } public: segmentMin(ll n) : n(n){ t.resize(4*n, LLONG_MAX); } void generate(vl &a){ ll v = 1; makeTree(a,v,0,n-1); // REP(i,4*n){ // DEBUG(i); // DEBUG(t[i]); // } } ll getMin(ll a , ll b){ return findMin(1,0,n-1,a,b); } void update(ll pos, ll newVal){ ll tl = 0; ll tr = n-1; updateNodez(1,tl,tr,pos, newVal); } }; void solve(){ ll n ,q; cin >> n>>q; vl a(n); REP(i,n){ cin >> a[i]; // DEBUG(a[i]); } segmentMin S(n); S.generate(a); REP(i,q){ ll a,b,c; cin >> a >> b >> c; if(a==1){ S.update(b-1,c); } else{ cout << S.getMin(b-1,c-1) << "\n"; } } } int main(){ #ifdef mishrable // for getting input from input.txt freopen("input.txt", "r", stdin); // for writing output to output.txt freopen("output.txt", "w", stdout); #endif fast_cin(); int t =1; // cin >> t; while(t--){ solve(); } }
[ "ayushm1906@gmail.com" ]
ayushm1906@gmail.com
66fbcbf45532b22a929c055ba30db2fa70768ea9
9c451121eaa5e0131110ad0b969d75d9e6630adb
/Luogu/P2078 朋友.cpp
4289709871c8953d83508727ad773914feb44b6d
[]
no_license
tokitsu-kaze/ACM-Solved-Problems
69e16c562a1c72f2a0d044edd79c0ab949cc76e3
77af0182401904f8d2f8570578e13d004576ba9e
refs/heads/master
2023-09-01T11:25:12.946806
2023-08-25T03:26:50
2023-08-25T03:26:50
138,472,754
5
1
null
null
null
null
UTF-8
C++
false
false
758
cpp
#include <bits/stdc++.h> using namespace std; const int MAX=1e4+10; struct Disjoint_Set_Union { int pre[MAX],sz[MAX]; void init(int n) { int i; for(i=1;i<=n;i++) { pre[i]=i; sz[i]=1; } } int find(int x) { if(pre[x]!=x) pre[x]=find(pre[x]); return pre[x]; } bool merge(int a,int b) { int ra,rb; ra=find(a); rb=find(b); if(ra!=rb) { pre[ra]=rb; sz[rb]+=sz[ra]; return 1; } return 0; } }da,db; int main() { int n,m,p,q,i,a,b,ra,rb; scanf("%d%d%d%d",&n,&m,&p,&q); da.init(n); db.init(m); while(p--) { scanf("%d%d",&a,&b); da.merge(a,b); } while(q--) { scanf("%d%d",&a,&b); a=-a; b=-b; db.merge(a,b); } ra=da.sz[da.find(1)]; rb=db.sz[db.find(1)]; printf("%d\n",min(ra,rb)); return 0; }
[ "861794979@qq.com" ]
861794979@qq.com
98422d4c86fc485da33d34a7fbb61977824ff427
d3d1429da6d94ec4b3c003db06607bc9daa35804
/vendor/github.com/cockroachdb/c-rocksdb/internal/table/full_filter_block_test.cc
51ce1aaa9970249ae835b5cb3d9bea69e81df421
[ "ISC", "BSD-3-Clause" ]
permissive
zipper-project/zipper
f61a12b60445dfadf5fd73d289ff636ce958ae23
c9d2d861e1b920ed145425e63d019d6870bbe808
refs/heads/master
2021-05-09T14:48:04.286860
2018-05-25T05:52:46
2018-05-25T05:52:46
119,074,801
97
75
ISC
2018-03-01T10:18:22
2018-01-26T16:23:40
Go
UTF-8
C++
false
false
5,736
cc
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "table/full_filter_block.h" #include "rocksdb/filter_policy.h" #include "util/coding.h" #include "util/hash.h" #include "util/logging.h" #include "util/testharness.h" #include "util/testutil.h" namespace rocksdb { class TestFilterBitsBuilder : public FilterBitsBuilder { public: explicit TestFilterBitsBuilder() {} // Add Key to filter virtual void AddKey(const Slice& key) override { hash_entries_.push_back(Hash(key.data(), key.size(), 1)); } // Generate the filter using the keys that are added virtual Slice Finish(std::unique_ptr<const char[]>* buf) override { uint32_t len = static_cast<uint32_t>(hash_entries_.size()) * 4; char* data = new char[len]; for (size_t i = 0; i < hash_entries_.size(); i++) { EncodeFixed32(data + i * 4, hash_entries_[i]); } const char* const_data = data; buf->reset(const_data); return Slice(data, len); } private: std::vector<uint32_t> hash_entries_; }; class TestFilterBitsReader : public FilterBitsReader { public: explicit TestFilterBitsReader(const Slice& contents) : data_(contents.data()), len_(static_cast<uint32_t>(contents.size())) {} virtual bool MayMatch(const Slice& entry) override { uint32_t h = Hash(entry.data(), entry.size(), 1); for (size_t i = 0; i + 4 <= len_; i += 4) { if (h == DecodeFixed32(data_ + i)) { return true; } } return false; } private: const char* data_; uint32_t len_; }; class TestHashFilter : public FilterPolicy { public: virtual const char* Name() const override { return "TestHashFilter"; } virtual void CreateFilter(const Slice* keys, int n, std::string* dst) const override { for (int i = 0; i < n; i++) { uint32_t h = Hash(keys[i].data(), keys[i].size(), 1); PutFixed32(dst, h); } } virtual bool KeyMayMatch(const Slice& key, const Slice& filter) const override { uint32_t h = Hash(key.data(), key.size(), 1); for (unsigned int i = 0; i + 4 <= filter.size(); i += 4) { if (h == DecodeFixed32(filter.data() + i)) { return true; } } return false; } virtual FilterBitsBuilder* GetFilterBitsBuilder() const override { return new TestFilterBitsBuilder(); } virtual FilterBitsReader* GetFilterBitsReader(const Slice& contents) const override { return new TestFilterBitsReader(contents); } }; class PluginFullFilterBlockTest : public testing::Test { public: BlockBasedTableOptions table_options_; PluginFullFilterBlockTest() { table_options_.filter_policy.reset(new TestHashFilter()); } }; TEST_F(PluginFullFilterBlockTest, PluginEmptyBuilder) { FullFilterBlockBuilder builder( nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); Slice block = builder.Finish(); ASSERT_EQ("", EscapeString(block)); FullFilterBlockReader reader( nullptr, true, block, table_options_.filter_policy->GetFilterBitsReader(block), nullptr); // Remain same symantic with blockbased filter ASSERT_TRUE(reader.KeyMayMatch("foo")); } TEST_F(PluginFullFilterBlockTest, PluginSingleChunk) { FullFilterBlockBuilder builder( nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); builder.Add("foo"); builder.Add("bar"); builder.Add("box"); builder.Add("box"); builder.Add("hello"); Slice block = builder.Finish(); FullFilterBlockReader reader( nullptr, true, block, table_options_.filter_policy->GetFilterBitsReader(block), nullptr); ASSERT_TRUE(reader.KeyMayMatch("foo")); ASSERT_TRUE(reader.KeyMayMatch("bar")); ASSERT_TRUE(reader.KeyMayMatch("box")); ASSERT_TRUE(reader.KeyMayMatch("hello")); ASSERT_TRUE(reader.KeyMayMatch("foo")); ASSERT_TRUE(!reader.KeyMayMatch("missing")); ASSERT_TRUE(!reader.KeyMayMatch("other")); } class FullFilterBlockTest : public testing::Test { public: BlockBasedTableOptions table_options_; FullFilterBlockTest() { table_options_.filter_policy.reset(NewBloomFilterPolicy(10, false)); } ~FullFilterBlockTest() {} }; TEST_F(FullFilterBlockTest, EmptyBuilder) { FullFilterBlockBuilder builder( nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); Slice block = builder.Finish(); ASSERT_EQ("", EscapeString(block)); FullFilterBlockReader reader( nullptr, true, block, table_options_.filter_policy->GetFilterBitsReader(block), nullptr); // Remain same symantic with blockbased filter ASSERT_TRUE(reader.KeyMayMatch("foo")); } TEST_F(FullFilterBlockTest, SingleChunk) { FullFilterBlockBuilder builder( nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); builder.Add("foo"); builder.Add("bar"); builder.Add("box"); builder.Add("box"); builder.Add("hello"); Slice block = builder.Finish(); FullFilterBlockReader reader( nullptr, true, block, table_options_.filter_policy->GetFilterBitsReader(block), nullptr); ASSERT_TRUE(reader.KeyMayMatch("foo")); ASSERT_TRUE(reader.KeyMayMatch("bar")); ASSERT_TRUE(reader.KeyMayMatch("box")); ASSERT_TRUE(reader.KeyMayMatch("hello")); ASSERT_TRUE(reader.KeyMayMatch("foo")); ASSERT_TRUE(!reader.KeyMayMatch("missing")); ASSERT_TRUE(!reader.KeyMayMatch("other")); } } // namespace rocksdb int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "2539373634@qq.com" ]
2539373634@qq.com
66ae398629e125081e92336d200710d12dc33613
a0e695b8b8d46dc9615e7314fcc8458a21f2a6ac
/examples/Queue/Queue.ino
35c0f6688c3d597325761b51135526658067216a
[ "MIT" ]
permissive
Floessie/frt
769bf0753120214b69b7828550118f04bd5cf56f
a4278d9bd119834924a3c64edefccbf93266d53b
refs/heads/master
2021-05-11T19:57:14.657162
2020-12-07T17:19:06
2020-12-07T17:19:06
117,427,334
22
9
MIT
2018-02-04T16:29:16
2018-01-14T12:17:24
C++
UTF-8
C++
false
false
3,056
ino
#include <frt.h> namespace { // This is the data shared between producer and consumer task struct Data { int value; unsigned long timestamp; }; // This is our queue, which can store 10 elements of Data frt::Queue<Data, 10> queue; // This is the mutex to protect our output from getting mixed up frt::Mutex serial_mutex; // The producer task class ProducerTask final : public frt::Task<ProducerTask, 100> { public: bool run() { // We push the analog value and the current timestamp queue.push({analogRead(0), millis()}); // Note that there is no msleep() here, so this task runs // "full throttle" and will only yield if either preempted // by a higher priority task on the next scheduler tick or // the queue being full. return true; } }; // The consumer task class ConsumerTask final : public frt::Task<ConsumerTask, 150> { public: bool run() { Data data; // Get the (possibly old) data from the queue queue.pop(data); // This variant of pop() will wait forever for data to // arrive. If you ever plan to stop this task, use a // variant with timeout, so run() is left once in a while. const unsigned long now = millis(); // If you dare, try to remove the mutex and see what happens serial_mutex.lock(); Serial.print(F("Got value ")); Serial.print(data.value); Serial.print(F(" at ")); Serial.print(now); Serial.print(F(" which was queued at ")); Serial.println(data.timestamp); serial_mutex.unlock(); // Again, no msleep() here return true; } }; // Instances of the above tasks ProducerTask producer_task; ConsumerTask consumer_task; // The high priority monitoring task class MonitoringTask final : public frt::Task<MonitoringTask> { public: bool run() { msleep(1000, remainder); serial_mutex.lock(); Serial.print(F("Queue fill level: ")); Serial.println(queue.getFillLevel()); Serial.print(F("Producer stack used: ")); Serial.println(producer_task.getUsedStackSize()); Serial.print(F("Consumer stack used: ")); Serial.println(consumer_task.getUsedStackSize()); serial_mutex.unlock(); return true; } private: unsigned int remainder = 0; }; // Instance of the above task MonitoringTask monitoring_task; } void setup() { Serial.begin(9600); while (!Serial); monitoring_task.start(3); // As the consumer task is started with lower priority first, the // moment the producer starts, it will fill the queue completely // and stall. The consumer will wake and pop one element, then the // producer will kick in again filling the queue (only one item). // Only then the consumer will print out its line. It continues into // run() and pops one item, and so on. // You should play a bit with the start sequence and priorities here // to get a feeling on what's going on. consumer_task.start(1); producer_task.start(2); } void loop() { // As both producer and consumer are always runnable, you will // never see the next line. Serial.println(F("IDLE")); }
[ "floessie.mail@gmail.com" ]
floessie.mail@gmail.com
9c50ac98e7017f7ac0bc37473c505fbd5428448b
43a54d76227b48d851a11cc30bbe4212f59e1154
/cwp/include/tencentcloud/cwp/v20180228/model/DescribeReverseShellEventsRequest.h
f59f48d117fea24737d69dff064c94a32a067d56
[ "Apache-2.0" ]
permissive
make1122/tencentcloud-sdk-cpp
175ce4d143c90d7ea06f2034dabdb348697a6c1c
2af6954b2ee6c9c9f61489472b800c8ce00fb949
refs/heads/master
2023-06-04T03:18:47.169750
2021-06-18T03:00:01
2021-06-18T03:00:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,692
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_CWP_V20180228_MODEL_DESCRIBEREVERSESHELLEVENTSREQUEST_H_ #define TENCENTCLOUD_CWP_V20180228_MODEL_DESCRIBEREVERSESHELLEVENTSREQUEST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/cwp/v20180228/model/Filter.h> namespace TencentCloud { namespace Cwp { namespace V20180228 { namespace Model { /** * DescribeReverseShellEvents请求参数结构体 */ class DescribeReverseShellEventsRequest : public AbstractModel { public: DescribeReverseShellEventsRequest(); ~DescribeReverseShellEventsRequest() = default; std::string ToJsonString() const; /** * 获取返回数量,默认为10,最大值为100。 * @return Limit 返回数量,默认为10,最大值为100。 */ uint64_t GetLimit() const; /** * 设置返回数量,默认为10,最大值为100。 * @param Limit 返回数量,默认为10,最大值为100。 */ void SetLimit(const uint64_t& _limit); /** * 判断参数 Limit 是否已赋值 * @return Limit 是否已赋值 */ bool LimitHasBeenSet() const; /** * 获取偏移量,默认为0。 * @return Offset 偏移量,默认为0。 */ uint64_t GetOffset() const; /** * 设置偏移量,默认为0。 * @param Offset 偏移量,默认为0。 */ void SetOffset(const uint64_t& _offset); /** * 判断参数 Offset 是否已赋值 * @return Offset 是否已赋值 */ bool OffsetHasBeenSet() const; /** * 获取过滤条件。 <li>Keywords - String - 是否必填:否 - 关键字(主机内网IP|进程名)</li> * @return Filters 过滤条件。 <li>Keywords - String - 是否必填:否 - 关键字(主机内网IP|进程名)</li> */ std::vector<Filter> GetFilters() const; /** * 设置过滤条件。 <li>Keywords - String - 是否必填:否 - 关键字(主机内网IP|进程名)</li> * @param Filters 过滤条件。 <li>Keywords - String - 是否必填:否 - 关键字(主机内网IP|进程名)</li> */ void SetFilters(const std::vector<Filter>& _filters); /** * 判断参数 Filters 是否已赋值 * @return Filters 是否已赋值 */ bool FiltersHasBeenSet() const; private: /** * 返回数量,默认为10,最大值为100。 */ uint64_t m_limit; bool m_limitHasBeenSet; /** * 偏移量,默认为0。 */ uint64_t m_offset; bool m_offsetHasBeenSet; /** * 过滤条件。 <li>Keywords - String - 是否必填:否 - 关键字(主机内网IP|进程名)</li> */ std::vector<Filter> m_filters; bool m_filtersHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CWP_V20180228_MODEL_DESCRIBEREVERSESHELLEVENTSREQUEST_H_
[ "tencentcloudapi@tenent.com" ]
tencentcloudapi@tenent.com
885c09bc76da6340b35dfa0685075ef0a934de0e
e95eabe61b5b197a57779e7ad4e6acfbad9b7e39
/onethread/PageStorage.cpp
8c5bad61cab36d02a25058d99ce5c0146212e2c4
[]
no_license
MillQK/OS-proxy
3ebbfe31490286c29d9e7f14a8bf31435d6040be
6829d317f4aad96a7bad2e44ea18e8fb87995d17
refs/heads/master
2021-01-20T14:43:32.523031
2017-02-22T07:26:57
2017-02-22T07:26:57
82,773,017
0
0
null
null
null
null
UTF-8
C++
false
false
707
cpp
// // Created by Nikita on 13.12.15. // #include <stdlib.h> #include "PageStorage.h" PageStorage::PageStorage(){ full = false; } void PageStorage::addItem(char * buf, int size) { pagePieces.push_back(std::make_pair(buf, size)); } unsigned long PageStorage::size() { return pagePieces.size(); } std::pair<char *, int> PageStorage::getItem(unsigned long pos) { return pagePieces.at(pos); } bool PageStorage::isFull() const { return full; } void PageStorage::setFull(bool full) { PageStorage::full = full; } void PageStorage::deleteAll(){ for(unsigned long i=0; i<pagePieces.size(); i++){ free(pagePieces.at(i).first); } pagePieces.clear(); }
[ "noreply@github.com" ]
MillQK.noreply@github.com
cd87fa7c5a10b5259a6f5b992040276243f0e0e0
bc8848baeada90d427fb4130099abf11e38fa12c
/SSORT
70c111f2dcf7cb195ebc068c0580f45781c17d3a
[]
no_license
atharva-sarage/Codechef-Competitive-Programming
5e2699928bfca7190bca225ee69a731f058c3619
39e880ad877422f66272d1eb59dab77e9b423f1b
refs/heads/master
2020-06-09T21:57:38.731845
2019-07-17T06:14:35
2019-07-17T06:14:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,060
#include<bits/stdc++.h> #define mx 1005 using namespace std; int n,sum,min1,final,size; int visited[mx]; int par[mx]; int a[mx],b[mx],c[mx]; vector <int> vec; void dfs(int u,int parent) { visited[u]=true; par[u]=parent; if(visited[b[u]]) { int v=b[u]; sum=v; min1=v; while(u!=v) { size++; sum+=u; min1=min(min1,u); u=par[u]; } size++; return; } else dfs(b[u],u); } void DFS() { for(int i=1;i<=n;i++) { if(!visited[a[i]]) { sum=0; size=0; dfs(a[i],-1); //cout<<sum<<endl; if(size==1) { continue; } final+=(sum+min1*(size-2)); if(c[1]-min1*size+3*min1+c[1]*size<0) final+=c[1]-min1*size+3*min1+c[1]*size; } } } int main() { cin>>n; int count=1; while(n!=0) { final=0; memset(visited,false,sizeof(visited)); memset(b,-1,sizeof(b)); for(int i=1;i<=n;i++) { cin>>a[i]; c[i]=a[i]; } sort(c+1,c+n+1); for(int i=1;i<=n;i++) { b[c[i]]=a[i]; } //cout<<b[1]<<" "<<b[2]<<" "<<b[4]<<endl; DFS(); cout<<"Case "<<count<<":"<<" "<<final<<endl; cin>>n; count++; } }
[ "atharva.sarage@gmail.com" ]
atharva.sarage@gmail.com
9aa174e6ba12c2f7e959c6820bdd66ead7fb6e65
c67e2f5a8c34025762ebcc1d2c9a1c6201efc4a2
/displace.cpp
8eae8a73d4d00ebcbc0a8b63ae81976a60a4f28c
[]
no_license
cmwilli5/Project_Gunner
0fa0e8dec4abba0947fc1c4f7d89ae17e6762f04
ce3b3ea3b2b04298cf0205e7b8270efd53b8362f
refs/heads/master
2020-04-13T21:55:33.395442
2017-03-23T02:03:37
2017-03-23T02:03:37
50,155,647
0
0
null
null
null
null
UTF-8
C++
false
false
568
cpp
#include "displace.h" #include <iostream> #include <locale> const std::string Position::name{"position"}; template<> Position buildFromLua<Position>(sol::object& obj) { Position p; sol::table tbl = obj; p.pastPosX = p.posX = tbl["x"].get_or(0.0f); p.pastPosY = p.posY = tbl["y"].get_or(0.0f); return p; } const std::string Velocity::name{"velocity"}; template<> Velocity buildFromLua<Velocity>(sol::object& obj) { Velocity v; sol::table tbl = obj; v.velX = tbl["x"].get_or(0.0f); v.velY = tbl["y"].get_or(0.0f); return v; }
[ "corithianmw96@gmail.com" ]
corithianmw96@gmail.com
f4e4e6866ad32c77fcd24698c34aa8c8adcd6d08
2f10f807d3307b83293a521da600c02623cdda82
/deps/boost/win/debug/include/boost/heap/heap_concepts.hpp
dfd5fca24f6bda5779f159da7e967cdc05f5f6e6
[]
no_license
xpierrohk/dpt-rp1-cpp
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
refs/heads/master
2021-05-23T08:19:48.823198
2019-07-26T17:35:28
2019-07-26T17:35:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:d4d5547c28eec7025bf6170456268dc8da9585c1ae8006e3832c2885747b710c size 2592
[ "YLiLarry@gmail.com" ]
YLiLarry@gmail.com
2e6a6df95ab669b9d9de0222e79656fe48838c8b
a5c2bcbd0298b743ef86b046a37e1c303dc7ade8
/C++/Inheritance/00_Inheritance_Introduction.cpp
b75b20bcefeb2a75560d4ef6d09f34ebdff4a393
[]
no_license
lvoneduval/hackerrank
911c140d9e25ef39b7cfb5c3e8afb1e6634bdd33
be0ae48282d71fbac876962c9b0a636621615aa2
refs/heads/master
2021-09-14T09:37:52.676172
2018-05-11T12:11:59
2018-05-11T12:11:59
111,906,441
0
0
null
null
null
null
UTF-8
C++
false
false
608
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; class Triangle{ public: void triangle(){ cout<<"I am a triangle\n"; } }; class Isosceles : public Triangle{ public: void description() { cout << "In an isosceles triangle two sides are equal\n"; } void isosceles(){ cout<<"I am an isosceles triangle\n"; } //Write your code here. }; int main(){ Isosceles isc; isc.isosceles(); isc.description(); isc.triangle(); return 0; }
[ "lionel.duval@etu.umontpellier.fr" ]
lionel.duval@etu.umontpellier.fr
dde757ce8731636e04b8071998f5a398e6887e6e
3839a4abf93aba83d8e09a173480a3e4dd1f8246
/Morse.cpp
808639f172f640aaed330ed2a6fa073bc9f2b547
[]
no_license
MNWHN/homework
833ec372db3bec9978947d88edb7ad436669de67
b0a51bb52ad2232983dae0fc0bee2319e9145a81
refs/heads/master
2020-06-14T17:16:13.976181
2019-07-06T03:10:35
2019-07-06T03:10:35
195,069,622
1
0
null
null
null
null
UTF-8
C++
false
false
496
cpp
#include "Arduino.h" #include "Morse.h" Morse::Morse(int pin) { pinMode(pin,OUTPUT); _pin=pin; _delaytime=250; } void Morse::dot() { digitalWrite(_pin,HIGH); delay(_delaytime); digitalWrite(_pin,LOW); delay(_delaytime); } void Morse::dash() { digitalWrite(_pin,HIGH); delay(_delaytime*4); digitalWrite(_pin,LOW); delay(_delaytime); } void Morse::c_space() { digitalWrite(_pin,LOW); delay(_delaytime*3); } void Morse::w_space() { digitalWrite(_pin,LOW); delay(_delaytime*7); }
[ "noreply@github.com" ]
MNWHN.noreply@github.com
f055619d38239c61275956bb79e17faa1dd6723a
5f17573507d160aa087b02d0f00d97be7a603f6c
/308B.cpp
3a0a353116310f25e2f366d4f7fb331b433c31bd
[]
no_license
nishnik/Competitive-Programming
33590ea882e449947befc36594fd20c720c05049
cab12301ca7343b6e5f4464fcfbb84b437379da8
refs/heads/master
2021-01-10T05:43:44.252506
2016-02-23T14:14:03
2016-02-23T14:14:03
52,363,354
0
0
null
null
null
null
UTF-8
C++
false
false
1,464
cpp
#include <bits/stdc++.h> //usage getline(cin,str_name); #define rep(i, n) for(__typeof(n) i = 0; i < (n); i++) #define rrep(i, n) for(__typeof(n) i = (n) - 1; i >= 0; --i) #define rep1(i, n) for(__typeof(n) i = 1; i <= (n); i++) #define FOR(i, a, b) for(__typeof(b) i = (a); i <= (b); i++) #define forstl(i, s) for (__typeof ((s).end ()) i = (s).begin (); i != (s).end (); ++i) #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define ll long long #define vi vector<int> #define vvi vector<vi > #define vl vector<long> #define vvl vector<vl > #define vll vector<long long> #define vvll vector<vll > /* Usage: Just create an instance of it at the start of the block of which you want to measure running time. Reliable up to millisecond scale. You don't need to do anything else, even works with freopen. */ class TimeTracker { clock_t start, end; public: TimeTracker() { start = clock(); } ~TimeTracker() { end = clock(); //fprintf(stderr, "%.3lf s\n", (double)(end - start) / CLOCKS_PER_SEC); } }; using namespace std; int main() { ios::sync_with_stdio(false); //cin.tie(0);cout.tie(0); long n; cin>>n; long long sum=0; //cout<<std::fixed<<(n+1)*floorl(log10(10*n))-(pow(10,floorl(log10(10*n)))-1)/9<<std::fixed; long long a=1,b=9; while(n>b) { n-=b; sum+=b*a; a++; b*=10; } sum+=n*a; cout<<sum; } //
[ "nishantiam@gmail.com" ]
nishantiam@gmail.com
585b6d7592c1cc4b1d7a36ab145d9cc3280f39f4
4e528dddd0e5d2131fbe673428046e22930348e2
/Engine/Source/Math/ColorHSV.cpp
93c60d7ac1a36be2f4e75ee62c0caafa710473d0
[]
no_license
ConductorRU/Chronopolis
1da11fd782339dd783ecb443ddd0fddf05b7bba5
6ec21a8463a54200bbe937c48fabf01317455261
refs/heads/master
2020-06-24T21:51:48.595659
2018-05-28T11:02:17
2018-05-28T11:02:17
74,618,149
0
0
null
null
null
null
UTF-8
C++
false
false
658
cpp
#include "stdafx.h" #include "ColorRGB.h" #include "ColorHSV.h" namespace DEN { ColorHSV::ColorHSV(const ColorRGB &col) { float r = float(col.r) / 255.0f; float g = float(col.g) / 255.0f; float b = float(col.b) / 255.0f; float cMax = max(max(r, g), b); float cMin = min(min(r, g), b); float del = cMax - cMin; h = 0.0f; if(del > 0.000001f) { if(r >= g && r >= b) h = 60.0f*((g - b) / del); else if(g >= r && g >= b) h = 60.0f*((b - r) / del + 2.0f); else h = 60.0f*((r - g) / del + 4.0f); h = h - float((int(h) / 360) * 360); } v = cMax; s = del; if(del > 0.0f) s /= v; a = float(col.a) / 255.0f; } }
[ "draaks@yandex.ru" ]
draaks@yandex.ru
4e1aa8ccfea39a755a7fbb96f9f6a59ec8edbc3e
b3cf6ac1b9946a0399887bb8875b0c1bf943f9d6
/AudioEvent.cpp
92638ef2a395150c3ebed519f0c52b78dfc96534
[ "MIT" ]
permissive
rogerbusquets97/3D-Engine
19e30b137287eedf1e48ac4dadde63532d4a048d
0995a916664da9950b6d6a6edc34acf64c839057
refs/heads/master
2021-09-05T01:28:37.442597
2017-12-17T12:22:54
2018-01-23T11:14:42
103,663,586
0
1
null
2017-11-12T21:20:44
2017-09-15T14:00:51
C
UTF-8
C++
false
false
897
cpp
#include "AudioEvent.h" #include "ModuleImGui.h" #include "AudioSource.h" AudioEvent::AudioEvent() { } AudioEvent::~AudioEvent() { } void AudioEvent::UnLoad() { } void AudioEvent::Load(JSON_File * file, SoundBank * p, int id) { bool succes = file->MoveToInsideArray("IncludedEvents", id); if (succes) { LOG_OUT("Can be readed"); } this->id = file->GetNumber("Id"); this->name = file->GetString("Name"); this->parent = p; } void AudioEvent::UIDraw(AudioSource* parent ) { if (ImGui::CollapsingHeader(name.c_str())) { if (ImGui::Button("Play")) { //play event parent->obj->PlayEvent(name.c_str()); } ImGui::SameLine(); if (ImGui::Button("Stop")) { AK::SoundEngine::ExecuteActionOnEvent(name.c_str(), AK::SoundEngine::AkActionOnEventType::AkActionOnEventType_Pause); } ImGui::SameLine(); if (ImGui::Button("Send")) { parent->SendEvent(name.c_str()); } } }
[ "duranbusquetsroger@gmail.com" ]
duranbusquetsroger@gmail.com
910e8dd8ebca3b32a06c7ccc82355b0e3b611595
7d047b3755c8f1e81b1473c2d89c6741cdc55835
/Search & Sort/Merge_Sort.cpp
978f4e2bdea10eb14a1714e1940f9b689546371c
[ "MIT" ]
permissive
yashika66011/Daily-DSA-Coding
f44b4076ed9ce1ce6ee99dcd655ee40cb19bb366
af8dddb0e062abe8576b390e5d338aaf3e598c29
refs/heads/main
2023-07-13T02:51:45.657529
2021-08-18T16:23:27
2021-08-18T16:23:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,337
cpp
#include<iostream> #include<algorithm> using namespace std; int * mergeTwoArrays(int as[], int bs[]) { int *a = as; int *b = bs; int n = sizeof(a)/sizeof(a[0]); int m = sizeof(a)/sizeof(a[0]); int *c = new int(n+m); int k = 0; for(int i=0, j=0; i<n && j<m;) { if(a[i] < b[j]) c[k++] = a[i++]; else if(a[i] > b[j]) c[k++] = b[j++]; else { c[k++] = a[i++]; c[k++] = b[j++]; } } if(n < m) { for(int i = n-1; i<m;) c[k++] = b[i++]; } else { for(int i = m-1; i<n;) c[k++] = a[i++]; } return c; } int * mergeSort(int arr[], int start, int end) { if(start == end) { int *a = new int(1); a[0] = start; return a; } int mid = (start + end)/2; int *f1 = mergeSort(arr, start, mid); int *f2 = mergeSort(arr, mid+1, end); int *f3 = mergeTwoArrays(f1, f2); return f3; } void printArray(int arr[], int n) { for(int i=0; i<n; i++) cout<<arr[i]<<" "; } int main() { int arr[] = {7, 4, 1, 3, 6, 8, 2, 5}; int n = sizeof(arr)/sizeof(arr[0]); cout<<"Array: "; printArray(arr, n); // mergeSort(arr, 0, n-1); cout<<"\nSorted Array: "; printArray(mergeSort(arr, 0, n-1), n); return 0; }
[ "sethidaksh02@gmail.com" ]
sethidaksh02@gmail.com
1ae15738a4b05f9b0f772df3c61a8b8fc02c31b6
5159d50078fa2945d027050a5bcd016228bb89b8
/algo2.cpp
7c640f4731fab0dd609281e8bd6eac02712af579
[]
no_license
maniteja123/ComputerGraphics
2dacf7668e27139ddc35751b2e5de7231f1271a3
52b42cf9fa58ffc48dae1cc61830bf312583043b
refs/heads/master
2020-12-25T22:20:31.646255
2016-01-01T20:20:57
2016-01-01T20:20:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,924
cpp
#include <stdio.h> #include <GL/gl.h> #include <GL/glut.h> #include "generate_tree.h" #include "circle.h" #include "line.h" const double density = 1.0; const int maxheight = 4; const int XJUMP = 20; const int YJUMP = 50; const int R = 5; const int YMAX = 700; const int WMIN = 0; const int WMAX = 700; int x = 1; pair < Node*, pair <int, int> > Tree; void Fetch(Node* root) { /* This extra pass is an inorder traversal to store the x since drawing a line would be different for left and right children. */ if (root == NULL) return; Fetch(root->left); root->x = x++; Fetch(root->right); } void Draw(Node* root) { /* Inorder traversal to draw the tree */ if (root == NULL) return; Draw(root->left); int fromx = root->x * XJUMP; int fromy = WMAX - 10 - YJUMP * root->depth; midpointcircle(R, fromx, fromy, WMIN, WMAX); if (root != Tree.first) { int tox = root->parent->x * XJUMP; int toy = WMAX - 10 - YJUMP * root->parent->depth; drawline(fromx, fromy, tox, toy, WMIN, WMAX); } Draw(root->right); } void display(void) { glClear (GL_COLOR_BUFFER_BIT); glColor3f (1.0, 1.0, 1.0); drawaxes(WMIN, WMAX, 100,10); Draw(Tree.first); //midpointcircle(10, 100, 100 , 0, WMAX); //drawline(10, 40, 30, 100, 0, 200); glFlush (); } void init (void) { glClearColor (0.0, 0.0, 0.0, 0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); } int main(int argc, char** argv) { Tree = generate(density, maxheight); Fetch(Tree.first); glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (WMAX, WMAX); glutInitWindowPosition (100, 100); glutCreateWindow ("TREE DRAWING ASSIGNMENT 1 ALGO 2"); init (); glutDisplayFunc(display); glutMainLoop(); return 0; /* ISO C requires main to return int. */ }
[ "manitejanmt@gmail.com" ]
manitejanmt@gmail.com
824d7ebfc7b629205e64a97797e4900034fc4d74
057c525d6fbff928fc0cb0cd6b2930e9494b5d4b
/training-data/cpp/76-SoXtComponent.c++
579cbc3f629de452b1ec75a072e26b2580b9cbaf
[]
no_license
uk-gov-mirror/ukwa.text-id
0931742d1f2df3091ac52eee6160c177ea98180d
5f3dcc6436bc46dedb375b37e3fd51c1c0d9b45b
refs/heads/master
2022-02-26T15:32:15.901527
2019-11-19T16:36:06
2019-11-19T16:36:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,656
/*N *N * Aa (A) 0 Aa Aa, Aa. Aa Aa Aa. N *N * Aa a a a a; a a a a a/aN * a a a a a a a A Aa Aa AaN * Aa a a a a Aa Aa Aa; aN * a 0.0 a a Aa, a (a a a) a a a.N *N * Aa a a a a a a a a a a a,N * a A A A; a a a a a aN * A a A A A A A. Aa a AN * Aa Aa Aa Aa a a a.N *N * Aa, a a a a a a a a a aN * a a a a a a a a a a aN * a a a. Aa a a a, a a aN * a, a a a a a a. Aa a, aN * a, a a a a a a a a a a aN * a a, a a a a a.N * N * Aa a a a a a a a A Aa Aa AaN * Aa a a a a; a a, a a a Aa AaN * Aa, Aa., 0 Aa Aa, Aa 0, Aa, A 0-0 AN *N * Aa a: Aa Aa, Aa., 0 Aa Aa,N * Aa Aa, A 0, a:N * N * a://a.a.a N * N * Aa a a a a a, a: N * N * a://a.a.a/a/AaAa/AaAa/N *N */N N /*N * Aa (A) 0-0 Aa Aa, Aa.N *N _______________________________________________________________________N ______________ A A A A A A A A A A A A A A A A A A . ____________N |N | $Aa: 0.0 $N |N | Aa:N | AaAaAaN |N | Aa(a): Aa Aa, Aa AaN |N ______________ A A A A A A A A A A A A A A A A A A . ____________N _______________________________________________________________________N */N #a <Aa/AaAa.a>N #a <Aa/a/AaAaAa.a>N #a <Aa/Aa/AaAaAa.a>N #a <Aa/Aa/AaAa.a>N N #a <Aa/a/AaAaAa.a>N N #a <a.a>N #a <a.a> // a a() a a()N #a <a.a> // a a()N #a <a.a> // a a() a a()N N #a <A0/Aa.a>N #a <A0/Aa.a>N #a <A0/AaAa.a>N N #a <Aa/Aa.a>N #a <Aa/AaAa.a>N #a <Aa/AaA.a>N #a <Aa/Aa.a>N N #a <Aa/a/AaA.a>N N N a a *aAaAa = "Aa Aa Aa Aa";N a a *aAaAa = "Aa Aa Aa a a.";N a a *aAaAa = "a a a a a a.";N a a *aAaAa = "AaAaAa";N N // a aN AaAa *AaAaAa::aAa = A;N N ////////////////////////////////////////////////////////////////////////N //N // AaN //N AaAaAa::AaAaAa(N Aa a,N a a *a, N AaAa aAaAa)N //N ////////////////////////////////////////////////////////////////////////N {N #a AN // a a Aa a aN a (AaAa::aAa() == A) {N AaAaAa::a("AaAaAa::AaAaAa",N "AaAa::aAa() a a A Aa. Aa a a a AaAa::a() a.");N a;N }N #aN N a (aAa == A)N aAa = a AaAa;N N aAaAa(aAaAa);N a (a != A)N _a = a(a);N a _a = A;N N aAa = A; // a a A a a a a aN a = A;N aAa = A;N a.aAa(0, 0);N N // Aa a a a a a aAaAa()N _aAa = A;N N // a a a a a aN aAa = (a == A || !aAaAa);N aAaAa = (aAa || (a != A && AaAaAa(a)));N a (aAa) {N Aa aAa = (a != A) ? a : AaAa::aAaAaAa();N aAa = AaAaAaAa(N aAaAa(),N aAaAaAaAa, N aAa,N A, 0);N }N a aAa = a;N N // a'a a a a a a a a, aN // a a a a a a a a aN // a() a a (a a a a a a aN // a a a)N a (aAaAa) {N AaAaAaAa(aAa, AaAaAa, AaA_A, A);N Aa aAaAa = AaAaAa(AaAa(aAa),N "A_A_A", Aa);N AaAaAaAa(aAa, aAaAa, N (AaAaAa) AaAaAa::aAaAaA,N (AaAa) a);N }N N // a a (a a a a a a a a)N aAa = A;N aAa = A;N AaAa = AaAaAa(AaAa::aAaAa(aAa));N aAa = A; // a a aN aAaAa = A;N }N N ////////////////////////////////////////////////////////////////////////N //N // AaN //N AaAaAa::~AaAaAa()N //N ////////////////////////////////////////////////////////////////////////N {N // Aa a a a a a a a a.N // Aa, a a a a a a a a a a a a.N a (_aAa != A) {N AaAaAa(_aAa, AaAaAa,N AaAaAa::aAaA, (AaAa) a);N N AaAaAaAa(_aAa, AaAaAa, A,N (AaAaAa) AaAaAa::aAaAaA,N (AaAa) a);N N Aa aAa = AaAa::aAaAa(_aAa);N a ((aAa != A) && (aAa != _aAa))N AaAaAaAa(aAa, AaAaAa, A,N (AaAaAa) AaAaAa::aAaAaA,N (AaAa) a);N N a (aAaAa && (aAa != A)) {N Aa aAaAa = AaAaAa(AaAa(aAa),N "A_A_A", Aa);N AaAaAaAa(aAa, aAaAa, N (AaAaAa) AaAaAa::aAaAaA,N (AaAa) a);N }N }N N // Aa a a a.N a (aAaAa() != A && aAa)N AaAaAa(aAa);N a a (_aAa != A)N AaAaAa(_aAa);N N a (_a != A) a(_a);N a (a != A) a(a);N a (aAa != A) a(aAa);N N a aAa;N }N N ////////////////////////////////////////////////////////////////////////N //N // Aa a a a a a a a a.N //N AaAaN AaAaAa::aAa()N //N ////////////////////////////////////////////////////////////////////////N {N aAaAaAa();N N a aAa;N }N N ////////////////////////////////////////////////////////////////////////N //N // a a a a a a a a a a, a aN // a a a a a a a.N //N aN AaAaAa::aAaAaAa()N //N ////////////////////////////////////////////////////////////////////////N {N AaAa aAa = aAa;N N // a a a a a a a a (a a A'A aN // a a a a AaAaAa(a) - aN // a a() a a a.N aAa = (AaAa && aAa && _aAa N && AaAa(_aAa));N N a (aAa != aAa && aAa)N aAa->aAa((a *)(a a)aAa); N }N N ////////////////////////////////////////////////////////////////////////N //N // a a a a a a a a a a a aN //N aN AaAaAa::aAaAaAa(N AaAaAaAaA *a, a *aAa)N //N ////////////////////////////////////////////////////////////////////////N {N a (aAa == A)N aAa = a AaAaAa;N N aAa->aAa((AaAaAaA *) a, aAa);N }N N ////////////////////////////////////////////////////////////////////////N //N // a a a a a a a a a a a aN //N aN AaAaAa::aAaAaAa(N AaAaAaAaA *a, a *aAa)N //N ////////////////////////////////////////////////////////////////////////N {N a (aAa == A)N a;N N aAa->aAa((AaAaAaA *) a, aAa);N }N N ////////////////////////////////////////////////////////////////////////N //N // Aa a a a a a a a a.N //N aN AaAaAa::aAaAa(Aa a)N //N ////////////////////////////////////////////////////////////////////////N { N _aAa = a;N N // Aa a a a a a a a a aN AaAaAa (_aAa, AaAaAa,N AaAaAa::aAaA, (AaAa) a );N N // a a a a a a a/a aN // a a a.N AaAaAaAa(_aAa, AaAaAa, A,N (AaAaAa) AaAaAa::aAaAaA,N (AaAa) a);N N Aa aAa = AaAa::aAaAa(_aAa);N a ((aAa != A) && (aAa != _aAa))N AaAaAaAa(aAa, AaAaAa, A,N (AaAaAa) AaAaAa::aAaAaA,N (AaAa) a);N }N N ////////////////////////////////////////////////////////////////////////N //N // a a a a aN //N ////////////////////////////////////////////////////////////////////////N N a a *N AaAaAa::aAaAaAa() aN { a aAaAa; } // a a a a aN N a a *N AaAaAa::aAaAa() aN { a "Aa Aa"; }N N a a *N AaAaAa::aAaAaAa() aN { a "Aa Aa"; }N N ////////////////////////////////////////////////////////////////////////N //N // Aa a a a a a a a a (a).N //N // a aN //N aN AaAaAa::aAaAa()N //N ////////////////////////////////////////////////////////////////////////N {N a (aAaAa) {N N // a a a a a a a a a a a a aN a (a == A)N a = a(aAaAa());N a (aAa == A)N aAa = a(aAaAaAa());N AaAaAaAa(aAa,N AaAa, a, AaAaAa, aAa, A);N }N }N N ////////////////////////////////////////////////////////////////////////N //N // Aa a a a a.N //N // Aa: aN aN AaAaAa::aAa(a AaAa0a &aAa)N //N ////////////////////////////////////////////////////////////////////////N {N a (aAaAa() != A)N AaAa::aAaAa(aAa, aAa);N a a (_aAa != A)N AaAa::aAaAa(_aAa, aAa);N N // a a a a aN a = aAa;N }N N ////////////////////////////////////////////////////////////////////////N //N // Aa a a a a.N //N // Aa: aN AaAa0aN AaAaAa::aAa()N //N ////////////////////////////////////////////////////////////////////////N {N // Aa a a a a a a a, a a a a aN // a a.N a (aAaAa() != A)N a = AaAa::aAaAa(aAa);N a a (_aAa != A)N a = AaAa::aAaAa(_aAa);N N a a;N }N N ////////////////////////////////////////////////////////////////////////N //N // a a a a a a a a a a a aN //N aN AaAaAa::aAa(a a *aAa)N //N ////////////////////////////////////////////////////////////////////////N {N a (a != A) a(a);N a = (aAa != A) ? a(aAa) : A;N N a (a != A && _aAa != A && AaAaAa(AaAa(_aAa)))N AaAaAaAa(AaAa(_aAa), AaAa, a, A);N }N N ////////////////////////////////////////////////////////////////////////N //N // a a a a a a a a a a a a aN //N aN AaAaAa::aAaAa(a a *aAa)N //N ////////////////////////////////////////////////////////////////////////N {N a (aAa != A) a(aAa);N aAa = (aAa != A) ? a(aAa) : A;N N a (aAa != A && _aAa != A && AaAaAa(AaAa(_aAa)))N AaAaAaAa(AaAa(_aAa), AaAaAa, aAa, A);N }N N ////////////////////////////////////////////////////////////////////////N //N // a - a a a.N //N aN AaAaAa::a()N //N ////////////////////////////////////////////////////////////////////////N {N // Aa a a!N AaAa::a(_aAa);N N // Aa a a a a a a.N a (aAaAa && aAa)N AaAa::a(aAa);N }N N ////////////////////////////////////////////////////////////////////////N //N // a - a a a.N //N aN AaAaAa::a()N //N ////////////////////////////////////////////////////////////////////////N {N #a 0N // a a a a a - a a a a a aN // a a a a a a a a a'a a a.N // a a a a a a a a a N // a a a, a a a a a...N N // a a a a a a, a a....N a (! aAa())N a;N #aN N a (aAaAa) {N // a a a a a a a a aN // a a a a a a a a a.N a (AaAa(aAa)) {N a a, a;N AaAaAaAa(aAa, AaAa, &a, AaAa, &a, A);N AaAa a;N a.a = Aa;N a.a = a;N a.a = a;N AaAaAa(AaAa(aAa), AaAa(aAa), &a);N }N N AaAa::a(aAa); // a a AaAa() (a a)N }N aN AaAa::a(aAa()); // a a AaAaAa() (a a)N }N N ////////////////////////////////////////////////////////////////////////N //N // Aa:N // Aa() a a a a a a a, a aN // a a a (a a a)N //N // Aa: a aN //N aN AaAaAa::aAaAa()N //N ////////////////////////////////////////////////////////////////////////N {N a (aAa == AaAa::aAaAaAa())N a(0);N aN a();N }N N ////////////////////////////////////////////////////////////////////////N //N // Aa a a a a a, a A a a a a a AaAaAa.N //N // Aa: a, aN //N AaAaAa *N AaAaAa::aAa(Aa a)N //N ////////////////////////////////////////////////////////////////////////N {N a (a == A)N a A;N N // a a a a a a a aN // a a 'a', a a 'a'.N a *a = A;N AaAaAa::aAa->a((a a) a, a);N N a (AaAaAa *) a;N }N N N ////////////////////////////////////////////////////////////////////////N //N // Aa a a a a a a a a.N // Aa a a a a a a aAa a.N // a a 'a', a a 'a'.N //N // Aa: aN //N aN AaAaAa::aAa(Aa a)N //N ////////////////////////////////////////////////////////////////////////N {N // a a a a a'a a aN a *a = A;N a (AaAaAa::aAa->a((a a) a, a)) {N #a AN // a a A a.N // a a'a a a a a, a.N // a a a a a a, a a a aN // (a a a a a a a a a).N AaAaAa *a = (AaAaAa *) a;N a (a != a) {N AaAaAa::a("AaAaAa::aAa",N "a a a 0 a a! a a: %a, a a: %a", a->aAaAa(), aAaAa());N }N #aN }N a {N // Aa a a a a aN AaAaAa::aAa->a((a a) a, a);N }N }N N ////////////////////////////////////////////////////////////////////////N //N // Aa a a a a a a a a.N // Aa a a a a a a aAa a.N //N // Aa: aN //N aN AaAaAa::aAa(Aa a)N //N ////////////////////////////////////////////////////////////////////////N {N a (aAa != A)N aAa->a((a a) a);N }N N ////////////////////////////////////////////////////////////////////////N //N // Aa:N // Aa a a a a a a a a a aN // a a a a a. Aa a a a a a a a:N // 0) a a aN // 0) A_A_A a aN // 0) $(A)/a/a/AaN // 0) a a a "Aa a a a a"N //N // Aa: aN //N aN AaAaAa::aAaAa(a a *aAa)N //N ////////////////////////////////////////////////////////////////////////N {N a aAa[0];N a aAa[0];N a(aAa, "a ");N N #a 0N // ??? a a a a a a a a Aa. Aa aN // ??? a a a a a a a a a a. (a 0)N //???a- a a a, a a a'a a a.N a a, a, a;N aAaAa(A_A_A, &a); N aAaAa(A_A_A,&a);N aAaAa(A_A_A, &a);N a0_a a = a + a + a;N N N a (a < 0)N a(aAa, "-a "); // a a aN #aN N a a[0];N a(a, "a a > /a/a");N a (a(a) != 0) {N AaAa::aAaAaAa(_aAa, aAaAa, aAaAa);N a;N }N N // a a a a a a a a aN a ( a(aAa, A_A) == 0 ) {N a(aAa, aAa);N a(aAa, " &");N a (a(aAa) != 0)N AaAa::aAaAaAa(_aAa, aAaAa, aAaAa);N a;N }N N // a a a a a a N a *aAa = a("A_A_A");N a (aAa != A) {N a(aAa, aAa);N a(aAa, "/");N a(aAa, aAa);N a ( a(aAa, A_A) == 0 ) {N a(aAa, aAa);N a(aAa, " &");N a (a(aAa) != 0)N AaAa::aAaAaAa(_aAa, aAaAa, aAaAa);N a;N }N }N N // a a a a a aN a(aAa, A "/a/a/Aa/");N a(aAa, aAa);N a ( a(aAa, A_A) == 0 ) {N a(aAa, aAa);N a(aAa, " &");N a (a(aAa) != 0)N AaAa::aAaAaAa(_aAa, aAaAa, aAaAa);N a;N }N N //N // a a a a a a a a a aN //N AaAa::aAaAaAa(_aAa, aAaAa, aAaAa);N }N N N ////////////////////////////////////////////////////////////////////////N //N // Aa a a A - a a a a a.N //N // a aN //N aN AaAaAa::aAa()N //N ////////////////////////////////////////////////////////////////////////N {N #a AN AaAaAa::a("AaAaAa::aAa",N "a a a, a a a a a a a a a.", N "Aa, a a a a a.");N #aN _aAa = A;N }N N //N ////////////////////////////////////////////////////////////////////////N // a a aN ////////////////////////////////////////////////////////////////////////N //N N // Aa a _aAa a a.N aN AaAaAa::aAaA(N Aa, N AaAa aAa, N AaAa)N {N AaAaAa *a = (AaAaAa *) aAa;N a->aAa();N }N N //N // a a a a a a A_A_A aN // (a a a a)N //N aN AaAaAa::aAaAaA(Aa, AaAaAa *a, a *)N {N a (a->aAaAa != A)N (*a->aAaAa) (a->aAaAa, a);N aN a->aAaAa();N }N N //N // a a a a a a a/a (a aN // aAa a a a a a a'a a a)N //N aN AaAaAa::aAaAaA(Aa, AaAaAa *a, Aa *a, Aa *)N {N a (a->a == AaAa) {N // Aa a a-a a a a a a a aN a (a->aAa) {N a->aAaAa();N a->aAa = A;N }N N a->aAa = A;N a->aAaAaAa();N }N a a (a->a == AaAa) {N a->aAa = A;N a->aAaAaAa();N }N }N N //N // a a a a a a a/a (a aN // aAa a a a a a a'a a a)N //N aN AaAaAa::aAaAaA(Aa, AaAaAa *a, Aa *a, Aa *)N {N a (a->a == AaAa) {N a->AaAa = A;N a->aAaAaAa();N }N a a (a->a == AaAa) {N a->AaAa = A;N a->aAaAaAa();N }N }N
[ "Andrew.Jackson@bl.uk" ]
Andrew.Jackson@bl.uk
6e0c112d5566b23328959a66e5c239a7a9251395
39f1e2608183b7d50dbbba336e908fdbc0a2287d
/HANGOVER_SPOJ/main.cpp
b5b63540a0e90fa6073232f254f2d61956c94b55
[]
no_license
Hritiksingh/SPOJ_Solutions
657b51871d408538bbdd9c62216bd5ea830b845c
d32597842167360f4515439cc31cbfc95f2abfdf
refs/heads/master
2022-11-04T20:53:35.398029
2020-06-22T06:45:48
2020-06-22T06:45:48
262,012,971
0
0
null
null
null
null
UTF-8
C++
false
false
559
cpp
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr);cout.tie(nullptr); float n; while(true){ float sum=0,i=2; cin>>n; //----If input is 0.00 it will end taking input.------// if(n==0.00)break; while(sum<=n){ //-----we've to only check upto that point when the sum would become greater than given input 'c'-----// sum+=1/i; i++; if(sum>=n)break; } cout<<i-2<<" card(s)\n"; } return 0; }
[ "hritiksingh812@gmail.com" ]
hritiksingh812@gmail.com
9d118adcb599aab686ea66f93834d5432de670ea
72742d4ee57fb66cfe3f10290ccb596dcde1e59e
/camp2014/day2/c.cpp
6b6f47753e7c2b16f52969e2fb41f5e08f5969b9
[]
no_license
mertsaner/Algorithms
cd5cf84548ea10aafb13b4a3df07c67c1a007aef
f7aecb7e8aadff1e9cf49cc279530bc956d54260
refs/heads/master
2023-03-18T03:18:26.122361
2016-02-14T22:48:31
2016-02-14T22:48:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
918
cpp
#include <iostream> #include <cmath> using namespace std; unsigned long long a[20]; unsigned long long d(unsigned long long a) { unsigned long long res=0; while(a>0) a/=10, res++; return res; } unsigned long long middle(unsigned long long b) { unsigned long long res=b; unsigned long long c=d(b)-1; res%=(unsigned long long)pow(10.0, (double)c); return res/10; } unsigned long long f(unsigned long long b) { if(b<10) return b; unsigned long long res=0,c=b; res += a[d(b)-1]; while(b>=10) b/=10; unsigned long long first=b%10; res += middle(c); if(first!=1 && d(c)>=2) res += (first-1)*(unsigned long long)pow(10.0, (double)d(c)-2); if(c%10>=first) res++; return res; } int main() { unsigned long long int l,r; cin >> l >> r; a[1]=a[2]=9; for(int i=3;i<20;i++) a[i]=a[i-1]*10; for(int i=2;i<20;i++) a[i]+=a[i-1]; cout << (f(r) - f(l-1)) << endl; return 0; }
[ "kadircetinkaya.06.tr@gmail.com" ]
kadircetinkaya.06.tr@gmail.com
c47ee5cea456f116b9f63ecbf9830e19c75634f1
ba6dac289a3f95eb8a3b6f4fd018a52d894660a6
/2020-06-25/2020-06-26/2206/2206.cpp
b1dee593122f3015b6a6e02f19a219ff26fe2bf6
[]
no_license
dl57934/Algorithms
7f7b1c06521863c71f0631d78f1b826597101597
f7a2a3c9e67b59c6a6516cbf87b9cba222f494e3
refs/heads/master
2021-06-12T11:10:53.966903
2021-03-16T20:10:17
2021-03-16T20:10:17
162,096,787
1
0
null
null
null
null
UTF-8
C++
false
false
1,733
cpp
#include <cstdio> #include <queue> using namespace std; void input(); void bfs(); void resultPrint(); int N, M; int map[1002][1002]; queue < pair<pair<int, int>, int> > qu; int dis[1002][1002][3]; int check[1002][1002][3]; int xpos[4] = {0, 0, -1, 1}; int ypos[4] = {1, -1, 0, 0}; int main(){ input(); bfs(); resultPrint(); } void input(){ scanf("%d %d", &N, &M); for(int y = 1; y <= N; y++){ for(int x = 1; x <= M; x++){ scanf("%1d", &map[y][x]); } } qu.push(make_pair(make_pair(1, 1),1)); } // 0은 벽을 부심, 방문할 수 있음 // 1은 벽을 부술 수 있음, 방문 함 void bfs(){ dis[1][1][0] = 1; dis[1][1][1] = 1; check[1][1][0] = 0; check[1][1][1] = 0; while(!qu.empty()){ pair<int, int> nowPoint = qu.front().first; int canvisit = qu.front().second; qu.pop(); for(int i = 0; i < 4; i++){ int ny = nowPoint.first + ypos[i]; int nx = nowPoint.second + xpos[i]; if(ny >= 1 && ny <= N && nx >= 1 && nx <= M){ if(map[ny][nx] == 0 && !check[ny][nx][canvisit]){ dis[ny][nx][canvisit] = dis[nowPoint.first][nowPoint.second][canvisit] + 1; check[ny][nx][canvisit] = 1; qu.push(make_pair(make_pair(ny,nx), canvisit)); }else if(map[ny][nx] == 1 && !check[ny][nx][1] && canvisit){ dis[ny][nx][0] = dis[nowPoint.first][nowPoint.second][canvisit] + 1; check[ny][nx][0] = 1; qu.push(make_pair(make_pair(ny,nx), 0)); } } } } } void resultPrint(){ if(!dis[N][M][0] && !dis[N][M][1]){ printf("-1\n"); return ; } if(dis[N][M][0] == 0) printf("%d", dis[N][M][1]); else if(dis[N][M][1] == 0) printf("%d", dis[N][M][0]); else if(dis[N][M][1] < dis[N][M][0]) printf("%d", dis[N][M][1]); else printf("%d", dis[N][M][0]); }
[ "dl57934@naver.com" ]
dl57934@naver.com
f64daf7451ccc9f52d21f8057603ef3f5cab4f75
ed2411e3ca762ba7a1c68ed0b2011cfa533aa5a0
/code/engine.vc2008/xrManagedUILib/xrManagedUILib/ISpectreUILib.cpp
bee9b834cb7c4e8fcc18eabc9bf3cc5baeb79c83
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "Apache-2.0" ]
permissive
andreyholkin/xray-oxygen
59be08e8a7f35577418a459cedc0ef799695e257
663ed0795f84e1b8cec0d6404ded27aad71b067c
refs/heads/master
2020-04-02T12:47:17.244026
2018-10-18T15:42:16
2018-10-18T15:42:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
46
cpp
#include "stdafx.h" #include "ISpectreUILib.h"
[ "vihtarb@gmail.com" ]
vihtarb@gmail.com
b85d02e568236da8a508aced8fd952f075e8dd1a
a3723c8cf87c2b07a0f2726dff10b5a89d1db121
/Zadanie_5/TransmisionOfPackage.h
5fcb53bc6f68b064612b3baecaf11a50a1a97eb2
[]
no_license
ATSP5/Symulacja-Cyfrowa
04d2d3ef610b0dc2b8c2641261d7ca9dbda94ad3
4351cb1d0590b9409cf1e8c31048c54972487524
refs/heads/main
2023-01-22T20:15:04.873965
2020-12-06T12:03:21
2020-12-06T12:03:21
305,356,209
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
883
h
#ifndef TRANSMISIONOFPACKAGE_H #define TRANSMISIONOFPACKAGE_H #include "TelecommunicationSystem.h" #include "EndOfPackageTransmision.h" #include "EndOfChannelQuestioning.h" #include "ApLogger.h" class TransmisionOfPackage { private: bool event_locked_; int source_;// Numer stacji bazowej dla której to zdarzenie występuje TelecommunicationSystem* telecommunication_system_; vector<EndOfChannelQuestioning* > end_of_channel_questioning_; vector<EndOfPackageTransmision* > end_of_package_transmision_; public: void Execute(ApLogger* ap_log_); TransmisionOfPackage(int source_station_, TelecommunicationSystem* telecommunication_sys_, vector<EndOfPackageTransmision* > &end_of_package_transmision_V, vector<EndOfChannelQuestioning* > &end_of_channel_questioning_V_); bool GetEventLockedStatus(); void SetEventLock(bool lock_stat_); }; #endif // !TRANSMISIONOFPACKAGE_H
[ "adamprukala@wp.pl" ]
adamprukala@wp.pl
2a1d062c4c401e6fabbeb7195150f0f20b262006
16c87360f00b4ea12c024875f4aa3a1be685603d
/ModeRunControl/DlgModeRunCtrl.h
8bd31df89485b0d0bf5323c745a80164a3ac863a
[]
no_license
radiohide/temp
28ffe85e507b189c48c0c399f708f66f0558a4f2
7740a9965524a5a7a88e59291cc1f06382f01c58
refs/heads/master
2021-06-05T17:35:24.721125
2021-04-20T09:04:48
2021-04-20T09:04:48
86,920,856
0
0
null
null
null
null
UTF-8
C++
false
false
1,911
h
#if !defined(AFX_DLGMODERUNCTRL_H__3958F334_C95E_41A7_AB0C_845B6BC2B743__INCLUDED_) #define AFX_DLGMODERUNCTRL_H__3958F334_C95E_41A7_AB0C_845B6BC2B743__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DlgModeRunCtrl.h : header file // ///////////////////////////////////////////////////////////////////////////// // CDlgModeRunCtrl dialog #include "DlgMCtrlDay.h" #include "DlgMCtrlCycle.h" #include "DlgMCtrlDuty.h" #include "DlgMCtrlMonth.h" #include "DlgMCtrlWeek.h" #include "DlgMCtrlType.h" #include "ModelCalcControl.h" class CDlgModeRunCtrl : public CDialog { // Construction public: CDlgModeRunCtrl(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CDlgModeRunCtrl) enum { IDD = IDD_DIALOG_MODERUN_CONCTRL }; CComboBox m_ComBoTaskType; //}}AFX_DATA public: CArray<CDlgMCtrlType*,CDlgMCtrlType*&> dlgAllTypeArr; ModelCalcControl *m_pMCalControl; public: void SetModelCalcControl(ModelCalcControl *pMCalControl); private: void showMCtrlDlgByIndex(int index); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDlgModeRunCtrl) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CDlgModeRunCtrl) virtual BOOL OnInitDialog(); afx_msg void OnSelchangeComboTasktype(); afx_msg void OnClose(); afx_msg void OnButtonSetRunABSTime(); afx_msg void OnButtonSetRunDataTime(); afx_msg void OnButtonApply(); afx_msg void OnButtonOk(); afx_msg void OnButtonCancle(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DLGMODERUNCTRL_H__3958F334_C95E_41A7_AB0C_845B6BC2B743__INCLUDED_)
[ "chenxi1@gdtianren.com" ]
chenxi1@gdtianren.com
57a88ae232ea60577401bed5bf9e3989e32a2e15
07e33a6c7e044d8873246cb17b2dd9b262322093
/drill5/15.cpp
c8b533f5fcffa8a9ee3345010e745b6ee63e7c66
[]
no_license
NRaccoon/Bev.Prog.
3971f6ce90ddf603f6b13ac553f5fad0d2c4c9b1
137d4fa076b24735f2bbd2f8a806fb3353e2086f
refs/heads/master
2020-03-29T09:22:02.515417
2018-12-13T21:22:27
2018-12-13T21:22:27
149,754,456
0
0
null
null
null
null
UTF-8
C++
false
false
123
cpp
#include "std_lib_facilities.h" int main() { string s = "Success!\n"; for (int i = 0; i < s.size(); ++i) cout << s [i]; }
[ "noreply@github.com" ]
NRaccoon.noreply@github.com
7800ffd1fee9486932c5f66bcf1a5d1991fc0dc9
e557ce74c9fe34aa2b68441254b7def699067501
/src/libtsduck/base/network/tsTCPServer.h
3b49f9c3f0b27f3c0e3ad3f39757a0a8413dfb1f
[ "BSD-2-Clause" ]
permissive
cedinu/tsduck-mod
53d9b4061d0eab9864d40b1d47b34f5908f99d8a
6c97507b63e7882a146eee3613d4184b7e535101
refs/heads/master
2023-05-10T12:56:33.185589
2023-05-02T09:00:57
2023-05-02T09:00:57
236,732,523
0
0
BSD-2-Clause
2021-09-23T08:36:08
2020-01-28T12:41:10
C++
UTF-8
C++
false
false
5,006
h
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2023, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- //! //! @file //! TCP Server //! //---------------------------------------------------------------------------- #pragma once #include "tsTCPConnection.h" namespace ts { //! //! Implementation of a TCP/IP server. //! @ingroup net //! //! The following lists the typical server-side scenario in the correct order. //! Many steps such as setting socket options are optional. The symbol [*] means mandatory. //! Depending on the platform, some options settings are sensitive to the order. //! The following order has proven to work on most platforms. //! //! - [*] open() //! - reusePort() //! - setSendBufferSize() //! - setReceiveBufferSize() //! - setLingerTime() / setNoLinger() //! - setKeepAlive() //! - setNoDelay() //! - setTTL() //! - [*] bind() //! - [*] listen() //! - [*] accept() //! - close() //! //! Invoking close() is optional since the destructor of the class will properly //! close the socket if not already done. //! class TSDUCKDLL TCPServer: public TCPSocket { TS_NOCOPY(TCPServer); public: //! //! Reference to the superclass. //! typedef TCPSocket SuperClass; //! //! Constructor //! TCPServer(): TCPSocket() { } //! //! Start the server. //! //! Here, @e starting the server means starting to listen to incoming //! client connections. Internally to the kernel, the incoming connections //! are queued up to @a backlog. When the method accept() is invoked and //! some incoming connections are already queued in the kernel, the oldest //! one is immediately accepted. Otherwise, accept() blocks until a new //! incoming connection arrives. //! //! @param [in] backlog Maximum number of incoming connections which allowed //! to queue in the kernel until the next call to accept(). Note that this //! value is a minimum queue size. But the kernel may accept more. There is //! no guarantee that additional incoming connections will be rejected if more //! than @a backlog are already queueing. //! @param [in,out] report Where to report error. //! @return True on success, false on error. //! bool listen(int backlog, Report& report = CERR); //! //! Wait for an incoming client connection. //! //! @param [out] client This object receives the new connection. Upon successful //! return from accept(), the TCPConnection object is a properly connected TCP //! session. Once the connection is completed, the TCPConnection objects on the //! client side and the server side are symmetric and can be used the same way. //! @param [out] addr This object receives the socket address of the client. //! If the server wants to filter client connections based on their IP address, //! it may use @a addr for that. //! @param [in,out] report Where to report error. //! @return True on success, false on error. //! @see listen() //! bool accept(TCPConnection& client, IPv4SocketAddress& addr, Report& report = CERR); // Inherited and overridden virtual bool close(Report& report = CERR) override; }; }
[ "thierry@lelegard.fr" ]
thierry@lelegard.fr
efaf92ad81ec56dd8da80052a21a78114ec48446
25d540ecc1962b8a818732007668d37fd3156959
/OpenSauce/Halo2/Halo2_Xbox/Objects/Objects.Scripting.inl
36cbd4cfc69e7a698ffde490035d0dc13e053378
[]
no_license
PlayerGamer3547/OpenSauce
01bf5bf3d0e7b97c77130afe47d95c0e31e8ab87
d4a80fca53fd864e48e03b7f0fae6ad1bed88f78
refs/heads/master
2022-12-11T03:30:10.250464
2020-08-02T10:36:36
2020-08-02T10:36:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,396
inl
/* Yelo: Open Sauce SDK Halo 1 (CE) Edition See license\OpenSauce\Halo1_CE for specific license information */ #include "Game/Camera.hpp" #include "Game/GameStateRuntimeData.hpp" #include "Objects/Objects.hpp" #include "Objects/Objects.WeaponSettings.hpp" #include <YeloLib/cseries/value_conversion.hpp> #include <YeloLib/Halo1/objects/objects_yelo.hpp> namespace Yelo { namespace Objects { static void* scripting_objects_distance_to_object_evaluate(void** arguments) { struct s_arguments { datum_index object_list; datum_index dest_object; }* args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.real = -1.0f; if(!args->dest_object.IsNull()) { real min_dist = FLT_MAX; // Get the destination object's origin so that we can compare it, relative to each object in the list real_vector3d dest_object_origin; blam::object_get_origin(args->dest_object, dest_object_origin); // Enumerate the object list, testing each object's origin with dest for(datum_index curr_list_reference, curr_object_index = blam::object_list_get_first(args->object_list, curr_list_reference); !curr_object_index.IsNull(); curr_object_index = blam::object_list_get_next(args->object_list, curr_list_reference)) { // Compare the current object from the list to the destination object real dist = GetObjectDistanceFromPoint(curr_object_index, dest_object_origin); // We want the smallest distance of all the objects if(min_dist > dist) min_dist = dist; } if(min_dist != FLT_MAX) result.real = min_dist; } return result.pointer; } static void* scripting_object_data_get_real_evaluate(void** arguments) { struct s_arguments { datum_index object_index; cstring data_name; cstring subdata_name; }* args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.real = -1.0f; if(!args->object_index.IsNull()) { s_object_header_datum* object = Objects::ObjectHeader()[args->object_index]; ObjectDataGetRealByName(object, args->data_name, args->subdata_name, result); } return result.pointer; } static void* scripting_object_data_set_real_evaluate(void** arguments) { struct s_arguments { datum_index object_index; cstring data_name; cstring subdata_name; real data_value; }* args = CAST_PTR(s_arguments*, arguments); if(!args->object_index.IsNull()) { s_object_header_datum* object = Objects::ObjectHeader()[args->object_index]; ObjectDataSetRealByName(object, args->data_name, args->subdata_name, args->data_value); } return nullptr; } static void* scripting_object_data_set_vector_evaluate(void** arguments) { struct s_arguments { datum_index object_index; cstring data_name; int16 vector_index; PAD16; }* args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; if(!args->object_index.IsNull()) { s_object_header_datum* object = Objects::ObjectHeader()[args->object_index]; real_vector3d* obj_vector = ObjectDataGetVectorByName(object, args->data_name); const real_vector3d* vector = GameState::RuntimeData::VectorValueGet(args->vector_index); if(obj_vector != nullptr && vector != nullptr) { *obj_vector = *vector; result.boolean = true; } } return result.pointer; } static void* scripting_object_data_save_vector_evaluate(void** arguments) { struct s_arguments { datum_index object_index; cstring data_name; int16 vector_index; PAD16; }* args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; if(!args->object_index.IsNull()) { s_object_header_datum* object = Objects::ObjectHeader()[args->object_index]; real_vector3d* obj_vector = ObjectDataGetVectorByName(object, args->data_name); real_vector3d* vector = GameState::RuntimeData::VectorValueGetForModify(args->vector_index); if(obj_vector != nullptr && vector != nullptr) { *vector = *obj_vector; result.boolean = true; } } return result.pointer; } ////////////////////////////////////////////////////////////////////////// // WEAPONS static void* scripting_weapon_data_get_real_evaluate(void** arguments) { struct s_arguments { datum_index weapon_index; cstring data_name; }* args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.real = -1.0f; if(!args->weapon_index.IsNull()) { auto weapon = blam::object_try_and_get_and_verify_type<s_weapon_datum>(args->weapon_index); if (weapon != nullptr) WeaponDataGetRealByName(weapon, args->data_name, result); } return result.pointer; } static void* scripting_weapon_data_set_real_evaluate(void** arguments) { struct s_arguments { datum_index weapon_index; cstring data_name; real data_value; }* args = CAST_PTR(s_arguments*, arguments); if(GameState::IsLocal() && !args->weapon_index.IsNull()) { auto weapon = blam::object_try_and_get_and_verify_type<s_weapon_datum>(args->weapon_index); if(weapon != nullptr) WeaponDataSetRealByName(weapon, args->data_name, args->data_value); } return nullptr; } ////////////////////////////////////////////////////////////////////////// // WEAPONS - MAGAZINES static void* scripting_weapon_data_magazine_get_integer_evaluate(void** arguments) { struct s_arguments { datum_index weapon_index; int32 magazine_index; cstring data_name; cstring subdata_name; }* args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.int32 = NONE; if(GameState::IsLocal() && !args->weapon_index.IsNull()) { auto weapon = blam::object_try_and_get_and_verify_type<s_weapon_datum>(args->weapon_index); if(weapon != nullptr) WeaponDataMagazineGetIntegerByName(weapon, args->magazine_index, args->data_name, args->subdata_name, result); } return result.pointer; } static void* scripting_weapon_data_magazine_set_integer_evaluate(void** arguments) { struct s_arguments { datum_index weapon_index; int32 magazine_index; cstring data_name; cstring subdata_name; int32 data_value; }* args = CAST_PTR(s_arguments*, arguments); if(GameState::IsLocal() && !args->weapon_index.IsNull()) { auto weapon = blam::object_try_and_get_and_verify_type<s_weapon_datum>(args->weapon_index); if(weapon != nullptr) WeaponDataMagazineSetIntegerByName(weapon, args->magazine_index, args->data_name, args->subdata_name, args->data_value); } return nullptr; } ////////////////////////////////////////////////////////////////////////// // WEAPONS - TRIGGERS static void* scripting_weapon_data_trigger_set_real_evaluate(void** arguments) { struct s_arguments { datum_index weapon_index; int32 trigger_index; cstring data_name; cstring subdata_name; real data_value; }* args = CAST_PTR(s_arguments*, arguments); // IF ANY OF YOUR DESIGNERS USE THIS FUCKING SCRIPT FUNCTION, THEN YOU ALL DESERVE TO BE FUCKING SHOT. // SRSLY. // We don't support modifying trigger data in anything but local games because it writes to tag memory if(GameState::IsLocal() && !args->weapon_index.IsNull()) { auto weapon = blam::object_try_and_get_and_verify_type<s_weapon_datum>(args->weapon_index); if(weapon != nullptr) WeaponTagDataTriggerSetRealByName(weapon, args->trigger_index, args->data_name, args->subdata_name, args->data_value); } return nullptr; } ////////////////////////////////////////////////////////////////////////// // UNITS static void* scripting_unit_data_get_object_evaluate(void** arguments) { struct s_arguments { datum_index unit_index; cstring data_name; }* args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.datum = datum_index::null; if(!args->unit_index.IsNull()) { auto* unit = blam::object_try_and_get_and_verify_type<s_unit_datum>(args->unit_index); if(!unit) { return result.pointer; } UnitDataGetObjectIndexByName(unit, args->data_name, result); } return result.pointer; } static void* scripting_unit_data_get_integer_evaluate(void** arguments) { struct s_arguments { datum_index unit_index; cstring data_name; }* args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.int32 = NONE; if(!args->unit_index.IsNull()) { auto* unit = blam::object_try_and_get_and_verify_type<s_unit_datum>(args->unit_index); if(!unit) { return result.pointer; } UnitDataGetIntegerByName(unit, args->data_name, result); } return result.pointer; } static void* scripting_unit_data_set_integer_evaluate(void** arguments) { struct s_arguments { datum_index unit_index; cstring data_name; int32 data_value; }* args = CAST_PTR(s_arguments*, arguments); if(!args->unit_index.IsNull()) { auto* unit = blam::object_try_and_get_and_verify_type<s_unit_datum>(args->unit_index); if(!unit) { return nullptr; } UnitDataSetIntegerByName(unit, args->data_name, args->data_value); } return nullptr; } static void* scripting_unit_data_get_real_evaluate(void** arguments) { struct s_arguments { datum_index unit_index; cstring data_name; }* args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.real = -1.0f; if(!args->unit_index.IsNull()) { auto* unit = blam::object_try_and_get_and_verify_type<s_unit_datum>(args->unit_index); if(!unit) { return result.pointer; } UnitDataGetRealByName(unit, args->data_name, result); } return result.pointer; } static void* scripting_unit_data_set_real_evaluate(void** arguments) { struct s_arguments { datum_index unit_index; cstring data_name; real data_value; }* args = CAST_PTR(s_arguments*, arguments); if(GameState::IsLocal() && !args->unit_index.IsNull()) { auto* unit = blam::object_try_and_get_and_verify_type<s_unit_datum>(args->unit_index); if(!unit) { return nullptr; } UnitDataSetRealByName(unit, args->data_name,args->data_value); } return nullptr; } static void* scripting_vehicle_remapper_enabled_evaluate(void** arguments) { struct s_arguments { cstring state_name; }* args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.boolean = !c_settings_objects::Instance()->m_vehicle_remapper_enabled; if( args->state_name[0] != '\0' && strcmp(args->state_name, "get")!=0 ) { bool value = false; ValueConversion::FromString(args->state_name, value); VehicleRemapperEnable( value ); } return result.pointer; } static void* scripting_unit_is_key_down_evaluate(void** arguments) { struct s_arguments { datum_index unit_index; short keypress; }*args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.boolean = false; if (!args->unit_index.IsNull()) { auto* unit = blam::object_try_and_get_and_verify_type<s_unit_datum>(args->unit_index); if (!unit) { return result.pointer; } if (GetKeyState (args->keypress) & 0x8000) { result.boolean = true; } } return result.pointer; } static void* scripting_unit_camera_fov_set_evaluate(void** arguments) { struct s_arguments { datum_index unit_index; real fov; }*args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.boolean = false; if (!args->unit_index.IsNull()) { auto* unit = blam::object_try_and_get_and_verify_type<s_unit_datum>(args->unit_index); if (!unit) { return result.pointer; } if (args->fov) { Fov::GetFieldOfView; Fov::SetFieldOfView(args->fov); result.boolean = true; } } return result.pointer; } static void* scripting_unit_weapon_set_position_evaluate(void** arguments) { struct s_arguments { datum_index unit_index; real weapon_pos_x; real weapon_pos_y; real weapon_pos_z; }*args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.boolean = false; if (!args->unit_index.IsNull()) { auto* unit = blam::object_try_and_get_and_verify_type<s_unit_datum>(args->unit_index); if (!unit) { return result.pointer; } if (args->weapon_pos_x && args->weapon_pos_y && args->weapon_pos_z, NONE) { real_vector3d weapon_position{ args->weapon_pos_x, args->weapon_pos_y, args->weapon_pos_z }; Weapon::Initialize(); Weapon::GetWeaponPosition(); Weapon::SetWeaponPosition(weapon_position); Weapon::Dispose(); result.boolean = true; } } return result.pointer; } static void* scripting_unit_switch_weapon_evaluate(void** arguments) { struct s_arguments { datum_index unit_index; cstring tag_path; }*args = CAST_PTR(s_arguments*, arguments); TypeHolder result; result.pointer = nullptr; result.boolean = false; if (!args->unit_index.IsNull()) { auto* unit = blam::object_try_and_get_and_verify_type<s_unit_datum>(args->unit_index); if (!unit) { return result.pointer; } if (StrCmp(args->tag_path, "")) { result.boolean = true; } } return result.pointer; } }; };
[ "voidsshadow@hotmail.com" ]
voidsshadow@hotmail.com
78c12902a28ad83e4d243f4b040ffe4e871e5d47
7cbfe0520262ed4cdb8e309d51fb13edf2895d04
/SRM656/CorruptedMessage.cpp
79d78b94237b39f89849ba3366133ab755cc440e
[]
no_license
ry0u/SRM
917383d8e2096388b7de7b53edd6e362d00a2126
02a08e74e67f8f929cffcde4075c4d41b580d7c4
refs/heads/master
2020-12-25T17:25:46.661867
2017-02-20T09:26:55
2017-02-20T09:26:55
29,791,579
0
0
null
null
null
null
UTF-8
C++
false
false
1,041
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "CorruptedMessage.cpp" #include <iostream> #include <string> #include <vector> #include <algorithm> #include <map> #include <sstream> #define REP(i,k,n) for(int i=k;i<n;i++) #define rep(i,n) for(int i=0;i<n;i++) using namespace std; class CorruptedMessage { public: string reconstructMessage(string s, int k) { string ret = ""; map<char,int> m; rep(i,s.size()) { m[s[i]]++; } bool flag = true; char c = s[0]; rep(i,27) { if(m['a'+i] == s.size()-k) { flag = false; c = (char)('a'+i); break; } } if(!flag) { stringstream ss; ss << c; rep(i,s.size()) { ret += ss.str(); } } else { char t = s[0]; rep(i,27) { if(m['a'+i] == 0) { t = (char)('a'+i); break; } } stringstream ss; ss << t; rep(i,s.size()) ret += ss.str(); } return ret; } }; // BEGIN CUT HERE int main() { CorruptedMessage ___test; cout << ___test.reconstructMessage("abs",3) << endl; } // END CUT HERE
[ "ry0u_yd@yahoo.co.jp" ]
ry0u_yd@yahoo.co.jp
66576d2bc351366ec99bf0014bbe39e747403f23
56f6eb0a7d89285154cb0fdf1289ea894b5c8592
/src/tasks/task.hpp
a097006647c1f2d5fed88f16ae0032fb8ec19450
[ "MIT" ]
permissive
ATetiukhin/QMathematics
2f6e5914b880907328dbb283f7d95242fb4173d4
7db9084184c9a517a69358713a04de61b0bb40ef
refs/heads/master
2021-01-15T11:11:57.060208
2015-01-20T06:09:06
2015-01-20T06:09:06
28,423,972
2
1
null
null
null
null
UTF-8
C++
false
false
456
hpp
/** * @file task.hpp * @Author ATetiukhin * @date January, 2015 * @brief General class @ref Task for different tasks. */ #ifndef TASK_HPP_INCLUDE #define TASK_HPP_INCLUDE #include <QWidget> #include "type_task.hpp" class Task : public QObject { Q_OBJECT public: virtual ~Task() {} QWidget * getWidget() { return ui_; } protected: TypeTask * task_; QWidget * ui_; }; #endif /* End of 'task.hpp' file */
[ "artemtetiukhin@yandex.ru" ]
artemtetiukhin@yandex.ru
3afc0731f911195c0df2a8b7c6c44c5368b598ed
dcb7dae56932f62292fd0d607e32dc2f238d5551
/339-B/main.cpp
96bbebf67678478703e0bc7d077d85779f784d1f
[]
no_license
alielrafeiFCIH/Problem_Solving
b5f330d115d3ca1c34613eb2639226c271f0052b
15863cd43012831867fa2035fc92733a059dcfbf
refs/heads/master
2020-06-27T03:33:15.668655
2019-09-03T09:49:26
2019-09-03T09:49:26
199,831,566
0
0
null
null
null
null
UTF-8
C++
false
false
566
cpp
#include <bits/stdc++.h> using namespace std; int main() { int n; int m,a; vector<int>v; long long int sum=0; scanf("%d%d",&n,&m); for(int i = 1;i<=m;i++){ cin>>a; v.push_back(a); } int start = 1; int s = v.size(); for(int i =0 ;i<s;i++){ if(v[i]<start){ int temp = abs(v[i]-start+n); sum+=temp; start=v[i]; }else{ int temp = abs(v[i]-start); sum+=temp; start = v[i]; } } cout<<sum; return 0; }
[ "alielrafei.fcih@gmail.com" ]
alielrafei.fcih@gmail.com
36ed35eae3c26e36c57746576276357544f14212
99571aa2e9a2b1542ca2d236edef81dd54aa797c
/hpc2017/src/Game.cpp
ff1f7f947a762c7ec45d678c996a0c91ec10a2b7
[]
no_license
kmyk/hallab-progcon-2017
67e2856dc0a589d59bb5626c6d12e7cbb0a08c1d
074d023bb699225b8d5a36b3a8916f3903ba8809
refs/heads/master
2021-07-10T21:33:59.074206
2017-10-15T22:46:30
2017-10-15T22:46:30
106,384,496
0
0
null
null
null
null
UTF-8
C++
false
false
2,501
cpp
//------------------------------------------------------------------------------ /// @file /// @author ハル研究所プログラミングコンテスト実行委員会 /// /// @copyright Copyright (c) 2017 HAL Laboratory, Inc. /// @attention このファイルの利用は、同梱のREADMEにある /// 利用条件に従ってください。 //------------------------------------------------------------------------------ #include "Game.hpp" #include "Assert.hpp" namespace hpc { //------------------------------------------------------------------------------ /// Game クラスのインスタンスを生成します。 Game::Game(RandomSeed aSeed) : mRandom(aSeed) , mRecorder() , mTimer() { } //------------------------------------------------------------------------------ /// シード値を変更します。 /// /// @param[in] aSeed 新しいシード値。 void Game::changeSeed(RandomSeed aSeed) { mRandom = Random(aSeed); } //------------------------------------------------------------------------------ /// ゲームを実行します。 /// /// @param[in] aAnswer ゲームの解答。 void Game::run(Answer& aAnswer) { mTimer.start(); for(int i = 0; i < Parameter::GameStageCount; ++i) { uint w = mRandom.randU32(); uint z = mRandom.randU32(); uint y = mRandom.randU32(); uint x = mRandom.randU32(); RandomSeed seed(x, y, z, w); Stage stage(seed); stage.init(); aAnswer.init(stage); mRecorder.afterInitStage(stage); while(!stage.hasFinished() && stage.turn() < Parameter::GameTurnLimit) { Actions actions; aAnswer.moveItems(stage, actions); stage.moveItems(actions); TargetPositions targetPositions; aAnswer.moveUFOs(stage, targetPositions); stage.moveUFOs(targetPositions); stage.advanceTurn(); mRecorder.afterAdvanceTurn(stage); } mRecorder.afterFinishStage(); aAnswer.finalize(stage); } mRecorder.afterFinishAllStages(); mTimer.stop(); } //------------------------------------------------------------------------------ /// ログ記録器を取得します。 const Recorder& Game::recorder()const { return mRecorder; } //------------------------------------------------------------------------------ /// タイマーを取得します。 const Timer& Game::timer()const { return mTimer; } } // namespace // EOF
[ "kimiyuki95@gmail.com" ]
kimiyuki95@gmail.com
cbfd87221d228f36a2cca49a91e06e8b55769791
44ea78720cf1fbbbb57a204d462f08ef8ccb7c42
/ABC/ABC087/B/main.cpp
33dde054485bd96ae7c59a0765a4b3d447ad00aa
[]
no_license
kironbot/AtCoder
854a85d55e2d3c0c8ef76589ad905af20d9c567d
4c05bf806413f5c601baa7432b9d85b102ba34b7
refs/heads/master
2021-06-29T16:14:47.667960
2020-09-27T06:17:02
2020-09-27T06:17:02
138,470,049
0
0
null
null
null
null
UTF-8
C++
false
false
375
cpp
#include <iostream> using namespace std; int main() { int A, B, C, X; cin >> A >> B >> C >> X; int res = 0; for (int a=0; a <= A; ++a){ for (int b=0; b <= B; ++b){ for (int c=0; c <= C; ++c){ int total = 500*a + 100*b + 50*c; if (total == X) ++res; } } } cout << res << endl; }
[ "sgr.araki@gmail.com" ]
sgr.araki@gmail.com
496962d72745862d609a595e37ffadd7856da31a
a998da51959779d30ed25089f25ef5d8606a2f26
/include/FlxState.h
dbcf795c1c10b652d6173ec22e82f188f3c6c194
[]
no_license
ratalaika/FlixelCpp
a9f3ed1cb42f19786bdc75e97b68322442572a5a
8843a3f1c88d96873ec887243dfbad9ea6601b01
refs/heads/master
2021-01-23T20:55:37.108817
2012-10-21T10:14:08
2012-10-21T10:14:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
878
h
/* This file is a part of "Flixel C++ port" project Copyrights (c) by Michał Korman 2012 */ #ifndef _FLX_STATE_H_ #define _FLX_STATE_H_ #include "backend/cpp.h" #include "FlxGroup.h" /** * Basic scene managment class */ class FlxState : public FlxGroup { public: /** * Default destrurctor */ ~FlxState() { clear(); } /** * State creating event. It's called once when state is being set as default. * To override. */ virtual void create() { } /** * State leaving event. It's called once when state is being destroyed (but before destructor). * To override. */ virtual void leave() { } /** * Update state event. * To override. */ virtual void update() { FlxGroup::update(); } /** * Draw event. * To override. */ void draw() { FlxGroup::draw(); } }; #endif
[ "dynax126@gmail.com" ]
dynax126@gmail.com
93471e570f963ac8d082e21425538eaee739519f
db1636ffd781a60bc6eb8676eb73d3fa29a6a834
/Workshop_16_09_26/distance.cpp
cad905197ca0bb30b5bdc18636c6042950eb5b4e
[]
no_license
atishay197/machine-learning
6841928822621061df697781aabf33d825ce6007
400dff6cf1b5dd4075aeecd01432dfc9a3af0abe
refs/heads/master
2021-01-17T19:00:38.091677
2016-09-27T07:33:46
2016-09-27T07:33:46
62,532,298
0
0
null
null
null
null
UTF-8
C++
false
false
3,345
cpp
#include <bits/stdc++.h> float distanceMat[10][10] = {9999}; struct cordinate { float x; float y; // float z; cordinate(float x,float y) { this->x = x; this->y = y; // this->x = z; } cordinate() { this->x = 999999; this->y = 999999; } }; struct cluster { float x[10]; float y[10]; int i; cluster() { i = 0; } }; struct cluster addToCluster(cordinate b,struct cluster a) { // printf("Adding : %f , %f to a[%d]\n",b.x,b.y,a.i); a.x[a.i] = b.x; a.y[a.i] = b.y; a.i += 1; return a; } float distCalc(struct cordinate a,struct cordinate b) { return (pow(((pow((a.x-b.x),2))+pow((a.y-b.y),2)),0.5)); //+pow((a->Z-b->Z),2)); } struct cluster mergeCluster(struct cluster a,struct cluster b) { for(int i=0 ; i<b.i ; i++) { b.x[i] = a.x[a.i]; b.y[i] = a.y[a.i]; a.i += 1; } return a; } void updateDistanceMatrix(int points,struct cluster a[10]) { for(int i=0 ; i<points ; i++) { for(int j=0 ; j<points ; j++) { for(int k=0 ; k<a[i].i ; k++) { for(int l=0 ; l<a[j].i ; l++) { float cur = distCalc(cordinate(a[i].x[k],a[i].y[k]),cordinate(a[j].x[l],a[j].y[l])); // printf("%d %d %d %d %f %f = a.x: %f a.y: %f a.x: %f a.y: %f",i,j,k,l,cur,distanceMat[i][j],a[i].x[k],a[i].y[k],a[j].x[l],a[j].y[l]); if(distanceMat[i][j] > cur) distanceMat[i][j] = cur; } } // printf("%f\t",distanceMat[i][j]); } // printf("\n"); } } void printCluster(struct cluster a) { for(int i=0 ; i<a.i ; i++) { printf("(%f,%f)\n",a.x[i],a.y[i]); } printf("\n"); return; } void distanceMatrix(int points) { for(int i=0 ; i<points ; i++) { for(int j=0 ; j<points ; j++) distanceMat[i][j] = 99999; } } void printDistanceMatrix(int points) { for(int i=0 ; i<points ; i++) { for(int j=0 ; j<points ; j++) printf("%f\t",distanceMat[i][j]); printf("\n"); } } struct closestCluster { struct cluster a; struct cluster b; closestCluster(struct cluster a,struct cluster b) { this->a = a; this->b = b; } }; struct closestCluster findClosestCluster(struct cluster a[10], int points) { float mindis = 9999999; int mini=0,minj=0; for(int i=0 ; i<points ; i++) { for(int j=0 ; j<points ; j++) if(distanceMat[i][j] < mindis && distanceMat[i][j] != 0 && i!=j) { mindis = distanceMat[i][j]; mini = i; minj = j; } } return closestCluster(a[mini],a[minj]); } void printClosestCluster(struct closestCluster a) { int i; for(i=0 ; i<a.a.i ; i++) { printf("(%f,%f),",a.a.x[i],a.a.y[i]); } for(i=0 ; i<a.b.i ; i++) { printf("(%f,%f),",a.b.x[i],a.b.y[i]); } return; } int main() { struct cordinate a[10]; struct cluster b[10]; int points = 6; a[0] = cordinate(1,1); a[1] = cordinate(1.5,1.5); a[2] = cordinate(5,5); a[3] = cordinate(3,4); a[4] = cordinate(4,4); a[5] = cordinate(3,3.5); distanceMatrix(points); for(int i=0 ; i<points ; i++) b[i] = addToCluster(a[i],b[i]); for(int i=0 ; i<points ; i++) printCluster(b[i]); updateDistanceMatrix(points,b); int clusterNumber = points; while(clusterNumber != 1) { distanceMatrix(points); updateDistanceMatrix(clusterNumber,b); struct closestCluster c = findClosestCluster(b,clusterNumber); printClosestCluster(c); printf("\n"); // findClosestCluster(struct cluster a[10],int clusterNumber); clusterNumber--; printDistanceMatrix(points); } }
[ "atishay197@gmail.com" ]
atishay197@gmail.com
6459025ad65a3d035ce78d6239440d44ebc10333
a22f21123e0371039018fb4b46657b3059b372bc
/gdal/gcore/mdreader/reader_geo_eye.h
9cb5dfebf200411f4bae75202dcc14f41f076fd1
[ "MIT", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-info-zip-2005-02", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer", "SunPro" ]
permissive
klokantech/gdal
ddd4ace538691ae2ea4ce1a9eb114b96537f0b13
d8c41274833752b48ca39311816f82c2a16a3971
refs/heads/trunk
2023-09-05T11:27:15.048327
2015-08-08T13:47:17
2015-08-08T13:47:17
33,614,415
1
1
null
2015-04-08T15:10:19
2015-04-08T15:10:19
null
UTF-8
C++
false
false
2,532
h
/****************************************************************************** * $Id$ * * Project: GDAL Core * Purpose: Read metadata from GeoEye imagery. * Author: Alexander Lisovenko * Author: Dmitry Baryshnikov, polimax@mail.ru * ****************************************************************************** * Copyright (c) 2014-2015, NextGIS info@nextgis.ru * * 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 READER_GEO_EYE_H_INCLUDED #define READER_GEO_EYE_H_INCLUDED #include "../gdal_mdreader.h" /** @brief Metadata reader for Geo Eye TIFF filename: aaaaaaaaaa.tif Metadata filename: *_metadata* RPC filename: aaaaaaaaaa_rpc.txt Common metadata (from metadata filename): SatelliteId: Sensor CloudCover: Percent Cloud Cover AcquisitionDateTime: Acquisition Date/Time */ class GDALMDReaderGeoEye: public GDALMDReaderBase { public: GDALMDReaderGeoEye(const char *pszPath, char **papszSiblingFiles); virtual ~GDALMDReaderGeoEye(); virtual const bool HasRequiredFiles() const; virtual char** GetMetadataFiles() const; protected: virtual void LoadMetadata(); virtual const time_t GetAcquisitionTimeFromString(const char* pszDateTime); char **LoadRPCWktFile() const; char **LoadIMDWktFile() const; protected: CPLString m_osIMDSourceFilename; CPLString m_osRPBSourceFilename; }; #endif // READER_GEO_EYE_H_INCLUDED
[ "polimax at mail.ru" ]
polimax at mail.ru
bff0a1a53148c02ab3206d8abf72706c7595ad42
ac5efd0ab39d906e3386d7a2f118eb5aa640b01e
/leetcode/Combinations.cpp
8abe364a9676e9745f69934016588c5f6bc785f4
[]
no_license
erickingcs/Interview-Qs
acd0637fa326ffe21cf00f199d1dc4267f98526b
9f11120252aa4206b99615c7bcf77ca71bf21929
refs/heads/master
2021-01-21T00:22:13.181039
2013-05-06T12:27:27
2013-05-06T12:27:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
675
cpp
class Solution { public: void generate(vector<vector<int> > &ans, vector<int> &tuple, int now, int n, int k) { if (k == 0) { ans.push_back(tuple); return; } for (int i = now; i <= n; i++) { tuple.push_back(i); generate(ans, tuple, i + 1, n, k - 1); tuple.pop_back(); } } vector<vector<int> > combine(int n, int k) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > ans; vector<int> tuple(0); generate(ans, tuple, 1, n, k); return ans; } };
[ "watermelonlh@gmail.com" ]
watermelonlh@gmail.com
db5bc358da46ce8bb7e362c43356f49cfdb4e2f6
53e7f3022a2cf3730fb41da48ccf6f8a7ef40818
/test/cplus/iterator.cpp
0ff7a9cfcdcf98bd18595b11d4f29e321b0b77eb
[]
no_license
jeonjonghyeok/c-practice
f38d40303eb9902c505fb1e146a492d902a60397
97c5d9f0997ffb950584ecf24f83b8a50c428508
refs/heads/master
2023-03-07T21:59:49.175614
2021-02-18T16:46:37
2021-02-18T16:46:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
408
cpp
#include <iostream> #include <vector> using namespace std; int main(){ vector<int> v; v.push_back(10); v.push_back(20); v.push_back(30); v.push_back(40); v.push_back(50); vector<int>::iterator iter=v.begin(); cout << iter[3] << endl; iter += 2; cout << *iter << endl; cout << endl; for(iter = v.begin(); iter!=v.end();++iter) { cout << *iter << endl; } return 0; }
[ "tongher1685@gmail.com" ]
tongher1685@gmail.com
58535051a68ee2cc06b99a12a97dd0528b1747cf
9e21b7819881da8f916dbd0f3299253424a105a5
/include/third_party/WebKit/Source/core/inspector/InspectorAuditsAgent.h
b4eb7b7a0ab3b03f97306e3492973c9a16948ec3
[ "Apache-2.0" ]
permissive
yuske/spitfire
10cc76bedd72871d5cff1a441b20ed54fb03a926
e2e6c70d18473cb29b593e393681a28d03a5f1b3
refs/heads/master
2021-09-07T10:57:40.679242
2018-02-21T22:21:52
2018-02-21T22:21:52
104,356,972
0
0
null
2017-09-21T14:14:01
2017-09-21T14:14:01
null
UTF-8
C++
false
false
1,308
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef InspectorAuditsAgent_h #define InspectorAuditsAgent_h #include "core/CoreExport.h" #include "core/inspector/InspectorBaseAgent.h" #include "core/inspector/protocol/Audits.h" namespace blink { class CORE_EXPORT InspectorAuditsAgent final : public InspectorBaseAgent<protocol::Audits::Metainfo> { WTF_MAKE_NONCOPYABLE(InspectorAuditsAgent); public: explicit InspectorAuditsAgent(InspectorNetworkAgent*); ~InspectorAuditsAgent() override; void Trace(blink::Visitor*) override; // Protocol methods. protocol::Response getEncodedResponse(const String& request_id, const String& encoding, protocol::Maybe<double> quality, protocol::Maybe<bool> size_only, protocol::Maybe<String>* out_body, int* out_original_size, int* out_encoded_size) override; private: Member<InspectorNetworkAgent> network_agent_; }; } // namespace blink #endif // !defined(InspectorAuditsAgent_h)
[ "yuske.dev@gmail.com" ]
yuske.dev@gmail.com
69d4aeb80cf03b862c6d679f08a62332e7e41fca
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/inetsrv/iis/config/src/inc/catalogcollectionwriter.h
dd8f3a48e296f040aa92af41a63239153abd551f
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
839
h
#ifndef _CATALOGCOLLECTIONWRITER_H_ #define _CATALOGCOLLECTIONWRITER_H_ class CCatalogCollectionWriter { public: CCatalogCollectionWriter(); ~CCatalogCollectionWriter(); void Initialize(tTABLEMETARow* i_pCollection, CWriter* i_pcWriter); HRESULT GetPropertyWriter(tCOLUMNMETARow* i_pProperty, ULONG* i_aPropertySize, CCatalogPropertyWriter** o_pProperty); HRESULT WriteCollection(); private: HRESULT ReAllocate(); HRESULT BeginWriteCollection(); HRESULT EndWriteCollection(); CWriter* m_pCWriter; tTABLEMETARow m_Collection; CCatalogPropertyWriter** m_apProperty; ULONG m_cProperty; ULONG m_iProperty; }; // CCatalogCollectionWriter #endif // _CATALOGCOLLECTIONWRITER_H_
[ "112426112@qq.com" ]
112426112@qq.com
e96590c16490c4795c55ec2d0a50dbe29dcfa07f
6d1a022d7b639e9eaa8d1595a7897a70bc4b1d54
/eyesee-mpp/awcdr/apps/cdr/source/minigui-cpp/data/fast_delegate_bind.h
f2ffe78b1118c36f26914b0f4632d730df5df2be
[]
no_license
icprog/lindenis-v536-softwinner
c2673b155ab911e82c9c477be3a921c4d098c77d
2fdf6f7aef8b5e1e24a54650fe589e5b6208b24b
refs/heads/master
2020-12-26T06:16:25.103604
2020-01-20T05:32:18
2020-01-21T05:35:58
237,413,679
1
0
null
2020-01-31T11:08:11
2020-01-31T11:08:10
null
UTF-8
C++
false
false
9,498
h
/***************************************************************************** Copyright (C), 2015, AllwinnerTech. Co., Ltd. File name: fast_delegate_bind.h Author: yangy@allwinnertech.com Version: v1.0 Date: 2015-11-24 Description: History: *****************************************************************************/ // FastDelegateBind.h // Helper file for FastDelegates. Provides bind() function, enabling // FastDelegates to be rapidly compared to programs using boost::function and boost::bind. // // Documentation is found at http://www.codeproject.com/cpp/FastDelegate.asp // // Original author: Jody Hagins. // Minor changes by Don Clugston. // // Warning: The arguments to 'bind' are ignored! No actual binding is performed. // The behaviour is equivalent to boost::bind only when the basic placeholder // arguments _1, _2, _3, etc are used in order. // // HISTORY: // 1.4 Dec 2004. Initial release as part of FastDelegate 1.4. #ifndef FASTDELEGATEBIND_H #define FASTDELEGATEBIND_H #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //////////////////////////////////////////////////////////////////////////////// // FastDelegate bind() // // bind() helper function for boost compatibility. // (Original author: Jody Hagins). // // Add another helper, so FastDelegate can be a dropin replacement // for boost::bind (in a fair number of cases). // Note the elipses, because boost::bind() takes place holders // but FastDelegate does not care about them. Getting the place holder // mechanism to work, and play well with boost is a bit tricky, so // we do the "easy" thing... // Assume we have the following code... // using boost::bind; // bind(&Foo:func, &foo, _1, _2); // we should be able to replace the "using" with... // using fastdelegate::bind; // and everything should work fine... //////////////////////////////////////////////////////////////////////////////// #ifdef FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX namespace fastdelegate { //N=0 template <class X, class Y, class RetType> FastDelegate< RetType ( ) > bind( RetType (X::*func)( ), Y * y, ...) { return FastDelegate< RetType ( ) >(y, func); } template <class X, class Y, class RetType> FastDelegate< RetType ( ) > bind( RetType (X::*func)( ) const, Y * y, ...) { return FastDelegate< RetType ( ) >(y, func); } //N=1 template <class X, class Y, class RetType, class Param1> FastDelegate< RetType ( Param1 p1 ) > bind( RetType (X::*func)( Param1 p1 ), Y * y, ...) { return FastDelegate< RetType ( Param1 p1 ) >(y, func); } template <class X, class Y, class RetType, class Param1> FastDelegate< RetType ( Param1 p1 ) > bind( RetType (X::*func)( Param1 p1 ) const, Y * y, ...) { return FastDelegate< RetType ( Param1 p1 ) >(y, func); } //N=2 template <class X, class Y, class RetType, class Param1, class Param2> FastDelegate< RetType ( Param1 p1, Param2 p2 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2 ), Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2 ) >(y, func); } template <class X, class Y, class RetType, class Param1, class Param2> FastDelegate< RetType ( Param1 p1, Param2 p2 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2 ) const, Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2 ) >(y, func); } //N=3 template <class X, class Y, class RetType, class Param1, class Param2, class Param3> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3 ), Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3 ) >(y, func); } template <class X, class Y, class RetType, class Param1, class Param2, class Param3> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3 ) const, Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3 ) >(y, func); } //N=4 template <class X, class Y, class RetType, class Param1, class Param2, class Param3, class Param4> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3, Param4 p4 ), Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4 ) >(y, func); } template <class X, class Y, class RetType, class Param1, class Param2, class Param3, class Param4> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3, Param4 p4 ) const, Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4 ) >(y, func); } //N=5 template <class X, class Y, class RetType, class Param1, class Param2, class Param3, class Param4, class Param5> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 ), Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 ) >(y, func); } template <class X, class Y, class RetType, class Param1, class Param2, class Param3, class Param4, class Param5> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 ) const, Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 ) >(y, func); } //N=6 template <class X, class Y, class RetType, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 ), Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 ) >(y, func); } template <class X, class Y, class RetType, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 ) const, Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 ) >(y, func); } //N=7 template <class X, class Y, class RetType, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 ), Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 ) >(y, func); } template <class X, class Y, class RetType, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 ) const, Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 ) >(y, func); } //N=8 template <class X, class Y, class RetType, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7, class Param8> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 ), Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 ) >(y, func); } template <class X, class Y, class RetType, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7, class Param8> FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 ) > bind( RetType (X::*func)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 ) const, Y * y, ...) { return FastDelegate< RetType ( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 ) >(y, func); } #endif //FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX } // namespace fastdelegate #endif // !defined(FASTDELEGATEBIND_H)
[ "given@lindeni.com" ]
given@lindeni.com
a662ffc476a5902bfa223fce62d52022907983a1
057f2783821562579dea238c1073d0ba0839b402
/OCR/OCR/.localhistory/OCR/1477516997$ocr.cpp
c916318efdabfe9aaadbe53e1e069cf8901d0a57
[]
no_license
KrzysztofKozubek/Projects
6cafb2585796c907e8a818da4b51c97197ccbd11
66ef23fbc8a6e6cf3b6ef837b390d7f2113a9847
refs/heads/master
2023-02-07T12:24:49.155221
2022-10-08T18:39:58
2022-10-08T18:39:58
163,520,516
0
0
null
2023-02-04T17:46:12
2018-12-29T15:18:18
null
WINDOWS-1250
C++
false
false
9,049
cpp
#include "ocr.h" // TODO: 1. wyrownanie katu 2. erozja i dylatacja (moze filtr) pozbycie sie szumu // zmiana organizacji // OCR::OCR(QWidget *parent) : QMainWindow(parent) { /* Kontrast & Jasność & Obrót */ ui.setupUi(this); this->image = imread("lena.jpg", 1); showImage = image.clone(); connect(ui.HSContrast1, SIGNAL(sliderReleased()), this, SLOT(changeContrasOrBrightness())); connect(ui.HSBrightness1, SIGNAL(sliderReleased()), this, SLOT(changeContrasOrBrightness())); connect(ui.HSRotate1, SIGNAL(sliderReleased()), this, SLOT(rotate())); connect(ui.BConfirmChange1, SIGNAL(clicked()), this, SLOT(confirmChange())); connect(ui.BLoadImage1, SIGNAL(clicked()), this, SLOT(loadImage())); connect(ui.BSaveImage1, SIGNAL(clicked()), this, SLOT(saveImage())); connect(ui.BLoadImage3, SIGNAL(clicked()), this, SLOT(loadImage2())); connect(ui.HSBinaryElement3, SIGNAL(sliderReleased()), this, SLOT(preProcessing())); connect(ui.HSBinaryKernel3, SIGNAL(sliderReleased()), this, SLOT(preProcessing())); connect(ui.HSErodeElement3, SIGNAL(sliderReleased()), this, SLOT(preProcessing())); connect(ui.HSErodeKernel3, SIGNAL(sliderReleased()), this, SLOT(preProcessing())); connect(ui.BRightImageRow2, SIGNAL(clicked()), this, SLOT(SegmentationIncreaseIndexImageRow())); connect(ui.BLeftImageRow2, SIGNAL(clicked()), this, SLOT(SegmentationReduceIndexImageRow())); connect(ui.BRightImageCell2, SIGNAL(clicked()), this, SLOT(SegmentationIncreaseIndexImageCell())); connect(ui.BLeftImageCell2, SIGNAL(clicked()), this, SLOT(SegmentationReduceIndexImageCell())); connect(ui.BSaveImages2, SIGNAL(clicked()), this, SLOT(saveEffect())); displayImage(this->image.clone()); /* END Kontrast & Jasność & Obrót END */ /* Przetwarzanie wstpne */ this->imageSign = imread("digits12.jpg", CV_BGR2GRAY); this->imageSignO = imageSign.clone(); if(imageSign.type() == 0) imshow("Z", imageSign); waitKey(); //double angle = autorotate(imageSign.clone()); preProcessing(); /* END Przetwarzanie wstpene */ /* Segmentation */ /* END Segmentation END */ } OCR::~OCR() {} #pragma region void OCR::displayImageInLabel(Mat image, QLabel* label) { cvtColor(image, image, CV_GRAY2RGB); Size size(100, 100); QImage imdisplay((uchar*)image.data, image.cols, image.rows, image.step, QImage::Format_RGB888); QImage img2 = imdisplay.scaled(300, 1000, Qt::KeepAspectRatio); label->setPixmap(QPixmap::fromImage(img2)); } Mat OCR::loadImageFrom(QString pathToImage, int flag = 1) { return imread(QStringToString(pathToImage), flag); } #pragma endregion Unversal method #pragma region void OCR::rotate() { Mat tmp = image.clone(); CPreProcessing::rotate(tmp, ui.HSRotate1->value()); displayImage(tmp); } void OCR::changeContrasOrBrightness() { Mat tmp = image.clone(); CPreProcessing::changeContrasOrBrightness(tmp, ui.HSContrast1->value(), ui.HSBrightness1->value()); displayImage(tmp); } void OCR::displayImage(Mat image) { cvtColor(image, image, CV_BGR2RGB); QImage imdisplay((uchar*)image.data, image.cols, image.rows, image.step, QImage::Format_RGB888); ui.LImage1->setPixmap(QPixmap::fromImage(imdisplay)); } void OCR::confirmChange() { image.release(); image = showImage.clone(); } void OCR::loadImage() { Mat tmp = imread(QStringToString(ui.LEPathImageLoad1->text()), 1); if (!tmp.empty()) { image.release(); showImage.release(); image = tmp.clone(); showImage = tmp.clone(); displayImage(image); } } void OCR::saveImage() { imwrite(QStringToString(ui.LEPathImageSave1->text()), image); } #pragma endregion Tab Contrast & Brightness & Rotate #pragma region void OCR::loadImage2() { displayImageInLabel(loadImageFrom(ui.LEPathImageLoad3->text()), ui.LImage3); } void OCR::preProcessing() { Mat tmp = imageSignO.clone(); imageSign = tmp.clone(); CPreProcessing::erode(imageSign, 2, 4); //Binary //threshold(tmp, imageSign, ui.HSBinaryKernel3->value(), 255, ui.HSBinaryElement3->value()); CPreProcessing::toBinary(imageSign, ui.HSBinaryKernel3->value()); imshow("Z", imageSign); waitKey(); //Change angle tmp = imageSign.clone(); Point2f src_center(imageSign.cols / 2.0F, imageSign.rows / 2.0F); Mat rot_mat = getRotationMatrix2D(src_center, -0.5, 1.0); warpAffine(tmp, imageSign, rot_mat, imageSign.size()); //Erode CPreProcessing::erode(imageSign, ui.HSErodeElement3->value(), ui.HSErodeKernel3->value()); displayImageInLabel(imageSign.clone(), ui.LImage3); SegmentationRow(imageSign.clone()); } #pragma endregion Przetwarzanie wstępne #pragma region void OCR::SegmentationLoadImage() { Mat tmp = imread(QStringToString(ui.LEPathImageLoad3->text()), 1); if (!tmp.empty()) { image.release(); showImage.release(); image = tmp.clone(); showImage = tmp.clone(); displayImage(image); } } void OCR::SegmentationSaveImage() { imwrite(QStringToString(ui.LEPathImageSave1->text()), image); } void OCR::SegmentationRow(Mat image) { Mat tmp = imageSign.clone(); int LIMIT_VALUE_LIGHT_BIT = 42; vImageSignRow.clear(); int cols = image.cols; int rows = image.rows; int cutStart = 0, cutEnd = 0; //information about level cutting int fromCut = 0, toCut = 0; //save position column double sum = 0; for (int y = 0; y < rows - 1; y++) { sum = CPreProcessing::advRow(image, y, 15); if (LIMIT_VALUE_LIGHT_BIT >= sum) { if (cutStart == 0) fromCut = y; if (cutStart == 1 && cutEnd == 0) { toCut = y; cutEnd = 1; } if (cutStart == 1 && cutEnd == 1) { tmp = image.clone(); CPreProcessing::cutImage(tmp, 0, fromCut, 0, tmp.rows - toCut); CPreProcessing::removeBlackBackground(tmp); vImageSignRow.push_back(tmp); tmp.release(); cutStart = toCut = cutEnd = 0; fromCut = y; } } else { if (cutStart == 0) cutStart = 1; } } indexImageRow = 0; SegmentationLoadImageRow(); } void OCR::SegmentationCell(Mat image) { int LIMIT_VALUE_LIGHT_BIT = 55; Mat tmp; vImageSignCell.clear(); int cols = image.cols; int rows = image.rows; int cutStart = 0, cutEnd = 0; //information about level cutting int fromCut = 0, toCut = 0; //save position column int size = 65; string help; int sum = 0; for (int y = 0; y < cols - 1; y++) { sum = CPreProcessing::advCol(image, y, 5); if (LIMIT_VALUE_LIGHT_BIT <= sum) { if (cutStart == 0) fromCut = y; if (cutStart == 1 && cutEnd == 0) { toCut = y; cutEnd = 1; } if (cutStart == 1 && cutEnd == 1) { tmp = image.clone(); CPreProcessing::cutImage(tmp, fromCut, 0, tmp.cols - toCut, 0); CPreProcessing::cutImage(tmp, (tmp.cols / 2) - size, (tmp.rows / 2) - size, (tmp.cols / 2) - size, (tmp.rows / 2) - size); vImageSignCell.push_back(tmp); tmp.release(); cutStart = toCut = cutEnd = 0; fromCut = y; } } else { if (cutStart == 0) cutStart = 1; } } indexImageCell = 0; SegmentationLoadImageCell(); } void OCR::SegmentationIncreaseIndexImageRow() { if (indexImageRow < vImageSignRow.size()-1) { indexImageRow++; SegmentationLoadImageRow(); } } void OCR::SegmentationReduceIndexImageRow() { if (indexImageRow > 0) { indexImageRow--; SegmentationLoadImageRow(); } } void OCR::SegmentationIncreaseIndexImageCell() { if (indexImageCell < vImageSignCell.size()-1) { indexImageCell++; SegmentationLoadImageCell(); } } void OCR::SegmentationReduceIndexImageCell() { if (indexImageCell > 0) { indexImageCell--; SegmentationLoadImageCell(); } } void OCR::SegmentationLoadImageRow() { ui.LImageRow2->clear(); if(indexImageRow < vImageSignRow.size()){ Mat image = vImageSignRow[indexImageRow].clone(); QImage imdisplay((uchar*)image.data, image.cols, image.rows, image.step, QImage::Format_Grayscale8); QImage img2 = imdisplay.scaled(600, 1000, Qt::KeepAspectRatio); ui.LImageRow2->setPixmap(QPixmap::fromImage(img2)); SegmentationCell(vImageSignRow[indexImageRow].clone()); } } void OCR::SegmentationLoadImageCell() { if(indexImageCell < vImageSignCell.size()){ ui.LImageCell2->clear(); Mat image = vImageSignCell[indexImageCell].clone(); QImage imdisplay((uchar*)image.data, image.cols, image.rows, image.step, QImage::Format_Grayscale8); QImage img2 = imdisplay.scaled(400, 1000, Qt::KeepAspectRatio); ui.LImageCell2->setPixmap(QPixmap::fromImage(imdisplay)); } } void OCR::saveEffect() { //Nazewnictwo znaków digit0_<user>_<probka> //<user> = {0..20} //<probka> = {0..9} int digit = 0; int user = 0; int sample = 0; vector<Mat> vImages; for (int i = 0; i < vImageSignRow.size(); i++){ SegmentationCell(vImageSignRow[i]); for (int j = 0; j < vImageSignCell.size(); j++) { vImages.push_back(vImageSignCell[j]); } } string fileName; for (int i = 0; i < vImages.size(); i++){ fileName = ("digits//digit" + (itos(digit)) + "_" + (itos(user)) + "_" + (itos(sample)) + ".jpg"); imwrite(fileName, vImages[i]); sample++; if (sample == 10) { user++; sample = 0; } if (user > 20) { digit++; user = 0; } } } #pragma endregion Segmentation
[ "krzysztof.kozubek135@gmail.com" ]
krzysztof.kozubek135@gmail.com
c83ac03d4259722f85dc6ab35c70693e22474965
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-lex/include/aws/lex/LexRuntimeServiceEndpointRules.h
5e473b02439ac0229a865d4b901c7dfe5fb3077f
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
470
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <cstddef> #include <aws/lex/LexRuntimeService_EXPORTS.h> namespace Aws { namespace LexRuntimeService { class LexRuntimeServiceEndpointRules { public: static const size_t RulesBlobStrLen; static const size_t RulesBlobSize; static const char* GetRulesBlob(); }; } // namespace LexRuntimeService } // namespace Aws
[ "sdavtaker@users.noreply.github.com" ]
sdavtaker@users.noreply.github.com
547bc50ff3115f2fa0b70ef5404221c6c4f1b733
ce6229f5915f9e6de1238861b4a940d61e56960b
/Sonder/Temp/il2cppOutput/il2cppOutput/mscorlib_System_IO_FileLoadException3198361301.h
fe76a03ba1f71a9316c2bb7f15a68f1d1e6f408d
[ "Apache-2.0" ]
permissive
HackingForGood/GoogleyEyes
d9e36e3dffb4edbd0736ab49a764736a91ecebcf
a92b962ab220686794350560a47e88191e165c05
refs/heads/master
2021-04-15T10:03:59.093464
2017-06-25T17:32:52
2017-06-25T17:32:52
94,575,021
7
0
null
null
null
null
UTF-8
C++
false
false
2,031
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_IO_IOException2458421087.h" // System.String struct String_t; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IO.FileLoadException struct FileLoadException_t3198361301 : public IOException_t2458421087 { public: // System.String System.IO.FileLoadException::msg String_t* ___msg_12; // System.String System.IO.FileLoadException::fileName String_t* ___fileName_13; // System.String System.IO.FileLoadException::fusionLog String_t* ___fusionLog_14; public: inline static int32_t get_offset_of_msg_12() { return static_cast<int32_t>(offsetof(FileLoadException_t3198361301, ___msg_12)); } inline String_t* get_msg_12() const { return ___msg_12; } inline String_t** get_address_of_msg_12() { return &___msg_12; } inline void set_msg_12(String_t* value) { ___msg_12 = value; Il2CppCodeGenWriteBarrier(&___msg_12, value); } inline static int32_t get_offset_of_fileName_13() { return static_cast<int32_t>(offsetof(FileLoadException_t3198361301, ___fileName_13)); } inline String_t* get_fileName_13() const { return ___fileName_13; } inline String_t** get_address_of_fileName_13() { return &___fileName_13; } inline void set_fileName_13(String_t* value) { ___fileName_13 = value; Il2CppCodeGenWriteBarrier(&___fileName_13, value); } inline static int32_t get_offset_of_fusionLog_14() { return static_cast<int32_t>(offsetof(FileLoadException_t3198361301, ___fusionLog_14)); } inline String_t* get_fusionLog_14() const { return ___fusionLog_14; } inline String_t** get_address_of_fusionLog_14() { return &___fusionLog_14; } inline void set_fusionLog_14(String_t* value) { ___fusionLog_14 = value; Il2CppCodeGenWriteBarrier(&___fusionLog_14, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "anishdhesikan@gmail.com" ]
anishdhesikan@gmail.com
cf72e6b580802c8a94bd2a17a19208d95abf270b
9e5df111aec78973c26b525622cbcce0fd8eca0c
/UVA/11300-11399/11324.cpp
fb6284b82c115c3d153e1a566bf076c52a1d17ce
[]
no_license
zmix/ACM-Program
c9482d8895447788f051b89e9cd3d0c1b3bd1072
aad8c5ed5c1d733270870b06419ec9045b4b4686
refs/heads/master
2020-07-21T17:33:21.286268
2019-05-31T01:40:52
2019-05-31T01:40:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
875
cpp
#include <stdio.h> #include <string.h> #include <algorithm> #include <vector> using namespace std; #define N 1100 int n, m; int vis[N]; vector<int> G[N]; int dfs(int u) { vis[u] = 1; int ans = 1; for (int i = 0; i < G[u].size(); ++i) { if (!vis[G[u][i] ]) ans += dfs(G[u][i]); } return ans; } int main() { freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); int T; scanf("%d", &T); while (T--) { scanf("%d%d", &n, &m); for (int i = 0; i <= n; ++i) G[i].clear(); for (int i = 0; i < m; ++i) { int u, v; scanf("%d%d", &u, &v); G[u].push_back(v); } int ans = 0; for (int i = 1; i <= n; ++i) { memset(vis, 0, sizeof(vis)); ans = max(ans, dfs(i)); } printf("%d\n", ans); } return 0; }
[ "qazxswh111@163.com" ]
qazxswh111@163.com
944a75f03ed0b4fa13c97af09c8c2f94a63cc8a5
7974c1a8bbfe289af80965e507ed9c3a6121c534
/protocolo/src/Affin.cpp
57cb08977a60eac061dd6e56c5549ecd6858bd91
[]
no_license
alexa1999/todododo
b07018bb17ec27014f57a2c7eaec460103d883a9
c2ed02581bed8f51ae267b6abc39a0f7aae4472a
refs/heads/master
2021-01-25T09:09:22.975546
2018-10-23T14:58:06
2018-10-23T14:58:06
93,788,275
0
0
null
null
null
null
UTF-8
C++
false
false
3,191
cpp
#include <iostream> #include <string> #include "Affin.h" #include <vector> #include <stdlib.h> using namespace std; Affin::Affin() { tam_alf=alfabeto.size(); Generar(); //ctor } int Affin::mcd(int a,int b) { int r; while(r!=0) { r=a%b; a=b; b=r; } return a; } void Affin::Generar() { /*vector <int> tmp; for(int i=1;i<tam_alf;i++) { if(mcd(i,tam_alf)==1) { tmp.push_back(i); } }*/ //a=413; //b=10840; a=rand()%100; b=rand()%100; while(mcd(a,tam_alf)!=1) { a=rand()%100; } //a=2920; //b=66; } string Affin::cifradoAffin(string msn) { string resultado; //Generar(); //a=56; //b=40; for(int j=0;j<msn.size();j++) { int y; int x; x=alfabeto.find(msn[j]); if(a<0){a=modulo((tam_alf-a*(mcd(tam_alf,a))),tam_alf);} //if(a>tam_alf){a=modulo((a*mcd(tam_alf,a))-tam_alf,tam_alf);} if(b<0){b=modulo((tam_alf-b*(mcd(tam_alf,b))),tam_alf);} //if(b>tam_alf){b=modulo((b*mcd(tam_alf,b))-tam_alf,tam_alf);} y=modulo((a*x+b),tam_alf); resultado+=alfabeto[y]; } return resultado; } int Affin::modulo(int a,int n) { int r=a-(a/n)*n; if(n<0) return r+=n; return r; } //-------------------------------------------------------------// vector<int> Affin::euclides_Extendido(int a, int b)//s=inversa r1=mcd { vector<int> EE; int r1=a; int r2=b; int s1=1; int s2=0; int t1=0; int t2=1; int cociente,r,s,t; while(r2>0) { cociente=r1/r2; r=r1-(cociente*r2); r1=r2; r2=r; s=s1-(cociente*s2); s1=s2; s2=s; t=t1-(cociente*t2); t1=t2; t2=t; } s=s1; t=t1; r=r1; EE.push_back(s); EE.push_back(t); EE.push_back(r); //s=modulo(s,b); return EE; } int Affin::Inversa(int a,int n) { vector<int> I; int inversa; if(mcd(a,n)==1) { I=euclides_Extendido(a,n); inversa=I[0]; if(inversa<0){ inversa=modulo(inversa,n); } } //cout<<"INVERSA****: "<<inversa<<endl; return inversa; } string Affin::descifradoAffin(string msn) { string resultado; int a_euExten=Inversa(a,tam_alf); int x,y,tmp; /*if(a_euExten<0) { a_euExten=modulo((tam_alf-a_euExten*(mcd(tam_alf,a_euExten))),tam_alf); }*/ for(int j=0;j<msn.size();j++) { y=alfabeto.find(msn[j]); b=modulo(b,tam_alf); if(b<0){b=tam_alf+b;}else{b=b;} //if(b>tam_alf){b=modulo((b*mcd(tam_alf,b))-tam_alf,tam_alf);} tmp=(y-b); tmp=modulo(tmp,tam_alf); if(tmp<0) { tmp=tmp+tam_alf; } else{tmp=tmp;} //if(tmp<0){tmp=modulo((tam_alf-tmp*(mcd(tam_alf,tmp))),tam_alf);} x=modulo((a_euExten*tmp),tam_alf); resultado+=alfabeto[x]; } return resultado; } Affin::~Affin() { //dtor }
[ "noreply@github.com" ]
alexa1999.noreply@github.com
c60310f1f56b4f699a1e038fe881ab17ffb6be30
3fbe8d05207316fcdb59d9bface41b0a154660b0
/qip_2nd_semester/hw1/HW_histoStretch.cpp
69221017fc0003362e93a20bc5397a663b1ceca7
[]
no_license
dongliang3571/Senior_design_csc599866
7a6091ca9c63a0cc17212829cae10cfd19683ae5
d31a7ccae44e86c2ff6b4dce57cbe2637c585097
refs/heads/master
2020-12-24T08:46:13.871449
2017-01-04T22:53:34
2017-01-04T22:53:34
51,631,712
1
1
null
2017-01-04T22:53:35
2016-02-13T04:16:26
C++
UTF-8
C++
false
false
809
cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HW_histoStretch: // // Apply histogram stretching to I1. Output is in I2. // Stretch intensity values between t1 and t2 to fill the range [0,255]. // // Written by: Dong Liang, 2016 // void HW_histoStretch(ImagePtr I1, int t1, int t2, ImagePtr I2) { IP_copyImageHeader(I1, I2); int w = I1->width(); int h = I1->height(); int total = w * h; // compute lut[] int i, lut[MXGRAY]; for (i = 0; i < MXGRAY; i++) { lut[i] = CLIP(MaxGray * (i - t1) / (t2 - t1), 0, MaxGray); } int type; ChannelPtr<uchar> p1, p2, endd; for(int ch = 0; IP_getChannel(I1, ch, p1, type); ch++) { IP_getChannel(I2, ch, p2, type); for(endd = p1 + total; p1<endd;) *p2++ = lut[*p1++]; } }
[ "dongliang3571@gmail.com" ]
dongliang3571@gmail.com
b052b0ea7e4f406c49b1a1614c635e20e57e4a5f
7ec0f688286844ad2902365e438c0a181cc07e6c
/test/EventFireTests.cpp
7b7c8201062199029f256ce24ef38d726d168abe
[ "MIT" ]
permissive
gbmhunter/HearYeHearYe
c14b15b9e77fce9b408c533d310c46a16603617c
797b38d69b2f40979f27f589c9e7bfb57e96961f
refs/heads/master
2021-06-19T23:28:37.176807
2017-07-06T16:51:49
2017-07-06T16:51:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
795
cpp
#include "gtest/gtest.h" #include "HearYeHearYe/Event.hpp" using namespace mn::HearYeHearYe; namespace { class EventFireTests : public ::testing::Test { protected: EventFireTests() { } virtual ~EventFireTests() { } }; TEST_F(EventFireTests, VoidEvent) { Event<void()> event; bool listenerCalled = false; event.AddListener([&] () { listenerCalled = true; }); event.Fire(); EXPECT_TRUE(listenerCalled); } TEST_F(EventFireTests, VoidIntEvent) { Event<void(int)> event; int savedNum = 0; event.AddListener([&] (int value) { savedNum = value; }); event.Fire(2); EXPECT_EQ(savedNum, 2); } } // namespace
[ "ghunter@urthecast.com" ]
ghunter@urthecast.com
404a70c217ea98259ffc9921ebc216ea7f70d8d5
8ed946d292a2b0dcd3d1f9989464cdb861300fa2
/Hollow Rhombus 2.cpp
d8b3b419aee5083cfceec54206e60625463c7947
[]
no_license
ABasitIrfan/Intensive-Programming-Cpp-Basics
c8869be3cb9d7a5e995da01070fb1825c9122f53
c5b05fbecbdc6c96f40ef097d0d6e868efe8bb57
refs/heads/main
2023-02-12T04:06:45.763197
2021-01-10T10:07:09
2021-01-10T10:07:09
328,127,145
1
0
null
null
null
null
UTF-8
C++
false
false
216
cpp
#include<stdio.h> #include<conio.h> main() { int a,b,c; for(a=1;a<=5;a++) { for(b=1;b<a;b++) { printf(" "); } for(c=1;c<=5;c++) { printf("*"); } printf("\n"); } }
[ "noreply@github.com" ]
ABasitIrfan.noreply@github.com
457354a4b1d062de960c3609332691873d2ee081
62a79652961a4a7e8dab19b5dadb7f6715a17d9d
/src/rotatingheatsource/expliciteuler/adapters/PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1.cpp
ca7d9034e9d399ea6bf140ab1ceec83d94c2729a
[]
no_license
www5sccs/hpvc
624af022f817c028f64ff4c8c74370b18868499a
127dd71562c7d0aecda3bda0c1e8ea035151cde1
refs/heads/master
2021-03-12T22:48:37.594884
2013-04-26T16:28:15
2013-04-26T16:28:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,957
cpp
#include "rotatingheatsource/expliciteuler/adapters/PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1.h" #include <sstream> #include "peano/utils/Loop.h" #ifdef Parallel #include "tarch/parallel/Node.h" #endif int rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::_snapshotCounter = 0; peano::MappingSpecification rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::touchVertexLastTimeSpecification() { return peano::MappingSpecification(peano::MappingSpecification::Nop,peano::MappingSpecification::AvoidFineGridRaces,true); } peano::MappingSpecification rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::touchVertexFirstTimeSpecification() { return peano::MappingSpecification(peano::MappingSpecification::WholeTree,peano::MappingSpecification::Serial,false); } peano::MappingSpecification rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::enterCellSpecification() { return peano::MappingSpecification(peano::MappingSpecification::WholeTree,peano::MappingSpecification::Serial,false); } peano::MappingSpecification rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::leaveCellSpecification() { return peano::MappingSpecification(peano::MappingSpecification::Nop,peano::MappingSpecification::AvoidFineGridRaces,true); } peano::MappingSpecification rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::ascendSpecification() { return peano::MappingSpecification(peano::MappingSpecification::Nop,peano::MappingSpecification::AvoidFineGridRaces,true); } peano::MappingSpecification rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::descendSpecification() { return peano::MappingSpecification(peano::MappingSpecification::Nop,peano::MappingSpecification::AvoidFineGridRaces,true); } std::map<tarch::la::Vector<DIMENSIONS,double> , int, tarch::la::VectorCompare<DIMENSIONS> > rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::_vertex2IndexMap; rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1(): _vtkWriter(0), _vertexWriter(0), _cellWriter(0), _vertexValueWriter(0) { } rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::~PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1() { } #if defined(SharedMemoryParallelisation) rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1(const PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1& masterThread): _vtkWriter(masterThread._vtkWriter), _vertexWriter(masterThread._vertexWriter), _cellWriter(masterThread._cellWriter), _vertexValueWriter(masterThread._vertexValueWriter) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::mergeWithWorkerThread(const PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1& workerThread) { } #endif void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::plotVertex( const rotatingheatsource::expliciteuler::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS,double>& fineGridX ) { if ( fineGridVertex.getRefinementControl() != rotatingheatsource::expliciteuler::Vertex::Records::Refined && fineGridVertex.getRefinementControl() != rotatingheatsource::expliciteuler::Vertex::Records::Refining && _vertex2IndexMap.find(fineGridX) == _vertex2IndexMap.end() ) { #if defined(Dim2) || defined(Dim3) _vertex2IndexMap[fineGridX] = _vertexWriter->plotVertex(fineGridX); #else _vertex2IndexMap[fineGridX] = _vertexWriter->plotVertex(tarch::la::Vector<3,double>(fineGridX.data())); #endif _vertexValueWriter->plotVertex (_vertex2IndexMap[fineGridX],fineGridVertex.getRhs() ); } } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::createHangingVertex( rotatingheatsource::expliciteuler::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS,double>& fineGridX, const tarch::la::Vector<DIMENSIONS,double>& fineGridH, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex ) { plotVertex( fineGridVertex, fineGridX ); } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::destroyHangingVertex( const rotatingheatsource::expliciteuler::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS,double>& fineGridX, const tarch::la::Vector<DIMENSIONS,double>& fineGridH, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::createInnerVertex( rotatingheatsource::expliciteuler::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS,double>& fineGridX, const tarch::la::Vector<DIMENSIONS,double>& fineGridH, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::createBoundaryVertex( rotatingheatsource::expliciteuler::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS,double>& fineGridX, const tarch::la::Vector<DIMENSIONS,double>& fineGridH, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::destroyVertex( const rotatingheatsource::expliciteuler::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS,double>& fineGridX, const tarch::la::Vector<DIMENSIONS,double>& fineGridH, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::createCell( rotatingheatsource::expliciteuler::Cell& fineGridCell, rotatingheatsource::expliciteuler::Vertex * const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::destroyCell( const rotatingheatsource::expliciteuler::Cell& fineGridCell, rotatingheatsource::expliciteuler::Vertex * const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell ) { } #ifdef Parallel void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::mergeWithNeighbour( rotatingheatsource::expliciteuler::Vertex& vertex, const rotatingheatsource::expliciteuler::Vertex& neighbour, int fromRank, const tarch::la::Vector<DIMENSIONS,double>& fineGridX, const tarch::la::Vector<DIMENSIONS,double>& fineGridH, int level ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::prepareSendToNeighbour( rotatingheatsource::expliciteuler::Vertex& vertex, int toRank, const tarch::la::Vector<DIMENSIONS,double>& x, const tarch::la::Vector<DIMENSIONS,double>& h, int level ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::prepareCopyToRemoteNode( rotatingheatsource::expliciteuler::Vertex& localVertex, int toRank, const tarch::la::Vector<DIMENSIONS,double>& x, const tarch::la::Vector<DIMENSIONS,double>& h, int level ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::prepareCopyToRemoteNode( rotatingheatsource::expliciteuler::Cell& localCell, int toRank, const tarch::la::Vector<DIMENSIONS,double>& cellCentre, const tarch::la::Vector<DIMENSIONS,double>& cellSize, int level ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::mergeWithRemoteDataDueToForkOrJoin( rotatingheatsource::expliciteuler::Vertex& localVertex, const rotatingheatsource::expliciteuler::Vertex& masterOrWorkerVertex, int fromRank, const tarch::la::Vector<DIMENSIONS,double>& x, const tarch::la::Vector<DIMENSIONS,double>& h, int level ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::mergeWithRemoteDataDueToForkOrJoin( rotatingheatsource::expliciteuler::Cell& localCell, const rotatingheatsource::expliciteuler::Cell& masterOrWorkerCell, int fromRank, const tarch::la::Vector<DIMENSIONS,double>& x, const tarch::la::Vector<DIMENSIONS,double>& h, int level ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::prepareSendToWorker( rotatingheatsource::expliciteuler::Cell& fineGridCell, rotatingheatsource::expliciteuler::Vertex * const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell, int worker ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::prepareSendToMaster( rotatingheatsource::expliciteuler::Cell& localCell, rotatingheatsource::expliciteuler::Vertex * vertices, const peano::grid::VertexEnumerator& verticesEnumerator, const rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, const rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::mergeWithMaster( const rotatingheatsource::expliciteuler::Cell& workerGridCell, rotatingheatsource::expliciteuler::Vertex * const workerGridVertices, const peano::grid::VertexEnumerator& workerEnumerator, rotatingheatsource::expliciteuler::Cell& fineGridCell, rotatingheatsource::expliciteuler::Vertex * const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell, int worker, const rotatingheatsource::expliciteuler::State& workerState, rotatingheatsource::expliciteuler::State& masterState ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::receiveDataFromMaster( rotatingheatsource::expliciteuler::Cell& receivedCell, rotatingheatsource::expliciteuler::Vertex * receivedVertices, const peano::grid::VertexEnumerator& receivedVerticesEnumerator, rotatingheatsource::expliciteuler::Vertex * const receivedCoarseGridVertices, const peano::grid::VertexEnumerator& receivedCoarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& receivedCoarseGridCell, rotatingheatsource::expliciteuler::Vertex * const workersCoarseGridVertices, const peano::grid::VertexEnumerator& workersCoarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& workersCoarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::mergeWithWorker( rotatingheatsource::expliciteuler::Cell& localCell, const rotatingheatsource::expliciteuler::Cell& receivedMasterCell, const tarch::la::Vector<DIMENSIONS,double>& cellCentre, const tarch::la::Vector<DIMENSIONS,double>& cellSize, int level ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::mergeWithWorker( rotatingheatsource::expliciteuler::Vertex& localVertex, const rotatingheatsource::expliciteuler::Vertex& receivedMasterVertex, const tarch::la::Vector<DIMENSIONS,double>& x, const tarch::la::Vector<DIMENSIONS,double>& h, int level ) { } #endif void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::touchVertexFirstTime( rotatingheatsource::expliciteuler::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS,double>& fineGridX, const tarch::la::Vector<DIMENSIONS,double>& fineGridH, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex ) { plotVertex( fineGridVertex, fineGridX ); } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::touchVertexLastTime( rotatingheatsource::expliciteuler::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS,double>& fineGridX, const tarch::la::Vector<DIMENSIONS,double>& fineGridH, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::enterCell( rotatingheatsource::expliciteuler::Cell& fineGridCell, rotatingheatsource::expliciteuler::Vertex * const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell ) { #ifdef Parallel if (fineGridCell.isLeaf() && !fineGridCell.isAssignedToRemoteRank()) { #else if (fineGridCell.isLeaf()) { #endif assertion( DIMENSIONS==2 || DIMENSIONS==3 ); int vertexIndex[TWO_POWER_D]; dfor2(i) tarch::la::Vector<DIMENSIONS,double> currentVertexPosition = fineGridVerticesEnumerator.getVertexPosition(i); assertion4 ( _vertex2IndexMap.find(currentVertexPosition) != _vertex2IndexMap.end(), currentVertexPosition, fineGridCell.toString(), fineGridVerticesEnumerator.toString(), fineGridVertices[ fineGridVerticesEnumerator(i) ].toString() ); vertexIndex[iScalar] = _vertex2IndexMap[currentVertexPosition]; enddforx if (DIMENSIONS==2) { _cellWriter->plotQuadrangle(vertexIndex); } if (DIMENSIONS==3) { _cellWriter->plotHexahedron(vertexIndex); } } } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::leaveCell( rotatingheatsource::expliciteuler::Cell& fineGridCell, rotatingheatsource::expliciteuler::Vertex * const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::beginIteration( rotatingheatsource::expliciteuler::State& solverState ) { assertion( _vtkWriter==0 ); _vtkWriter = new tarch::plotter::griddata::unstructured::vtk::VTKTextFileWriter(); _vertexWriter = _vtkWriter->createVertexWriter(); _cellWriter = _vtkWriter->createCellWriter(); _vertexValueWriter = _vtkWriter->createVertexDataWriter("rhs",1); } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::endIteration( rotatingheatsource::expliciteuler::State& solverState ) { _vertexWriter->close(); _cellWriter->close(); _vertexValueWriter->close(); delete _vertexWriter; delete _cellWriter; delete _vertexValueWriter; _vertexWriter = 0; _cellWriter = 0; _vertexValueWriter = 0; std::ostringstream snapshotFileName; snapshotFileName << "rhs" #ifdef Parallel << "-rank-" << tarch::parallel::Node::getInstance().getRank() #endif << "-" << _snapshotCounter << ".vtk"; _vtkWriter->writeToFile( snapshotFileName.str() ); _snapshotCounter++; _vertex2IndexMap.clear(); delete _vtkWriter; _vtkWriter = 0; } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::descend( rotatingheatsource::expliciteuler::Cell * const fineGridCells, rotatingheatsource::expliciteuler::Vertex * const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell ) { } void rotatingheatsource::expliciteuler::adapters::PerformExplicitEulerTimeStepAndPlot2VTKPlotVertexValue_1::ascend( rotatingheatsource::expliciteuler::Cell * const fineGridCells, rotatingheatsource::expliciteuler::Vertex * const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, rotatingheatsource::expliciteuler::Vertex * const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, rotatingheatsource::expliciteuler::Cell& coarseGridCell ) { }
[ "wittmanr@in.tum.de" ]
wittmanr@in.tum.de
5d044cad707478a950abfbb0b13adb73ad6e4da8
df07a7af2464bd7ba6c0099d60f06ec65e1d9d80
/abc098/c_v2.cpp
35ecf3a763eb22a587b98164008b68010eea32e7
[]
no_license
a-lilas/atcoder
8d99ab7f8be3cd05a12823749efb68aa8a9692ba
4abc043cd6b16e7816949a72d16f524e1d91e69c
refs/heads/master
2021-06-25T20:35:55.192092
2019-04-29T09:27:40
2019-04-29T09:27:40
134,447,043
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
#include <iostream> #include <cmath> #include <vector> #include <queue> #include <string> #include <map> #include <ios> #include <iomanip> #include <limits> #include <algorithm> #include <sstream> #include <bitset> #define REP(i, n) for(int i=0; i<n; i++) #define FOR(i, s, n) for(int i=s; i<n; i++) using namespace std; int main(){ int N; string S; cin >> N; cin >> S; int W[N] = {}; int E[N] = {}; if (S[0] == 'W') W[0] = 1; else E[0] = 1; FOR(i, 1, N){ if (S[i] == 'W'){ W[i] = W[i-1] + 1; E[i] = E[i-1]; } else{ W[i] = W[i-1]; E[i] = E[i-1] + 1; } } int minans = E[N-1]; REP(i, N){ minans = min(minans, W[i] + E[N-1] - E[i]); } cout << minans << endl; }
[ "a-simada@ics.es.osaka-u.ac.jp" ]
a-simada@ics.es.osaka-u.ac.jp
a7c96c1117b072c75aca0d2249f298362c16b6a6
88d8e885fbd686d4ef35d444b80701cff6f43740
/AtCoderBeginnerContest/042/b.cpp
b24ee52f3caadb09172adc5d4c0c5539bda6c82a
[]
no_license
morishitamakoto0330/AtCoder
f18cf0804322775cbb5ee3ac958a8b5f129161c1
2c389f2809ec16cff4128dbbd985e3de94ad7309
refs/heads/master
2020-07-19T19:26:01.497595
2019-10-21T06:13:39
2019-10-21T06:13:39
206,501,162
0
0
null
null
null
null
UTF-8
C++
false
false
661
cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main(void) { int N, L, i; string str_tmp, ans; vector<string> S; // get input -------------------------------- cin >> N >> L; for(i = 0; i < N; i++) { cin >> str_tmp; S.push_back(str_tmp); } // sort ------------------------------------- sort(S.begin(), S.end()); // join ------------------------------------- ans = ""; for(i = 0 ; i < N; i++) { ans += S[i]; } // disp answer ------------------------------ cout << ans << endl; return 0; }
[ "morishita0330@gmail.com" ]
morishita0330@gmail.com
5e5ee04deb25f12663a29e0383e0ff7dcf72b0f0
4c23be1a0ca76f68e7146f7d098e26c2bbfb2650
/h2/3.8/H2O2
bd6a3d71997f6e0b8fe948c4e504db5625797c22
[]
no_license
labsandy/OpenFOAM_workspace
a74b473903ddbd34b31dc93917e3719bc051e379
6e0193ad9dabd613acf40d6b3ec4c0536c90aed4
refs/heads/master
2022-02-25T02:36:04.164324
2019-08-23T02:27:16
2019-08-23T02:27:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
834
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "3.8"; object H2O2; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField uniform 2.30129e-06; boundaryField { boundary { type empty; } } // ************************************************************************* //
[ "jfeatherstone123@gmail.com" ]
jfeatherstone123@gmail.com
8cfe3b659c083bb8bcbca8f2e6379f0e12674c9b
df2db9b10b66cf4c2f527f5aa9a38ba4d6af6622
/Galactic Polar Wars/src/TitleBackground.h
7b2bcbfe206bb5a9d6f7a929a7acc2daebbfda65
[]
no_license
vashj1995/Galactic-Polar-Wars-Final
f98147216e6cf4a5ae00b56908fc4936eec63a48
ebe0998e6cbba4e49473208d502c24e6bb82b272
refs/heads/main
2023-04-15T07:35:22.770821
2021-04-22T22:02:58
2021-04-22T22:02:58
359,535,746
0
0
null
null
null
null
UTF-8
C++
false
false
547
h
#pragma once #ifndef _TITLE_BACKGROUND_ #define _TITLE_BACKGROUND_ #include "DisplayObject.h" #include "TextureManager.h" class TitleBackground : public DisplayObject { private: public: // constructor(s) TitleBackground(); // destructor ~TitleBackground(); // life-cycle methods inherited from DisplayObject void draw() override; void update() override; void clean() override; //getters and setters void setDestination(glm::vec2 destination); private: //glm::vec2 m_destination; }; #endif /* defined (__FreezerBackground__) */
[ "vashj1995@yahoo.com" ]
vashj1995@yahoo.com
1fcd9662db2fb34537ad22e4f2f161e8ddba1b57
338bd4e9ffdb9ab7c260b4f23b20f51d91d4793b
/BattleBoard/vieMainWindow.h
16794465143e102d57a6727d709b46aa30841340
[]
no_license
Greykoil/BattleBoard
e17357b6566eeee8e2acbda1732b161f188d7d40
3796765ae1c2bf78a5b9a15de77138139c40e2ce
refs/heads/master
2021-05-07T15:27:39.189970
2018-03-08T13:15:01
2018-03-08T13:15:01
109,824,659
0
0
null
null
null
null
UTF-8
C++
false
false
1,617
h
//============================================================================= //D The apps main window // // Contains a tab list of the windows where things actually happen // //----------------------------------------------------------------------------- #pragma once // includes from project // QT ui include #include "ui_vieMainWindow.h" //includes from QT #include <QtWidgets/QMainWindow> #include <QDialog> // system includes #include <vector> #include <memory> // class predeclarations to avoid header file inclusion class vieCharacterWindow; class modCharacter; // types: classes, enums, typedefs //============================================================================= class vieMainWindow : public QMainWindow { Q_OBJECT public: vieMainWindow( modCharacter* character_model, QWidget *parent = Q_NULLPTR ); // Constructor vieMainWindow(const vieMainWindow&) = delete; // Deleted copy constructor. vieMainWindow& operator=(const vieMainWindow&) = delete; // Deleted assignment operator. virtual ~vieMainWindow() = default; // Destructor protected: void add_tabs(); // Add the list of tabs that the main window is using private slots: // The list of event actions that can happen // Actions from the file menu drop down void actionOpen(); void actionNew(); void actionSave(); void actionTabChanged(int index); private: modCharacter* m_model; std::vector<std::unique_ptr<QDialog>> m_tab_list; // The vector of tabs that this window is going to show Ui::MainWindowClass m_ui; // The ui helper class provided by the QT framework };
[ "alex.i.j.spencer@gmail.com" ]
alex.i.j.spencer@gmail.com
616a06a2a625330c797b57369d6f32c5c7c97764
c5287793dd57fe738ec7aa776a5bc3fba515ea14
/block1/Bar.h
58dac93c834ffb3a6c78354071da7d5b1d322ace
[]
no_license
makoty/myBlock
063a8ac6849243ca1c1fb1cd64859d4ebf2634eb
c144e6bda58589d5c4c4755329dc9b926e99d453
refs/heads/master
2021-01-20T22:26:12.231932
2016-07-26T12:44:53
2016-07-26T12:44:53
62,219,816
0
0
null
null
null
null
UTF-8
C++
false
false
293
h
#ifndef _BAR_H_ #define _BAR_H_ #include "Const.h" #include "BaseObject.h" class Bar : public BaseObject { public: static Bar& getInstance() { static Bar instance; return instance; } void addPos(short x, short y); private: Bar(); ~Bar(); }; #endif // _BAR_H_
[ "v-nishizaka@a-tm.co.jp" ]
v-nishizaka@a-tm.co.jp
efc4f9cd4bcfa847d9e1e37bef8bb0f52c6fbd84
aec08f03a4c200a8bf42cbfa2b9c04c46f5a3699
/src/programs/gsa/TornadoPlot.cpp
05df35d87447a10434bb1ddd1aca8c1cf957e98e
[ "LicenseRef-scancode-warranty-disclaimer", "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
dwelter/pestpp
0d1b51df904a14d50492dfe240b7272034f3a042
921d04b83f161787bfc2137baadfa665a6b1b48c
refs/heads/master
2021-01-24T09:34:48.682006
2018-08-04T20:11:35
2018-08-04T20:11:35
4,577,568
29
29
null
2019-03-28T01:00:26
2012-06-06T20:22:15
C++
UTF-8
C++
false
false
7,255
cpp
#include <vector> #include <cassert> #include <numeric> #include <math.h> #include <errno.h> #include <fstream> #include <iostream> #include <map> #include <vector> #include <algorithm> #include <regex> #include "TornadoPlot.h" #include "Transformable.h" #include "RunManagerAbstract.h" #include "ParamTransformSeq.h" #include "ModelRunPP.h" #include "utilities.h" #include "FileManager.h" using namespace std; using namespace pest_utils; TornadoPlot::TornadoPlot(const vector<string> &_adj_par_name_vec, const Parameters &_fixed_pars, const Parameters &_init_pars, const Parameters &_lower_bnd, const Parameters &_upper_bnd, const set<string> &_log_trans_pars, ParamTransformSeq *_base_partran_seq_ptr, const std::vector<std::string> &_obs_name_vec, FileManager *file_manager_ptr, const ObservationInfo *_obs_info_ptr, bool _calc_obs_sen) //: GsaAbstractBase(_base_partran_seq_ptr, _adj_par_name_vec, _fixed_pars, _lower_bnd, _upper_bnd, //_obs_name_vec, file_manager_ptr), init_pars(_init_pars), obs_info_ptr(_obs_info_ptr), calc_obs_sen(_calc_obs_sen) { log_trans_pars = _log_trans_pars; } void TornadoPlot::assemble_runs(RunManagerAbstract &run_manager) { Parameters pars = fixed_ctl_pars; pars.insert(init_pars); // Assemble run Based on the inital Parameter values Parameters tmp_pars; tmp_pars = pars; base_partran_seq_ptr->ctl2model_ip(tmp_pars); int run_id = run_manager.add_run(tmp_pars, "base_run", Parameters::no_data); // Assemble runs which perturb each parameter to its max and min value for (const auto &ipar : adj_par_name_vec) { tmp_pars = pars; double low_value = lower_bnd.get_rec(ipar); tmp_pars[ipar] = low_value; base_partran_seq_ptr->ctl2model_ip(tmp_pars); run_id = run_manager.add_run(tmp_pars, ipar + " L", Parameters::no_data); tmp_pars = pars; double hi_value = upper_bnd.get_rec(ipar); tmp_pars[ipar] = hi_value; base_partran_seq_ptr->ctl2model_ip(tmp_pars); run_id = run_manager.add_run(tmp_pars, ipar + " U", Parameters::no_data); } } void TornadoPlot::calc_sen(RunManagerAbstract &run_manager, ModelRun model_run) { int n_runs = run_manager.get_nruns(); bool run_ok = false; int run_status; string run_name; double par_value_not_used; cout << endl; if (n_runs <= 1) { cerr << "Can not perform tornado calculations: insufficient number of runs (" << n_runs << ")" << endl; return; } run_manager.get_info(0, run_status, run_name, par_value_not_used); if (run_status <= 0) { cerr << "Cannot perform tornado calculations: base run failed " << endl; return; } ofstream &fout_tor = file_manager_ptr->open_ofile_ext("tor"); tornado_calc(run_manager, model_run, fout_tor, ""); file_manager_ptr->close_file("tor"); ofstream &fout_toi = file_manager_ptr->open_ofile_ext("toi"); if (calc_obs_sen) { for (const string &iobs : obs_name_vec) { tornado_calc(run_manager, model_run, fout_toi, iobs); } } file_manager_ptr->close_file("toi"); } void TornadoPlot::tornado_calc(RunManagerAbstract &run_manager, ModelRun model_run, ofstream &fout, const string obs_name) { // if obs_name == "" compute Tornado Polt for the global phi. // Otherwise, compute Tornada Plot for the named observation. ModelRun base_run = model_run; ModelRun run1 = model_run; Parameters pars_init; Parameters pars; Observations obs; const vector<string> &run_mngr_obs_name_vec = run_manager.get_obs_name_vec(); int n_runs = run_manager.get_nruns(); bool run_ok = false; stringstream message; cout << endl; if (n_runs <= 1) { cerr << "Can not perform tornado calculations: insufficient number of runs (" << n_runs << ")" << endl; return; } run_ok = run_manager.get_run(0, pars_init, obs); if (!run_ok) { cerr << "Cannot perform tornado calculations: base run failed " << endl; return; } base_partran_seq_ptr->model2ctl_ip(pars_init); model_run.update_ctl(pars_init, obs); double phi_base = 0; if (obs_name.empty()) { phi_base = model_run.get_phi(DynamicRegularization::get_zero_reg_instance()); } else { phi_base = obs[obs_name]; } int run_status; string par_name; string run_name; char run_type; double par_value_not_used; map<string, map<string, double> > phi_tornado_map; for (const auto &ipar : adj_par_name_vec) { phi_tornado_map[ipar] = map<string, double>(); } for (int i_run = 1; i_run < n_runs; ++i_run) { std::cout << string(message.str().size(), '\b'); message.str(""); message << "processing run " << i_run + 1 << " / " << n_runs; std::cout << message.str(); run_manager.get_info(i_run, run_status, run_name, par_value_not_used); strip_ip(run_name); run_type = run_name.back(); par_name = run_name.substr(0, run_name.size() - 2); run_ok = run_manager.get_run(i_run, pars, obs); if (run_ok) { base_partran_seq_ptr->model2ctl_ip(pars); double phi; if (obs_name.empty()) { model_run.update_ctl(pars, obs); phi= model_run.get_phi(DynamicRegularization::get_zero_reg_instance()); } else { phi = obs[obs_name]; } if (run_type == 'L') { phi_tornado_map[par_name]["lo"] = phi; } else if (run_type == 'U') { phi_tornado_map[par_name]["hi"] = phi; } } } //sort tornado plots vector< pair<string, double> > phi_range_vec; for (const auto &irec : phi_tornado_map) { double range = 0; map<string, double>::const_iterator map_end = irec.second.end(); map<string, double>::const_iterator iter_lo = irec.second.find("lo"); map<string, double>::const_iterator iter_hi = irec.second.find("hi"); if (iter_lo != map_end && iter_hi != map_end) { range = max(iter_hi->second, max(phi_base, iter_lo->second)) - min(iter_hi->second, min(phi_base, iter_lo->second)); range = abs(range); } else if (iter_hi != map_end) { range = iter_hi->second - phi_base; range = abs(range); } else if (iter_lo != map_end) { range = phi_base - iter_lo->second; range = abs(range); } phi_range_vec.push_back(make_pair(irec.first, range)); } std::sort(phi_range_vec.begin(), phi_range_vec.end(), [](pair<string, double> a, pair<string, double> b) { return std::abs(a.second) > std::abs(b.second); }); if (obs_name.empty()) { fout << "Observation: Global Phi" << endl; } else { fout << "Observation: " << obs_name << endl; } fout << "parameter_name, phi_lo, phi_init, phi_hi, par_lo, par_init, par_hi" << endl; for (const auto &i : phi_range_vec) { const string &par_name = i.first; const auto irec = phi_tornado_map.find(par_name); if (irec != phi_tornado_map.end()) { map<string, double>::const_iterator map_end = irec->second.end(); map<string, double>::const_iterator iter_lo = irec->second.find("lo"); map<string, double>::const_iterator iter_hi = irec->second.find("hi"); stringstream phi_hi; if (iter_hi != map_end) { phi_hi << iter_hi->second; } else { phi_hi << "na"; } stringstream phi_lo; if (iter_lo != map_end) { phi_lo << iter_lo->second; } else { phi_lo << "na"; } fout << par_name << ", " << phi_lo.str() << ", " << phi_base << ", " << phi_hi.str() << ", " << lower_bnd[par_name] << ", " << init_pars[par_name] << ", " << upper_bnd[par_name] << endl; } } } TornadoPlot::~TornadoPlot() { }
[ "dwelter1@bellsouth.net" ]
dwelter1@bellsouth.net
0136c1606fd769b0120cbf10444d3ac13217ddad
c603e00f13957e726f2e94a53a19b268ea0f60d7
/code/Uncertainty/FPG/FPG/source/planner/BrazilAlg.h
47643a0541cd264accbcb4031b38adc11f752c9b
[]
no_license
xuanjianwu/plantool
97015351670732297b5fbe742395c228b7e5ddba
4fe56c6ff8897690cc2a3f185901dfe3faeb819a
refs/heads/master
2021-01-21T20:39:03.688983
2017-05-30T00:57:44
2017-05-30T00:57:44
91,229,802
2
0
null
2017-05-14T08:24:03
2017-05-14T08:24:03
null
UTF-8
C++
false
false
1,345
h
/* * $Id: BrazilState.cpp 107 2006-07-27 03:31:12Z owen $ * * This file is part of the Brazil Planner. Copyright NICTA 2006. * * This file is commercial in confidence. You should no be looking at * it unless you are an employee of NICTA, a student who has signed * their IP to NICTA, or you have signed an NDA covering the Brazil * source code. If you are not one of these people we will poke out * your eyes with a gerkhin while forcing you to sing the Brazilian * national anthem. * */ #ifndef _BrazilAlg_h #define _BrazilAlg_h #include<PGBasics.hh> #include<RLAlg.hh> #include<OLPomdp.hh> #include<GOALPomdp.hh> #include"PlanningListener.h" /** * BrazilAlg is essentially the GOALPomdp alg from the libpg library, * but we need one small change. If there's a PlanningListener we need * to get a most likely plan every so often during optimisation. */ class BrazilAlg : public GOALPomdp { public: BrazilAlg(Controller* controller, Simulator* simulator, double discount, double stepSize) : GOALPomdp(controller, simulator, discount, stepSize) {}; virtual ~BrazilAlg() {}; virtual double learnCore(int stepsPerEpoch, int& totalSteps); virtual void printPerformanceInfo(bool printTitles, int steps, double avgReward, double maxParam, int seconds); }; #endif
[ "787499313@qq.com" ]
787499313@qq.com
97da6cb80324cfa36bd37cf177e908733eca2d4d
785df77400157c058a934069298568e47950e40b
/applications/shapeFit/section/tnbShapeFitSection.cxx
6f167b38d41cc355c21c2d85fb7fb7ad1024d7b3
[]
no_license
amir5200fx/Tonb
cb108de09bf59c5c7e139435e0be008a888d99d5
ed679923dc4b2e69b12ffe621fc5a6c8e3652465
refs/heads/master
2023-08-31T08:59:00.366903
2023-08-31T07:42:24
2023-08-31T07:42:24
230,028,961
9
3
null
2023-07-20T16:53:31
2019-12-25T02:29:32
C++
UTF-8
C++
false
false
12,113
cxx
#include <PtdShapeFit_Section.hxx> #include <PtdShapeFit2d_ScatterMap.hxx> #include <PtdShapeFit_Par.hxx> #include <Global_File.hxx> #include <TnbError.hxx> #include <OSstream.hxx> #include <Galgo.hpp> #include <Standard_Real.hxx> namespace tnbLib { static std::shared_ptr<PtdShapeFit_Section> mySection; static std::shared_ptr<PtdShapeFit2d_ScatterMap> myScatters; static std::shared_ptr<galgo::GeneticAlgorithm<double>> myGA; static double myMutationRate = 0.15; static double myCrossOverRate = 0.5; static int myNbElites = 1; static int myPopSize = 50; static int myNbGens = 40; static unsigned short verbose(0); static bool loadTag = false; static bool exeTag = false; class OptRunTime { /*Private Data*/ std::shared_ptr<galgo::GeneticAlgorithm<double>> theGA_; std::shared_ptr<PtdShapeFit_Section> theSection_; std::shared_ptr<PtdShapeFit2d_ScatterMap> theScatters_; public: // constructor [2/10/2023 Payvand] OptRunTime(); // Public functions and operators [2/10/2023 Payvand] void Perform(); }; void setVerbose(unsigned int i) { Info << endl; Info << " - the verbosity level is set to: " << i << endl; verbose = i; } void setMaxNbGens(int n) { myNbGens = n; if (verbose) { Info << endl << " - the max. no. of gens is set to: " << myNbGens << endl; } } void setPopSize(int n) { myPopSize = n; if (verbose) { Info << endl << " - the pop. size is set to: " << myPopSize << endl; } } void setMutation(double x) { myMutationRate = x; if (verbose) { Info << endl << " - the mutation is set to: " << myMutationRate << endl; } } void setCrossOverRate(double x) { myCrossOverRate = x; if (verbose) { Info << endl << " - the cross over rate is set to: " << myCrossOverRate << endl; } } void checkFolder(const std::string& name) { if (NOT boost::filesystem::is_directory(name)) { FatalErrorIn(FunctionSIG) << "no {" << name << "} directory has been found!" << endl << abort(FatalError); } } void loadSection() { checkFolder("section"); const auto currentPath = boost::filesystem::current_path(); // change the current path [2/7/2023 Payvand] boost::filesystem::current_path(currentPath.string() + R"(\section)"); if (file::IsFile(boost::filesystem::current_path(), ".PATH")) { auto name = file::GetSingleFile(boost::filesystem::current_path(), ".PATH").string(); fileName fn(name + ".PATH"); std::ifstream myFile; myFile.open(fn); if (myFile.is_open()) { std::string address; std::getline(myFile, address); // change the current path [2/6/2023 Payvand] boost::filesystem::current_path(address); { auto name = file::GetSingleFile(boost::filesystem::current_path(), PtdShapeFit_Section::extension).string(); mySection = file::LoadFile<std::shared_ptr<PtdShapeFit_Section>>(name + PtdShapeFit_Section::extension, verbose); if (NOT mySection) { FatalErrorIn(FunctionSIG) << " the section is null." << endl << abort(FatalError); } } } else { FatalErrorIn(FunctionSIG) << "the file is not open: " << name + ".PATH" << endl; } } else { auto name = file::GetSingleFile(boost::filesystem::current_path(), PtdShapeFit_Section::extension).string(); mySection = file::LoadFile<std::shared_ptr<PtdShapeFit_Section>>(name + PtdShapeFit_Section::extension, verbose); if (NOT mySection) { FatalErrorIn(FunctionSIG) << " the section is null." << endl << abort(FatalError); } } //- change back the current path boost::filesystem::current_path(currentPath); } void loadScatterMap() { checkFolder("scatters"); const auto currentPath = boost::filesystem::current_path(); // change the current path [2/7/2023 Payvand] boost::filesystem::current_path(currentPath.string() + R"(\scatters)"); if (file::IsFile(boost::filesystem::current_path(), ".PATH")) { auto name = file::GetSingleFile(boost::filesystem::current_path(), ".PATH").string(); fileName fn(name + ".PATH"); std::ifstream myFile; myFile.open(fn); if (myFile.is_open()) { std::string address; std::getline(myFile, address); // change the current path [2/6/2023 Payvand] boost::filesystem::current_path(address); { auto name = file::GetSingleFile(boost::filesystem::current_path(), PtdShapeFit2d_ScatterMap::extension).string(); myScatters = file::LoadFile<std::shared_ptr<PtdShapeFit2d_ScatterMap>>(name + PtdShapeFit2d_ScatterMap::extension, verbose); if (NOT myScatters) { FatalErrorIn(FunctionSIG) << " the scatter map is null." << endl << abort(FatalError); } } } else { FatalErrorIn(FunctionSIG) << "the file is not open: " << name + ".PATH" << endl; } } else { auto name = file::GetSingleFile(boost::filesystem::current_path(), PtdShapeFit2d_ScatterMap::extension).string(); myScatters = file::LoadFile<std::shared_ptr<PtdShapeFit2d_ScatterMap>>(name + PtdShapeFit2d_ScatterMap::extension, verbose); if (NOT myScatters) { FatalErrorIn(FunctionSIG) << " the scatter map is null." << endl << abort(FatalError); } } //- change back the current path boost::filesystem::current_path(currentPath); } void loadSectionFile(const std::string& name) { file::CheckExtension(name); mySection = file::LoadFile<std::shared_ptr<PtdShapeFit_Section>>(name + PtdShapeFit_Section::extension, verbose); if (NOT mySection) { FatalErrorIn(FunctionSIG) << " the section is null." << endl << abort(FatalError); } } void loadScatterMapFile(const std::string& name) { file::CheckExtension(name); myScatters = file::LoadFile<std::shared_ptr<PtdShapeFit2d_ScatterMap>>(name + PtdShapeFit2d_ScatterMap::extension, verbose); if (NOT myScatters) { FatalErrorIn(FunctionSIG) << " the scatter map is null." << endl << abort(FatalError); } } void loadFiles() { if (boost::filesystem::is_directory("section")) { loadSection(); } else { auto name = file::GetSingleFile(boost::filesystem::current_path(), PtdShapeFit_Section::extension).string(); loadSectionFile(name); } if (boost::filesystem::is_directory("scatters")) { loadScatterMap(); } else { auto name = file::GetSingleFile(boost::filesystem::current_path(), PtdShapeFit2d_ScatterMap::extension).string(); loadScatterMapFile(name); } loadTag = true; } void saveTo(const std::string& name) { if (NOT exeTag) { FatalErrorIn(FunctionSIG) << "the application is not performed!" << endl << abort(FatalError); } file::CheckExtension(name); file::SaveTo(mySection, name + PtdShapeFit_Section::extension, verbose); } void execute() { if (NOT loadTag) { Info << endl << " no file has been loaded." << endl << abort(FatalError); } OptRunTime ga; ga.Perform(); exeTag = true; if (verbose) { Info << endl << " - the application is performed." << endl; } } } tnbLib::OptRunTime::OptRunTime() { theGA_ = std::make_shared<galgo::GeneticAlgorithm<double>>(myPopSize, myNbGens, true); theSection_ = mySection; theScatters_ = myScatters; } void tnbLib::OptRunTime::Perform() { auto costFun = [this](const std::vector<double>& xs) -> std::vector<double> { try { auto cost = theSection_->CalcError(xs, theScatters_); return { -cost }; } catch (const Standard_Failure& x) { Info << x.GetMessageString() << endl; return { RealFirst() }; } catch (...) { Info << " Unknown Error has been detected." << endl; return { RealFirst() }; } }; myGA = theGA_; /**/ auto variables = mySection->RetrieveParList(); int idx = 0; for (const auto& x : variables) { if (NOT x) { FatalErrorIn(FunctionSIG) << "variable is null." << endl << abort(FatalError); } const auto lower = x->LowerVal(); const auto upper = x->UpperVal(); //std::cout << x->Name() << ": " << lower << ", " << upper << std::endl; galgo::Parameter<double> par({ lower,upper }); myGA->param.emplace_back(new galgo::Parameter<double>(par)); myGA->lowerBound.push_back(lower); myGA->upperBound.push_back(upper); if (idx == 0) { myGA->idx.push_back(idx); } else { myGA->idx.push_back(myGA->idx.at(idx - 1) + par.size()); } idx++; } //std::exit(1); myGA->Objective = costFun; myGA->genstep = 1; myGA->mutrate = myMutationRate; myGA->nbparam = variables.size(); myGA->nbbit = variables.size() * 16; myGA->covrate = myCrossOverRate; const int nbElits = myNbElites; //myGA->elitpop = nbElits == 0 ? 1 : nbElits; myGA->run(); const auto& bestResult = myGA->pop(0)->getParam(); mySection->SetParameters(bestResult); const auto& bestParams = mySection->Pars(); if (verbose) { Info << endl; for (const auto& x : bestParams->x) { Info << " - " << x.name << ": " << x.x << endl; } } if (verbose) { Info << endl << " the application is performed, successfully!" << endl; } } #ifdef DebugInfo #undef DebugInfo #endif // DebugInfo #include <chaiscript/chaiscript.hpp> namespace tnbLib { typedef std::shared_ptr<chaiscript::Module> module_t; void setFunctions(const module_t& mod) { //- io functions mod->add(chaiscript::fun([](const std::string& name)-> void {saveTo(name); }), "saveTo"); mod->add(chaiscript::fun([]()-> void {loadFiles(); }), "loadFiles"); //- settings mod->add(chaiscript::fun([](unsigned short i)->void {verbose = i; }), "setVerbose"); mod->add(chaiscript::fun([](double x)-> void {setCrossOverRate(x); }), "setCrossOverRate"); mod->add(chaiscript::fun([](int n)-> void {setMaxNbGens(n); }), "setNbGens"); mod->add(chaiscript::fun([](double x)->void {setMutation(x); }), "setMutationRate"); mod->add(chaiscript::fun([](int n)-> void {setPopSize(n); }), "setPopSize"); // operators [2/10/2023 Payvand] mod->add(chaiscript::fun([]()-> void {execute(); }), "execute"); } std::string getString(char* argv) { std::string argument(argv); return std::move(argument); } Standard_Boolean IsEqualCommand(char* argv, const std::string& command) { auto argument = getString(argv); return argument IS_EQUAL command; } } using namespace tnbLib; int main(int argc, char* argv[]) { //sysLib::init_gl_marine_integration_info(); FatalError.throwExceptions(); if (argc <= 1) { Info << " - No command is entered" << endl << " - For more information use '--help' command" << endl; FatalError.exit(); } if (argc IS_EQUAL 2) { if (IsEqualCommand(argv[1], "--help")) { Info << endl; Info << " This application is aimed to fit a parametric section to scatters." << endl << " - files: section, scatterMap" << endl; Info << endl << " Function list:" << endl << endl << " # IO functions: " << endl << endl << " - loadFiles()" << endl << " - saveTo(name)" << endl << endl << " # Settings: " << endl << endl << " - setCrossOverRate(x)" << endl << " - setMutationRate(x)" << endl << " - setNbGens(n)" << endl << " - setPopSize(n)" << endl << " - setVerbose(unsigned int); - Levels: 0, 1" << endl << endl << " # operators: " << endl << endl << " - execute()" << endl << endl; return 0; } else if (IsEqualCommand(argv[1], "--run")) { chaiscript::ChaiScript chai; auto mod = std::make_shared<chaiscript::Module>(); setFunctions(mod); chai.add(mod); //std::string address = ".\\system\\mesh2dToPlt"; try { fileName myFileName(file::GetSystemFile("tnbShapeFitSection")); chai.eval_file(myFileName); return 0; } catch (const chaiscript::exception::eval_error& x) { Info << x.pretty_print() << endl; } catch (const error& x) { Info << x.message() << endl; } catch (const std::exception& x) { Info << x.what() << endl; } } } else { Info << " - No valid command is entered" << endl << " - For more information use '--help' command" << endl; FatalError.exit(); } return 1; }
[ "aasoleimani86@gmail.com" ]
aasoleimani86@gmail.com
26487956f42c35e13773c56dc735b6eb94367b33
9eb2245869dcc3abd3a28c6064396542869dab60
/benchspec/CPU/523.xalancbmk_r/build/build_base_mytest-64.0001/XalanEntity.cpp
1a4c93bd929fc9aaa711319447b2624de934aa08
[]
no_license
lapnd/CPU2017
882b18d50bd88e0a87500484a9d6678143e58582
42dac4b76117b1ba4a08e41b54ad9cfd3db50317
refs/heads/master
2023-03-23T23:34:58.350363
2021-03-24T10:01:03
2021-03-24T10:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
cpp
version https://git-lfs.github.com/spec/v1 oid sha256:d8376ec06acf29a7aa809690c903c0b69f7861e162a499573aa4084a48c459e8 size 1103
[ "abelardojarab@gmail.com" ]
abelardojarab@gmail.com
82bc08b9aac5592f66f892f8c533507c6dad1dbe
02b4e557cc3514b94be16928035ed2725cc798b9
/rococo-dst/deptran/batch_start_args_helper.cc
ab593f3c5facf7d2d08cf1acb60312511ce5842f
[ "Apache-2.0" ]
permissive
yanghaomai/dst
b0286d04bd76b7c30d2d065a5f84033c5ca69000
897b929a692642cbf295c105d9d6e64090abb673
refs/heads/main
2023-04-06T19:59:11.487927
2021-04-12T13:19:10
2021-04-12T13:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,940
cc
#include "all.h" namespace rococo { //BatchStartArgsHelper::BatchStartArgsHelper(std::vector<Value> *arg) : arg_(arg) { //} // BatchStartArgsHelper::BatchStartArgsHelper() { arg_type_ = ARG_NONE; } int BatchStartArgsHelper::init_input(std::vector<Value> const *input, uint32_t num_piece) { if (arg_type_ != ARG_NONE) return -1; arg_type_ = ARG_INPUT; index_ = 0; piece_count_ = 0; num_piece_ = num_piece; input_ = input; return 0; } int BatchStartArgsHelper::get_next_input(i32 *p_type, i64 *pid, Value const** input, i32 *input_size, i32 *output_size) { verify(arg_type_ == ARG_INPUT); if (piece_count_ >= num_piece_) return -1; *p_type = (*input_)[index_++].get_i32(); *pid = (*input_)[index_++].get_i64(); *input_size = (*input_)[index_++].get_i32(); *output_size = (*input_)[index_++].get_i32(); *input = input_->data() + index_; index_ += *input_size; piece_count_++; return 0; } int BatchStartArgsHelper::init_output(std::vector<Value> *output, uint32_t num_piece, uint32_t expected_output_size) { if (arg_type_ != ARG_NONE) return -1; arg_type_ = ARG_OUTPUT; index_ = 0; piece_count_ = 0; num_piece_ = num_piece; output_ = output; output_->resize(num_piece * 2 + expected_output_size); return 0; } Value *BatchStartArgsHelper::get_output_ptr() { verify(arg_type_ == ARG_OUTPUT); return output_->data() + index_ + 2; } int BatchStartArgsHelper::put_next_output(i32 res, i32 output_size) { verify(arg_type_ == ARG_OUTPUT); if (piece_count_ >= num_piece_) return -1; (*output_)[index_++] = Value(res); (*output_)[index_++] = Value(output_size); index_ += output_size; piece_count_++; return 0; } int BatchStartArgsHelper::done_output() { verify(arg_type_ == ARG_OUTPUT); if (piece_count_ < num_piece_) return -1; output_->resize(index_); return 0; } int BatchStartArgsHelper::init_input_client(std::vector<Value> *input, uint32_t num_piece, uint32_t input_size) { if (arg_type_ != ARG_NONE) return -1; arg_type_ = ARG_INPUT_CLIENT; index_ = 0; piece_count_ = 0; num_piece_ = num_piece; input_client_ = input; input_client_->resize(num_piece * 4 + input_size); return 0; } int BatchStartArgsHelper::put_next_input_client(std::vector<Value> &input, i32 p_type, i64 pid, i32 output_size) { verify(arg_type_ = ARG_INPUT_CLIENT); if (piece_count_ >= num_piece_) return -1; (*input_client_)[index_++] = Value(p_type); (*input_client_)[index_++] = Value(pid); (*input_client_)[index_++] = Value((i32)input.size()); (*input_client_)[index_++] = Value(output_size); size_t i = 0; for (; i < input.size(); i++) (*input_client_)[index_++] = input[i]; piece_count_++; return 0; } int BatchStartArgsHelper::done_input_client() { verify(arg_type_ == ARG_INPUT_CLIENT); if (piece_count_ == num_piece_ && index_ == input_client_->size()) return 0; return -1; } int BatchStartArgsHelper::init_output_client(std::vector<Value> *output, uint32_t num_piece) { if (arg_type_ != ARG_NONE) return -1; arg_type_ = ARG_OUTPUT_CLIENT; index_ = 0; piece_count_ = 0; num_piece_ = num_piece; output_client_ = output; return 0; } int BatchStartArgsHelper::get_next_output_client(i32 *res, Value const** output, uint32_t *output_size) { verify(arg_type_ == ARG_OUTPUT_CLIENT); if (piece_count_ >= num_piece_) return -1; *res = (*output_client_)[index_++].get_i32(); i32 output_size_buf; output_size_buf = (*output_client_)[index_++].get_i32(); *output_size = (uint32_t)output_size_buf; *output = output_client_->data() + index_; index_ += output_size_buf; piece_count_++; return 0; } }
[ "wxdwfc@gmail.com" ]
wxdwfc@gmail.com
b11519934991f4dcc6b0cf5525ad85b25a82bad6
c094d381422c2788d67a3402cff047b464bf207b
/Algorithms in C/Algorithms in C/p072链表插入排序.cpp
4c577dba2c03c2fc1388b5f41e01785044693524
[]
no_license
liuxuanhai/C-code
cba822c099fd4541f31001f73ccda0f75c6d9734
8bfeab60ee2f8133593e6aabfeefaf048357a897
refs/heads/master
2020-04-18T04:26:33.246444
2016-09-05T08:32:33
2016-09-05T08:32:33
67,192,848
1
0
null
null
null
null
GB18030
C++
false
false
2,461
cpp
#include <stdio.h> #include <time.h> #include <stdlib.h> typedef struct node *link; typedef int item; struct node { item Item; link next; }; // 倒置链表 link reverse(link); // 返回尾node的指针 int main(void) { struct node headin, headout; // headin, 输入链表哑节点, 包含未排序数据, headout, 输出链表哑节点, 包含排序数据; int i; int N; // 要排序的数据项个数 // 输入项目个数 printf_s("输入项目个数: "); scanf_s("%d", &N); // 产生随机值, 保存在headin链中 link currentin = &headin; // "当前"操作节点为输入表哑节点 srand((unsigned long)time(0)); for (i = 0; i < N; i++) { currentin->next = (link)malloc(sizeof(node)); // "当前"操作节点为新节点 currentin = currentin->next; currentin->next = NULL; currentin->Item = rand() % 1000; } // 输出headin链的数据 currentin = headin.next; // "当前"为输入哑节点后边的一个项 for (i = 0; i < N; i++) { printf ("%d ", currentin->Item); currentin = currentin->next; } // 将headin链的node一个一个的插入到headout链中 link nextin; link currentout; headout.next = NULL; for (currentin = headin.next, headin.next = NULL; currentin != NULL; currentin = nextin) // 一直循环到输入链没有数据节点 { nextin = currentin->next; // 寻找headout中合适的插入位置 for (currentout = &headout; currentout->next != NULL; currentout = currentout->next) if (currentout->next->Item > currentin->Item) break; // 进行插入 currentin->next = currentout->next; currentout->next = currentin; } // 输出headout链 printf("\n\n\n\n"); currentout = headout.next; for (i = 0; i < N; i++) { printf ("%d ", currentout->Item); currentout = currentout->next; } // 倒置链表 printf("\n\n\n\n"); currentout = reverse(&headout);; for (i = 0; i < N; i++) { printf ("%d ", currentout->Item); currentout = currentout->next; } return 0; } link reverse(link li) { link Current, Next, Prev; Prev = NULL; Current = li; while (Current != NULL) { // 生成"下一个"节点 Next = Current->next; // 没有在上面初始化Next是考虑到Current下面没有node的情况, 在这里初始化表明, 只有在Current != NULL的情况下才有Next的存在; // 链接倒置 Current->next = Prev; // 刷新"上一个"和"当前"节点 Prev = Current; Current = Next; } return Prev; }
[ "heabking@gmail.com" ]
heabking@gmail.com
eba4d0edea9cf7d52b29e97e8a9d6ef769a97f7d
a504b543d48a2518c770920cc5f8efce7c91ede8
/angrybird/Box2D/birdred.cpp
75029fe9aa4cddfec0ccda1f877dbb56b8a4c4e5
[]
no_license
YifangYu/pd2-Angrybird
f3ab29db365771232b11f015f7f457ee7eb47fc0
e7d444bf0ab80ea22e26c6c5d19a7a47529cdc40
refs/heads/master
2020-05-29T15:06:36.978232
2016-06-19T15:47:16
2016-06-19T15:47:16
61,477,967
0
0
null
null
null
null
UTF-8
C++
false
false
46
cpp
#include "birdred.h" BirdRed::BirdRed() { }
[ "尤怡方" ]
尤怡方
e81f643c0e0f410a6193baf497097800c7f65540
0a9fbcf64062f0118d2e6b8b5d6e6a66a9a0299d
/PSYCHON.cpp
fb7a9db19ed2dd90d5c7c5e5e5799a81e94505aa
[]
no_license
mayank2903/SPOJSolutions
1991a7dddae4d7f8d0ba2caeab8cfb20fbee1415
c3a1e723c228e83d34ed8794f57c4f9a6ad16e7d
refs/heads/master
2016-09-09T21:54:24.181944
2015-02-01T00:45:18
2015-02-01T00:45:18
30,131,657
1
2
null
null
null
null
UTF-8
C++
false
false
1,711
cpp
#include <iostream> #include <cmath> using namespace std; #define ll unsigned long long #define MAX 10000000 #define LMT 3200 unsigned flag[MAX/64]; unsigned prime[664581], total; #define chkC(n) (flag[n>>6]&(1<<((n>>1)&31))) #define setC(n) (flag[n>>6]|=(1<<((n>>1)&31))) void sieve() { unsigned i, j, k; for(i=3;i<LMT;i+=2) if(!chkC(i)) for(j=i*i,k=i<<1;j<MAX;j+=k) setC(j); prime[1] = 2; for(i=3,j=2;i<MAX;i+=2) { if(!chkC(i)) { prime[j++] = i; } } total = j; } int f(int a) { unsigned int v=0; int h=a; int cntev=0; int cntod=0; for(int j=1,t=prime[j];t*t<=h; t = prime[++j]) { v=0; if(h%t==0) { while(h%t==0) { v++; h/=t; } if(v%2==0) cntev++; else cntod++; } if(h==1) break; } if(h!=1) cntod++; if(cntev>cntod) return 1; else return 0; } int main() { sieve(); int t,a; scanf("%d",&t); while(t--) { scanf("%d",&a); int cnt=f(a); if(cnt==1) printf("Psycho Number\n"); else printf("Ordinary Number\n"); } return 0; }
[ "pc.mayank@gmail.com" ]
pc.mayank@gmail.com
6e207908e2b9353a73a0b9e78a053e3e554962c6
3fbfd657c903442e0c08ace629f560e07a22c2eb
/GTreeLevel.cpp
4b721db6883468b65644bab9609dc098402a6999
[]
no_license
izhbannikov/FPSYNT
03461750f52fe5791d979604521060ba6fffad81
0d6df898be3b0e8ba8cc28421feb75895628deb5
refs/heads/master
2016-09-10T00:39:12.232105
2013-03-06T21:42:29
2013-03-06T21:42:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
238
cpp
/* * File: GTreeLevel.cpp * Author: ilya * * Created on 3 Ноябрь 2011 г., 19:34 */ #include "GTreeLevel.h" GTreeLevel::GTreeLevel() { } GTreeLevel::GTreeLevel(const GTreeLevel& orig) { } GTreeLevel::~GTreeLevel() { }
[ "i.zhbannikov@gmail.com" ]
i.zhbannikov@gmail.com
4ca0f7c65ed4eb4cd1f9651e983c6536c7ac0524
fd10d9751c5ef6cbcad14c0bf2ba3a92bc08de78
/analyzer/DanglingDelegateCommon.cpp
dadffd5486e0d25af6d69e3f8902611f6ef3b920
[ "BSD-3-Clause", "NCSA" ]
permissive
harite/facebook-clang-plugins
963a33cbd984d5519154fdc4c674415f72a7cee8
3faedd34d17438ff177270acd7ca7c6d84e8d3f6
refs/heads/master
2021-01-18T03:48:28.901789
2015-09-09T12:38:51
2015-09-09T13:55:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,950
cpp
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <clang/StaticAnalyzer/Core/Checker.h> #include <clang/StaticAnalyzer/Core/BugReporter/BugType.h> #include <clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h> #include <clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h> #include "DanglingDelegateCommon.h" using namespace clang; using namespace ento; namespace DanglingDelegate { const ObjCInterfaceDecl *getCurrentTopClassInterface(const CheckerContext &context) { const StackFrameContext *sfc = context.getStackFrame(); while (sfc && !sfc->inTopFrame()) { sfc = sfc->getParent()->getCurrentStackFrame(); } if (!sfc) { return NULL; } const ObjCMethodDecl *md = dyn_cast_or_null<ObjCMethodDecl>(sfc->getDecl()); if (!md) { return NULL; } return md->getClassInterface(); } // strips expressions a bit more than IgnoreParenImpCasts const Expr *ignoreOpaqueValParenImpCasts(const Expr *expr) { if (!expr) { return NULL; } const Expr *E = expr; do { expr = E; E = E->IgnoreParenImpCasts(); const OpaqueValueExpr *ove = dyn_cast_or_null<OpaqueValueExpr>(E); if (ove) { E = ove->getSourceExpr(); } } while (E != NULL && E != expr); return E; } bool isObjCSelfExpr(const Expr *expr) { expr = ignoreOpaqueValParenImpCasts(expr); if (!expr) { return false; } return expr->isObjCSelfExpr(); } const Expr *getArgOfObjCMessageExpr(const ObjCMessageExpr &expr, unsigned index) { if (expr.getNumArgs() < index + 1) { return NULL; } return expr.getArg(index); } const std::string getPropertyNameFromSetterSelector(const Selector &selector) { StringRef selectorStr = selector.getAsString(); // fancy names for setters are not supported if (!selectorStr.startswith("set")) { return ""; } std::string propName = selectorStr.substr(3, selectorStr.size()-4); if (propName.size() < 1) { return ""; } char x = propName[0]; propName[0] = (x >= 'A' && x <= 'Z' ? x - 'A' + 'a' : x); return propName; } const ObjCPropertyDecl *matchObjCMessageWithPropertyGetter(const ObjCMessageExpr &expr) { const ObjCMethodDecl *methDecl = expr.getMethodDecl(); if (!methDecl) { return NULL; } if (!methDecl->isPropertyAccessor() || methDecl->param_size() != 0) { return NULL; } const ObjCInterfaceDecl *intDecl = expr.getReceiverInterface(); if (!intDecl) { return NULL; } StringRef propName = expr.getSelector().getAsString(); IdentifierInfo &ii = intDecl->getASTContext().Idents.get(propName); return intDecl->FindPropertyDeclaration(&ii); } const ObjCPropertyDecl *matchObjCMessageWithPropertySetter(const ObjCMessageExpr &expr) { const ObjCMethodDecl *methDecl = expr.getMethodDecl(); if (!methDecl) { return NULL; } if (!methDecl->isPropertyAccessor() || methDecl->param_size() != 1) { return NULL; } const ObjCInterfaceDecl *intDecl = expr.getReceiverInterface(); if (!intDecl) { return NULL; } Selector selector = expr.getSelector(); std::string propName = getPropertyNameFromSetterSelector(selector); if (propName == "") { return NULL; } IdentifierInfo &II = intDecl->getASTContext().Idents.get(propName); return intDecl->FindPropertyDeclaration(&II); } // matches expressions _x and self.x const ObjCIvarDecl *matchIvarLValueExpression(const Expr &expr) { const Expr *normExpr = ignoreOpaqueValParenImpCasts(&expr); if (!normExpr) { return NULL; } // ivar? const ObjCIvarRefExpr *ivarRef = dyn_cast<ObjCIvarRefExpr>(normExpr); if (ivarRef) { return ivarRef->getDecl(); } // getter on self? const PseudoObjectExpr *poe = dyn_cast<PseudoObjectExpr>(normExpr); if (!poe) { return NULL; } const ObjCPropertyRefExpr *pre = dyn_cast_or_null<ObjCPropertyRefExpr>(poe->getSyntacticForm()); if (!pre) { return NULL; } // we want a getter corresponding to a real ivar of the current class if (!pre->isMessagingGetter() || pre->isImplicitProperty()) { return NULL; } const Expr *base = ignoreOpaqueValParenImpCasts(pre->getBase()); if (!base || !base->isObjCSelfExpr()) { return NULL; } ObjCPropertyDecl *propDecl = pre->getExplicitProperty(); if (!propDecl) { return NULL; } return propDecl->getPropertyIvarDecl(); } // matches [NSNotificationCenter defaultCenter] etc and make a string out of it const std::string matchObservableSingletonObject(const Expr &expr) { const ObjCMessageExpr *msg = dyn_cast_or_null<ObjCMessageExpr>(ignoreOpaqueValParenImpCasts(&expr)); if (!msg || msg->getReceiverKind() != ObjCMessageExpr::Class || !msg->getReceiverInterface()) { return ""; } std::string intName = msg->getReceiverInterface()->getNameAsString(); std::string selectorStr = msg->getSelector().getAsString(); if (intName == "NSNotificationCenter" && selectorStr == "defaultCenter") { return "+[" + intName + " " + selectorStr + "]"; } return ""; } bool isKnownToBeNil(const clang::ento::SVal &sVal, clang::ento::CheckerContext &context) { Optional<DefinedSVal> dv = sVal.getAs<DefinedSVal>(); if (dv) { ConstraintManager &manager = context.getConstraintManager(); ProgramStateRef stateNotNull = manager.assume(context.getState(), *dv, true); if (!stateNotNull) { // the value cannot be "not null" return true; } } return false; } } // end of namespace
[ "mathieubaudet@fb.com" ]
mathieubaudet@fb.com
dfc10408119d862074952612e53e7bc5c330b30c
fa65e06f2674281d1327640bdb4248e32433a0c3
/2ºAno/1ºSemestre/POO/pratica/aula_19_10_2020/aula_19_10_2020/aula1.cpp
203a8a45e108cdd8cffa9aba14981e1d1b2ac3da
[]
no_license
Coutinho020/Apontamentos-ISEC
18598165e5e68ec09df8ed973067f33a486af89e
0a9d54282a52ce195214cd8fef4513247e0ea4af
refs/heads/master
2023-08-24T00:58:09.928213
2021-10-24T15:33:37
2021-10-24T15:33:37
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,316
cpp
#include <iostream> #include <string> #include <sstream> using namespace std; #define N 15 struct Tabela { int mat[N]; }; void preenches(Tabela &t, int n) { for (int i = 0; i < N; i++) { t.mat[i] = n; } } void mostras(Tabela t) { for (int i = 0; i < N; i++) { cout << t.mat[i] << endl; } } int elementoAt(Tabela t, int pos) { if (pos > 0 && pos < N) { return t.mat[pos]; } else { return 0; } } bool mudaElemento(Tabela &t, int pos, int valor) { if (pos > 0 && pos < N) { t.mat[pos] = valor; return true; } else { return false; } } string &maisCurta(string &s1, string &s2) { if (s1.size() < s2.size()) { return s1; } else { return s2; } } int &elementoEm(Tabela &t, int pos) { if (pos > 0 && pos < N) { return t.mat[pos]; } else { return t.mat[0]; } } /* int main() { Tabela t; preenches(t, 10); */ //mostras(t); //cout << elementoAt(t, 3) << endl; /* if (mudaElemento(t, 3, 3)) { cout << elementoAt(t, 3) << endl; } else { cout << "Não mudou" << endl; } */ /* string a = "Bruno Teixeira"; string b = "bom dia"; cout << maisCurta(a,b) << endl; maisCurta(a, b) = "vou mudar"; cout << maisCurta(a, b) << endl; */ /* cout << elementoEm(t, 10) << endl;; elementoEm(t, 10) = 15; cout << elementoEm(t, 10) << endl; return 0; } */
[ "brunoalexandre3@hotmail.com" ]
brunoalexandre3@hotmail.com
2f75cf3cb6fa27440a0ae3394f14cccd7170f08f
b72698e6ff8c36a35e34dd5c80f3499e59ca5169
/libs/system/include/mrpt/system/WorkerThreadsPool.h
fd890a404fd973e97806445e8358644205b62864
[ "BSD-3-Clause" ]
permissive
jolting/mrpt
1d76a8811bbf09866bc9620fe720383f3badd257
2cfcd3a97aebd49290df5405976b15f8923c35cb
refs/heads/develop
2023-04-10T01:39:58.757569
2021-02-06T17:57:26
2021-02-06T17:57:26
54,604,509
1
2
BSD-3-Clause
2023-04-04T01:28:54
2016-03-24T01:15:39
C++
UTF-8
C++
false
false
3,038
h
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2021, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #pragma once #include <atomic> #include <condition_variable> #include <cstdint> #include <functional> #include <future> #include <mutex> #include <queue> #include <thread> #include <vector> namespace mrpt::system { /** * @brief A simple thread pool * * \note Partly based on: https://github.com/progschj/ThreadPool (ZLib license) */ class WorkerThreadsPool { public: enum queue_policy_t : uint8_t { /** Default policy: all tasks are executed in FIFO order */ POLICY_FIFO, /** If a task arrives and there are more pending tasks than worker threads, drop previous tasks. */ POLICY_DROP_OLD }; WorkerThreadsPool() = default; WorkerThreadsPool(std::size_t num_threads, queue_policy_t p = POLICY_FIFO) : policy_(p) { resize(num_threads); } ~WorkerThreadsPool() { clear(); } void resize(std::size_t num_threads); void clear(); //!< Stops all working jobs /** Enqueue one new working item, to be executed by threads when any is * available. */ template <class F, class... Args> auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; /** Returns the number of enqueued tasks, currently waiting for a free * working thread to process them. */ std::size_t pendingTasks() const noexcept; private: std::vector<std::thread> threads_; std::atomic_bool do_stop_{false}; std::mutex queue_mutex_; std::condition_variable condition_; std::queue<std::function<void()>> tasks_; queue_policy_t policy_{POLICY_FIFO}; }; template <class F, class... Args> auto WorkerThreadsPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<return_type()>>( std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<return_type> res = task->get_future(); { std::unique_lock<std::mutex> lock(queue_mutex_); // don't allow enqueueing after stopping the pool if (do_stop_) throw std::runtime_error("enqueue on stopped ThreadPool"); // policy check: drop pending tasks if we have more tasks than threads if (policy_ == POLICY_DROP_OLD) { while (tasks_.size() >= threads_.size()) { tasks_.pop(); } } // Enqeue the new task: tasks_.emplace([task]() { (*task)(); }); } condition_.notify_one(); return res; } } // namespace mrpt::system
[ "joseluisblancoc@gmail.com" ]
joseluisblancoc@gmail.com
b74821cfe112d700fc61d445fbdf83832be25dd3
5b1dd5d3cc755696c75a423da841daf2aa39afb5
/aliyun-api-ess/2014-08-28/src/ali_ess_describe_scheduled_tasks.cc
50c9a8b4da75caccc4b1878ff21e2806f42da5b7
[ "Apache-2.0" ]
permissive
aliyun-beta/aliyun-openapi-cpp-sdk
1c61ffd2f0f85fb149ba9941c77e193f5db4d364
5e708130870a27e0c749777118f9e26ace96e7d9
refs/heads/master
2016-08-12T06:21:57.634675
2015-12-15T08:14:59
2015-12-15T08:14:59
47,530,214
5
4
null
null
null
null
UTF-8
C++
false
false
12,745
cc
#include <stdio.h> #include "ali_api_core.h" #include "ali_string_utils.h" #include "ali_ess.h" #include "json/value.h" #include "json/reader.h" using namespace aliyun; namespace { void Json2Type(const Json::Value& value, std::string* item); void Json2Type(const Json::Value& value, EssDescribeScheduledTasksScheduledTaskType* item); void Json2Type(const Json::Value& value, EssDescribeScheduledTasksResponseType* item); template<typename T> class Json2Array { public: Json2Array(const Json::Value& value, std::vector<T>* vec) { if(!value.isArray()) { return; } for(int i = 0; i < value.size(); i++) { T val; Json2Type(value[i], &val); vec->push_back(val); } } }; void Json2Type(const Json::Value& value, std::string* item) { *item = value.asString(); } void Json2Type(const Json::Value& value, EssDescribeScheduledTasksScheduledTaskType* item) { if(value.isMember("ScheduledTaskId")) { item->scheduled_task_id = value["ScheduledTaskId"].asString(); } if(value.isMember("ScheduledTaskName")) { item->scheduled_task_name = value["ScheduledTaskName"].asString(); } if(value.isMember("Description")) { item->description = value["Description"].asString(); } if(value.isMember("ScheduledAction")) { item->scheduled_action = value["ScheduledAction"].asString(); } if(value.isMember("RecurrenceEndTime")) { item->recurrence_end_time = value["RecurrenceEndTime"].asString(); } if(value.isMember("LaunchTime")) { item->launch_time = value["LaunchTime"].asString(); } if(value.isMember("RecurrenceType")) { item->recurrence_type = value["RecurrenceType"].asString(); } if(value.isMember("RecurrenceValue")) { item->recurrence_value = value["RecurrenceValue"].asString(); } if(value.isMember("LaunchExpirationTime")) { item->launch_expiration_time = value["LaunchExpirationTime"].asInt(); } if(value.isMember("TaskEnabled")) { item->task_enabled = value["TaskEnabled"].asBool(); } } void Json2Type(const Json::Value& value, EssDescribeScheduledTasksResponseType* item) { if(value.isMember("TotalCount")) { item->total_count = value["TotalCount"].asInt(); } if(value.isMember("PageNumber")) { item->page_number = value["PageNumber"].asInt(); } if(value.isMember("PageSize")) { item->page_size = value["PageSize"].asInt(); } if(value.isMember("ScheduledTasks") && value["ScheduledTasks"].isMember("ScheduledTask")) { Json2Array<EssDescribeScheduledTasksScheduledTaskType>(value["ScheduledTasks"]["ScheduledTask"], &item->scheduled_tasks); } } } int Ess::DescribeScheduledTasks(const EssDescribeScheduledTasksRequestType& req, EssDescribeScheduledTasksResponseType* response, EssErrorInfo* error_info) { std::string str_response; int status_code; int ret = 0; bool parse_success = false; std::string secheme = this->use_tls_ ? "https" : "http"; AliRpcRequest* req_rpc = new AliRpcRequest(version_, appid_, secret_, secheme + "://" + host_); if((!this->use_tls_) && this->proxy_host_ && this->proxy_host_[0]) { req_rpc->SetHttpProxy( this->proxy_host_); } Json::Value val; Json::Reader reader; req_rpc->AddRequestQuery("Action","DescribeScheduledTasks"); if(!req.owner_id.empty()) { req_rpc->AddRequestQuery("OwnerId", req.owner_id); } if(!req.resource_owner_account.empty()) { req_rpc->AddRequestQuery("ResourceOwnerAccount", req.resource_owner_account); } if(!req.resource_owner_id.empty()) { req_rpc->AddRequestQuery("ResourceOwnerId", req.resource_owner_id); } if(!req.page_number.empty()) { req_rpc->AddRequestQuery("PageNumber", req.page_number); } if(!req.page_size.empty()) { req_rpc->AddRequestQuery("PageSize", req.page_size); } if(!req.scheduled_action1.empty()) { req_rpc->AddRequestQuery("ScheduledAction.1", req.scheduled_action1); } if(!req.scheduled_action2.empty()) { req_rpc->AddRequestQuery("ScheduledAction.2", req.scheduled_action2); } if(!req.scheduled_action3.empty()) { req_rpc->AddRequestQuery("ScheduledAction.3", req.scheduled_action3); } if(!req.scheduled_action4.empty()) { req_rpc->AddRequestQuery("ScheduledAction.4", req.scheduled_action4); } if(!req.scheduled_action5.empty()) { req_rpc->AddRequestQuery("ScheduledAction.5", req.scheduled_action5); } if(!req.scheduled_action6.empty()) { req_rpc->AddRequestQuery("ScheduledAction.6", req.scheduled_action6); } if(!req.scheduled_action7.empty()) { req_rpc->AddRequestQuery("ScheduledAction.7", req.scheduled_action7); } if(!req.scheduled_action8.empty()) { req_rpc->AddRequestQuery("ScheduledAction.8", req.scheduled_action8); } if(!req.scheduled_action9.empty()) { req_rpc->AddRequestQuery("ScheduledAction.9", req.scheduled_action9); } if(!req.scheduled_action10.empty()) { req_rpc->AddRequestQuery("ScheduledAction.10", req.scheduled_action10); } if(!req.scheduled_action11.empty()) { req_rpc->AddRequestQuery("ScheduledAction.11", req.scheduled_action11); } if(!req.scheduled_action12.empty()) { req_rpc->AddRequestQuery("ScheduledAction.12", req.scheduled_action12); } if(!req.scheduled_action13.empty()) { req_rpc->AddRequestQuery("ScheduledAction.13", req.scheduled_action13); } if(!req.scheduled_action14.empty()) { req_rpc->AddRequestQuery("ScheduledAction.14", req.scheduled_action14); } if(!req.scheduled_action15.empty()) { req_rpc->AddRequestQuery("ScheduledAction.15", req.scheduled_action15); } if(!req.scheduled_action16.empty()) { req_rpc->AddRequestQuery("ScheduledAction.16", req.scheduled_action16); } if(!req.scheduled_action17.empty()) { req_rpc->AddRequestQuery("ScheduledAction.17", req.scheduled_action17); } if(!req.scheduled_action18.empty()) { req_rpc->AddRequestQuery("ScheduledAction.18", req.scheduled_action18); } if(!req.scheduled_action19.empty()) { req_rpc->AddRequestQuery("ScheduledAction.19", req.scheduled_action19); } if(!req.scheduled_action20.empty()) { req_rpc->AddRequestQuery("ScheduledAction.20", req.scheduled_action20); } if(!req.scheduled_task_id1.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.1", req.scheduled_task_id1); } if(!req.scheduled_task_id2.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.2", req.scheduled_task_id2); } if(!req.scheduled_task_id3.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.3", req.scheduled_task_id3); } if(!req.scheduled_task_id4.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.4", req.scheduled_task_id4); } if(!req.scheduled_task_id5.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.5", req.scheduled_task_id5); } if(!req.scheduled_task_id6.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.6", req.scheduled_task_id6); } if(!req.scheduled_task_id7.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.7", req.scheduled_task_id7); } if(!req.scheduled_task_id8.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.8", req.scheduled_task_id8); } if(!req.scheduled_task_id9.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.9", req.scheduled_task_id9); } if(!req.scheduled_task_id10.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.10", req.scheduled_task_id10); } if(!req.scheduled_task_id11.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.11", req.scheduled_task_id11); } if(!req.scheduled_task_id12.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.12", req.scheduled_task_id12); } if(!req.scheduled_task_id13.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.13", req.scheduled_task_id13); } if(!req.scheduled_task_id14.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.14", req.scheduled_task_id14); } if(!req.scheduled_task_id15.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.15", req.scheduled_task_id15); } if(!req.scheduled_task_id16.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.16", req.scheduled_task_id16); } if(!req.scheduled_task_id17.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.17", req.scheduled_task_id17); } if(!req.scheduled_task_id18.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.18", req.scheduled_task_id18); } if(!req.scheduled_task_id19.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.19", req.scheduled_task_id19); } if(!req.scheduled_task_id20.empty()) { req_rpc->AddRequestQuery("ScheduledTaskId.20", req.scheduled_task_id20); } if(!req.scheduled_task_name1.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.1", req.scheduled_task_name1); } if(!req.scheduled_task_name2.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.2", req.scheduled_task_name2); } if(!req.scheduled_task_name3.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.3", req.scheduled_task_name3); } if(!req.scheduled_task_name4.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.4", req.scheduled_task_name4); } if(!req.scheduled_task_name5.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.5", req.scheduled_task_name5); } if(!req.scheduled_task_name6.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.6", req.scheduled_task_name6); } if(!req.scheduled_task_name7.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.7", req.scheduled_task_name7); } if(!req.scheduled_task_name8.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.8", req.scheduled_task_name8); } if(!req.scheduled_task_name9.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.9", req.scheduled_task_name9); } if(!req.scheduled_task_name10.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.10", req.scheduled_task_name10); } if(!req.scheduled_task_name11.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.11", req.scheduled_task_name11); } if(!req.scheduled_task_name12.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.12", req.scheduled_task_name12); } if(!req.scheduled_task_name13.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.13", req.scheduled_task_name13); } if(!req.scheduled_task_name14.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.14", req.scheduled_task_name14); } if(!req.scheduled_task_name15.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.15", req.scheduled_task_name15); } if(!req.scheduled_task_name16.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.16", req.scheduled_task_name16); } if(!req.scheduled_task_name17.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.17", req.scheduled_task_name17); } if(!req.scheduled_task_name18.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.18", req.scheduled_task_name18); } if(!req.scheduled_task_name19.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.19", req.scheduled_task_name19); } if(!req.scheduled_task_name20.empty()) { req_rpc->AddRequestQuery("ScheduledTaskName.20", req.scheduled_task_name20); } if(!req.owner_account.empty()) { req_rpc->AddRequestQuery("OwnerAccount", req.owner_account); } if(this->region_id_ && this->region_id_[0]) { req_rpc->AddRequestQuery("RegionId", this->region_id_); } if(req_rpc->CommitRequest() != 0) { if(error_info) { error_info->code = "connect to host failed"; } ret = -1; goto out; } status_code = req_rpc->WaitResponseHeaderComplete(); req_rpc->ReadResponseBody(str_response); if(status_code > 0 && !str_response.empty()){ parse_success = reader.parse(str_response, val); } if(!parse_success) { if(error_info) { error_info->code = "parse response failed"; } ret = -1; goto out; } if(status_code!= 200 && error_info && parse_success) { error_info->request_id = val.isMember("RequestId") ? val["RequestId"].asString(): ""; error_info->code = val.isMember("Code") ? val["Code"].asString(): ""; error_info->host_id = val.isMember("HostId") ? val["HostId"].asString(): ""; error_info->message = val.isMember("Message") ? val["Message"].asString(): ""; } if(status_code== 200 && response) { Json2Type(val, response); } ret = status_code; out: delete req_rpc; return ret; }
[ "zcy421593@126.com" ]
zcy421593@126.com
afdec558f8c70197c44073506ad1d0a92af1d1bb
f8f50d7e520b374dfa75c7ef0cfd62735e06bb27
/C++/EngineDevBox/EngineDevBox/main.cpp
138b3c8ce23075bb09f42ca9d78ca36d964e7983
[]
no_license
samratnagarjuna/CodeSamples
cba310b94bbd3dbeac3fe1d4a280a7d8b702acd0
8955cd85ce95416799b6d87727a548abaf452854
refs/heads/master
2021-05-01T22:43:28.574082
2017-01-21T19:07:04
2017-01-21T19:07:04
77,611,958
0
0
null
null
null
null
UTF-8
C++
false
false
2,279
cpp
#include <Windows.h> #define _USE_MATH_DEFINES #include <cmath> #include <iostream> #include "NEngine.h" #include "Message\NMessageManager.h" #include "Math\NMatrix4.h" #include "Math\NVector4.h" #include "Utility\NHashedString.h" #include "Utility\NConsolePrint.h" #include "Game\Game.h" #if defined _DEBUG #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif // _DEBUG using namespace Illehc; class TestMessageHandler : public MessageSystem::IMessageHandler { void OnReceive(const HashedString & i_Message, void * i_Data); }; void TestMessageHandler :: OnReceive(const HashedString & i_Message, void * i_Data) { DEBUG_PRINT("Test Message Handler Triggered\n"); } void MessageHandlerUnitTest() { MessageSystem::Init(); MessageSystem::IMessageHandler * handler = new TestMessageHandler(); MessageSystem::RegisterMessageHandler("Test", handler); MessageSystem::NotifyMessage("Test", NULL); MessageSystem::DeRegisterMessageHandler("Test", handler); MessageSystem::ShutDown(); delete handler; } void MatrixUnitTest() { Vector4 invector = Vector4 (1.0f, 0.0f, 0.0f, 1.0f); Matrix4 transmatrix = Matrix4::CreateTranslationCV(10.0f, 0.0f, 0.0f); Vector4 outvector = transmatrix.MultiplyRight(invector); DEBUG_PRINT("Expected Output = 11.0 , Produced Output = %f\n",outvector.getX()); Matrix4 rotmatrix = Matrix4::CreateZRotationCV((float)M_PI_2); outvector = rotmatrix.MultiplyRight(invector); DEBUG_PRINT("Expected Output = 1.0 , Produced Output = %f\n", outvector.getY()); Matrix4 transrotmatrix = transmatrix * rotmatrix; outvector = transrotmatrix.MultiplyRight(invector); DEBUG_PRINT("Expected Output = (10.0, 1.0) , Produced Output = (%f, %f)\n", outvector.getX(), outvector.getY()); } int WINAPI wWinMain(HINSTANCE i_hInstance, HINSTANCE i_hPrevInstance, LPWSTR i_lpCmdLine, int i_nCmdShow) { /* NOTE:: When loading Serialize Scene Press B (BackUp) to Serialize Data and L(Load) to Deserialize */ if (GameEngine::Init("Engine Illehc Dev Box", i_hInstance, i_nCmdShow)) { if (Game::Init()) { GameEngine::Run(); Game::ShutDown(); } GameEngine::ShutDown(); } #if defined _DEBUG _CrtDumpMemoryLeaks(); #endif // _DEBUG return 0; }
[ "samratnagarjuna@gmail.com" ]
samratnagarjuna@gmail.com
69eca6d929e429912ea850e544f7074da81b1acb
730a591e0bbef0d9abb7adbf45e0968b5f6bd7f0
/cpputils/Utils/Common/CommonUtils.cpp
78dda52f89a7f821904715ab540df1a4330c522c
[]
no_license
KAndQ/cocos2dx-utils
5c574287a9c46037838d348b0ce8b8b565c1bed8
497de1e41a660a6b4308061b14740b31534611d4
refs/heads/master
2021-01-01T18:54:49.746170
2015-06-04T11:56:22
2015-06-04T11:56:22
35,252,503
2
0
null
null
null
null
UTF-8
C++
false
false
10,654
cpp
// // CommonUtils.cpp // AndroidaBooM // // Created by Zhenyu Yao on 13-4-12. // // #include <stdio.h> #include <sstream> #include <math.h> #include <ctype.h> #include "CommonUtils.h" using namespace std; float PTM_RATIO = 32; //////////////////////////////////////////////////////////////////////////////////////////////////// // 一些常用功能 //////////////////////////////////////////////////////////////////////////////////////////////////// float32 floatValueFromDictionary(CCDictionary * dict, const string & key) { CCString * result = dynamic_cast<CCString *>(dict->objectForKey(key)); if (result != NULL) { return result->floatValue(); } else { return 0.0f; } } int32 intValueFromDictionary(CCDictionary * dict, const string & key) { CCString * result = dynamic_cast<CCString *>(dict->objectForKey(key)); if (result != NULL) { return result->intValue(); } else { return 0; } } uint32 uintValueFromDictionary(CCDictionary * dict, const string & key) { CCString * result = dynamic_cast<CCString *>(dict->objectForKey(key)); if (result != NULL) { return result->uintValue(); } else { return 0; } } bool boolValueFromDictionary(CCDictionary * dict, const string & key) { CCString * result = dynamic_cast<CCString *>(dict->objectForKey(key)); if (result != NULL) { return result->boolValue(); } else { return false; } } string stringValueFromDictionary(CCDictionary * dict, const string & key) { CCString * result = dynamic_cast<CCString *>(dict->objectForKey(key)); if (result != NULL) { return string(result->getCString()); } else { return string(); } } void tintAllSprite(CCNode * root, const ccColor4B & color) { Vector<CCNode *>::const_iterator beg = root->getChildren().begin(); Vector<CCNode *>::const_iterator end = root->getChildren().end(); for (; beg != end; ++beg) { CCNode * child = (CCNode *)*beg; tintAllSprite(child, color); } if (dynamic_cast<CCRGBAProtocol *>(root) != NULL) { CCRGBAProtocol * p = dynamic_cast<CCRGBAProtocol *>(root); p->setColor(ccc3(color.r, color.g, color.b)); p->setOpacity(color.a); } } void pauseAll(cocos2d::CCNode* node) { Vector<CCNode *>::const_iterator beg = node->getChildren().begin(); Vector<CCNode *>::const_iterator end = node->getChildren().end(); for (; beg != end; ++beg) { CCNode * child = (CCNode *)*beg; pauseAll(child); } node->pause(); } void resumeAll(cocos2d::CCNode* node) { Vector<CCNode *>::const_iterator beg = node->getChildren().begin(); Vector<CCNode *>::const_iterator end = node->getChildren().end(); for (; beg != end; ++beg) { CCNode * child = (CCNode *)*beg; resumeAll(child); } node->resume(); } //////////////////////////////////////////////////////////////////////////////////////////////////// // 几何/数学 //////////////////////////////////////////////////////////////////////////////////////////////////// float convertRadianToDegree(float radian) { return radian / M_PI * 180.0f; } float convertDegreeToRadian(float degree) { return degree / 180.0f * M_PI; } #if (ENABLED_BOX2D) CCPoint pointFromVec(const b2Vec2 & vec) { return ccp(vec.x, vec.y); } b2Vec2 vecFromPoint(const CCPoint & point) { return b2Vec2(point.x, point.y); } CCPoint pointFromVec_meter(const b2Vec2 & vec) { return ccp(vec.x * PTM_RATIO, vec.y * PTM_RATIO); } b2Vec2 vecFromPoint_meter(const CCPoint & point) { return b2Vec2(point.x / PTM_RATIO, point.y / PTM_RATIO); } #endif // ENABLED_BOX2D float pointFromMeter(float meterUnit) { return meterUnit * PTM_RATIO; } float meterFromPoint(float pointUnit) { return pointUnit / PTM_RATIO; } bool CCRectContainsRect(cocos2d::CCRect& rect1, cocos2d::CCRect& rect2) { if ((rect2.origin.x - rect1.origin.x <= rect1.size.width - rect2.size.width) &&rect2.origin.x >= rect1.origin.x &&rect2.origin.y >= rect1.origin.y && (rect2.origin.y - rect1.origin.y < rect1.size.height - rect2.size.height)) { return true; } return false; } //////////////////////////////////////////////////////////////////////////////////////////////////// // 分辨率处理 //////////////////////////////////////////////////////////////////////////////////////////////////// void adapterLandscapeResolution(float contentScale) { CCDirector * pDirector = CCDirector::sharedDirector(); // 屏幕适配 CCSize designSize = pDirector->getWinSize(); if ((designSize.width == 960 && designSize.height == 640) // iPhone4, 4S, iPod4 || (designSize.width == 1136 && designSize.height == 640) // iPhone5, iPod5 || (designSize.width == 1024 && designSize.height == 768)) // iPad1,2, iPad mini { // designSize.width /= contentScale; // designSize.height /= contentScale; designSize.width = 960 / contentScale; designSize.height = 640 / contentScale; } else if (designSize.width == 2048 && designSize.height == 1536) // iPad3 { // designSize.width /= contentScale * 2.0f; // designSize.height /= contentScale * 2.0f; designSize.width = 960 / contentScale; designSize.height = 640 / contentScale; } else // 其他分辨率 & iPhone3GS { designSize.width = 960 / contentScale; designSize.height = 640 / contentScale; } pDirector->setContentScaleFactor(contentScale); // pDirector->getOpenGLView()->setDesignResolutionSize(designSize.width, designSize.height, kResolutionFixedHeight); pDirector->getOpenGLView()->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::SHOW_ALL); } void adapterPortraitResolution(float contentScale) { CCDirector * pDirector = CCDirector::sharedDirector(); CCSize designSize = pDirector->getWinSize(); if ((designSize.width == 640 && designSize.height == 960) || (designSize.width == 640 && designSize.height == 1136) || (designSize.width == 768 && designSize.height == 1024)) { designSize.width /= contentScale; designSize.height /= contentScale; } else if (designSize.width == 1536 && designSize.height == 2048) { designSize.width /= contentScale * 2.0f; designSize.height /= contentScale * 2.0f; } else { designSize.width = 640 / contentScale; designSize.height = 960 / contentScale; } pDirector->setContentScaleFactor(contentScale); pDirector->getOpenGLView()->setDesignResolutionSize(designSize.width, designSize.height, kResolutionFixedHeight); } //////////////////////////////////////////////////////////////////////////////////////////////////// // 字符串处理 //////////////////////////////////////////////////////////////////////////////////////////////////// string int32ToString(int32 value) { char str[32] = {0}; sprintf(str, "%d", value); return string(str); } string uint32ToString(uint32 value) { char str[32] = {0}; sprintf(str, "%u", value); return string(str); } string uint64ToString(uint64 value) { char str[32] = {0}; sprintf(str, "%llu", value); return string(str); } string float32ToString(float32 value) { char str[32] = {0}; sprintf(str, "%f", value); return string(str); } string boolToString(bool value) { if (value) return string("true"); else return string("false"); } int32 int32FromString(const std::string & value) { if (value.empty()) return 0; istringstream iss(value); int32 number; iss >> number; return number; } uint32 uint32FromString(const std::string & value) { if (value.empty()) return 0; istringstream iss(value); uint32 number; iss >> number; return number; } uint64 uint64FromString(const std::string & value) { if (value.empty()) return 0; istringstream iss(value); uint64 number; iss >> number; return number; } float32 float32FromString(const std::string & value) { if (value.empty()) return 0.0f; istringstream iss(value); float32 number; iss >> number; return number; } bool boolFromString(const std::string & value) { std::string tmp = value; asciiToLower(tmp); if (tmp == "false" || tmp == "no" || tmp == "0") return false; return true; } void asciiToLower(std::string & origin) { for (size_t i = 0; i < origin.length(); ++i) origin[i] = tolower(origin[i]); } void asciiToUpper(std::string & origin) { for (size_t i = 0; i < origin.length(); ++i) origin[i] = toupper(origin[i]); } void slitStringBySeperator(const string & origin, vector<string> & others, const string & seperator) { size_t beg = 0; size_t end = 0; size_t originLen = origin.length(); size_t seperatorLen = seperator.length(); while (beg < originLen) { end = origin.find(seperator, beg); // 如果起始位置与终止位置在同一个地方, 那么将不记录字符串, 因为不存在截断的字符串. if (beg != end) { if (end == string::npos) { // 如果 (beg == 0 && end == string::npos), 那么表示的是没有搜索到分割符, 那么将不分离各个字符串. // 而下面的代码表示的是, 从当前位置切割字符串, 直到字符串末尾. if (beg != 0) { others.push_back(origin.substr(beg, end)); } break; } else { others.push_back(origin.substr(beg, end - beg)); } } beg = end + seperatorLen; } } string trimCharacterFromLast(const std::string & origin, char chTrim) { for (size_t i = origin.length() - 1; i < 0xffffffff; --i) { if (origin[i] != chTrim) { return origin.substr(0, i + 1); } } static string s_reuslt(""); return s_reuslt; } string subStringWithCharacterFromHead(const std::string& origin, char chSign) { size_t pos = origin.rfind(chSign); if (pos == string::npos) return origin; return origin.substr(0,pos); } string subStringWithCharacterFromLast(const std::string& origin, char chSign) { size_t pos = origin.rfind(chSign); if (pos == string::npos) return origin; return origin.substr(pos + 1); } string stringByDeletingPathExtension(const std::string & origin) { size_t pos = origin.rfind("."); return origin.substr(0, pos); } string stringByAppendingPathExtension(const std::string & origin, const std::string & extension) { return origin + "." + extension; } string pathExtensionWithString(const std::string & file) { size_t pos = file.rfind("."); if (pos == string::npos) return ""; if (pos == file.length() - 1) return ""; return file.substr(pos + 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // end file
[ "qingkaka@gmail.com" ]
qingkaka@gmail.com
b8a8063ae3f990f3313c8f2dad7036dfaf8af386
7ea05d5bb9dfd4ca467d32c2af8062452c3feaa4
/Project4/Sensor.cpp
757cfcdfde561804857fa838cc9c2ff41aac6350
[]
no_license
Renat97/CS202
b5e46effa571fc2ae9fe72bdf29f5b2760134bbb
12c9bfe3aaeaa7ab64d00dceabb7a20860dca366
refs/heads/master
2022-12-20T10:14:08.235202
2020-10-03T05:05:16
2020-10-03T05:05:16
296,836,372
0
0
null
null
null
null
UTF-8
C++
false
false
1,805
cpp
// // Sensor.cpp // Project4 // // Created by Renat Norderhaug on 9/23/17. // Copyright © 2017 Renat Norderhaug. All rights reserved. // #include "Sensor.h" #include <iostream> #include <cstring> #include <cstdio> using namespace std; int Sensor::gps_cnt = 0; int Sensor::camera_cnt = 0; int Sensor::lidar_cnt = 0; int Sensor::radar_cnt = 0; Sensor::Sensor() { setType("none"); } Sensor::Sensor(const char* type) { setType(type); } const char* Sensor::getType() const { return m_type; } void Sensor::setType(const char* type){ if(strcmp("gps", type)) { strcpy(m_type, type); m_extracost = 5.0; gps_cnt++; } else if(strcmp("camera", type)) { strcpy(m_type, type); m_extracost = 10.0; camera_cnt++; } else if(strcmp("lidar", type)) { strcpy(m_type, type); m_extracost = 15.0; lidar_cnt++; } else if(strcmp("radar", type)) { strcpy(m_type, type); m_extracost = 20.0; radar_cnt++; } else if(strcmp("none", type)) { strcpy(m_type, type); m_extracost = 0.0; } } float Sensor::getExtraCost() const { return m_extracost; } int Sensor::getGpsCount(){ return gps_cnt; } int Sensor::getCameraCount(){ return camera_cnt; } int Sensor::getLidarCount(){ return lidar_cnt; } int Sensor::getRadarCount(){ return radar_cnt; } void Sensor::resetGpsCount(){ gps_cnt = 0; } void Sensor::resetCameraCount(){ camera_cnt = 0; } void Sensor::resetLidarCount(){ lidar_cnt = 0; } void Sensor::resetRadarCount(){ radar_cnt=0; } void Sensor::printAllSensors() { cout << "gps: " << gps_cnt << " "; cout << "camera: "<< camera_cnt << " "; cout << "lidar: "<< lidar_cnt << " "; cout << "radar: " << radar_cnt << " "; cout << endl; } bool operator == (const Sensor& sensor1, const Sensor& sensor2) { return strcmp(sensor1.m_type, sensor2.m_type) == 0; }
[ "renat97@gmail.com" ]
renat97@gmail.com
78f35111dd3b413e2bbeb307f0bae21ebd7ede26
9a9e7d9eafad23d3690f7f8104daf35f08c03aab
/HelloGit/HelloGit.cpp
924bf65874c8d084f822e3d00aa038ffd3b8f113
[]
no_license
0I00II000I00I0I0/TestGit
80718460048baa565259d34f9193b5625c9d746f
df235eff4f0e2a2731f209c6a7a8f2ab07f012ee
refs/heads/master
2023-05-31T10:46:04.867955
2021-06-30T15:40:06
2021-06-30T15:40:06
381,754,818
0
0
null
null
null
null
UTF-8
C++
false
false
101
cpp
#include <iostream> int main() { std::cout << "Hello Git!\n"; system("pause"); return 0; }
[ "1357669331@qq.com" ]
1357669331@qq.com
6152d2b042b2ab3c1da404b804986fc20fd96d37
38630abe38b4b4d1c629df4f4de7e6b5f097d3c5
/Classes/AppDelegate.cpp
abb6194906e0bdf2cb961b30632f8ca3255b2baa
[]
no_license
xiaolizi521/pogoda
2e8c4d3e5904aa6f4ff3e972fe4ce1fce3a82bb5
2c7d2d08da50464915915a39236917db02c50748
refs/heads/master
2021-01-17T21:39:23.520819
2013-04-26T12:20:29
2013-04-26T12:20:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,979
cpp
#include "cocos2d.h" #include "CCEGLView.h" #include "AppDelegate.h" #include "HelloWorldScene.h" #include "SimpleAudioEngine.h" #include "SceneManager.h" #include "UserData.h" using namespace CocosDenshion; USING_NS_CC; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { SimpleAudioEngine::end(); } bool AppDelegate::applicationDidFinishLaunching() { // initialize director CCDirector *pDirector = CCDirector::sharedDirector(); pDirector->setOpenGLView(CCEGLView::sharedOpenGLView()); CCSize screenSize = CCEGLView::sharedOpenGLView()->getFrameSize(); CCSize designSize = CCSizeMake(640, 960); pDirector->setContentScaleFactor(1); CCEGLView::sharedOpenGLView()->setDesignResolutionSize(designSize.width,designSize.height, kResolutionNoBorder); // turn on display FPS //pDirector->setDisplayStats(true); pDirector->setDisplayStats(false); // set FPS. the default value is 1.0/60 if you don't call this pDirector->setAnimationInterval(1.0 / 60); // create a scene. it's an autorelease object //CCScene *pScene = HelloWorld::scene(); // run //pDirector->runWithScene(pScene); srand((unsigned)time(0)); SceneManager::initLoading(); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { CCDirector::sharedDirector()->stopAnimation(); if(SceneManager::music) SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { CCDirector::sharedDirector()->startAnimation(); if(SceneManager::music) SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); //CCSize winSize = CCDirector::sharedDirector()->getWinSize(); //Loading *loading = new Loading(); //CCDirector::sharedDirector()->getRunningScene()->addChild((CCNode *)loading); }
[ "wyklion@qq.com" ]
wyklion@qq.com
3f60cd7782b1a1dc3c0adc87672c3823c1163564
ef1173942b5783df6bda77dbfaa04966960782d0
/src/dialogs/RemoteDialog.h
c82961f7cb8a8c724c32f9144d44a891ce172536
[ "MIT" ]
permissive
dgalli1/gitahead
4e1d97226df9852a69af5117b25387c66c8c62cf
7304964210a5c216e17f2f86db2250a8dabc4333
refs/heads/master
2020-06-23T16:45:43.372139
2019-11-07T11:35:26
2019-11-07T11:35:26
198,684,774
0
0
MIT
2019-07-24T17:54:42
2019-07-24T17:54:41
null
UTF-8
C++
false
false
862
h
// // Copyright (c) 2016, Scientific Toolworks, Inc. // // This software is licensed under the MIT License. The LICENSE.md file // describes the conditions under which this software may be distributed. // // Author: Jason Haslam // #ifndef REMOTEDIALOG_H #define REMOTEDIALOG_H #include <QDialog> #include "git/Repository.h" class ReferenceList; class RepoView; class QCheckBox; class QComboBox; class QLineEdit; namespace git { class Reference; class Remote; } class RemoteDialog : public QDialog { public: enum Kind { Fetch, Pull, Push }; RemoteDialog(Kind kind, RepoView *parent); private: QComboBox *mRemotes; ReferenceList *mRefs = nullptr; QComboBox *mAction = nullptr; QCheckBox *mTags = nullptr; QCheckBox *mSetUpstream = nullptr; QCheckBox *mForce = nullptr; QLineEdit *mRemoteRef = nullptr; }; #endif
[ "jason@scitools.com" ]
jason@scitools.com
7a6b3625fb83fbcdd67f28db1178ba27a59021cd
8727d1a506114c2bbab2f74db9bdaf68b5a6c83e
/test6.cpp
2f3b7e0c87c48ffa427a00770544399ab4580a89
[]
no_license
BaiXious/Accelerated-cpp
5c5525eb9678ad98475208f82ea63b1606e31a86
26ad13fe83aa36c8d3ca1caf89b04e90f441d7d7
refs/heads/master
2022-01-13T08:11:14.337940
2018-08-28T04:06:10
2018-08-28T04:06:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
#include <iostream> #include <string> #include <vector> class A; void doanother(A* a) ; class dosth { public : void haha() { doanother(p); } private : A* p; }; class A { friend class dosth; private : std::vector<std::string> data; }; void doanother(A* a) { std::cout << a->data.size() << std::endl; } int main() { A a; return 0; }
[ "1051378379@qq.com" ]
1051378379@qq.com
ca497fb44fe3735a7e4e2f6c4b16231c06f3e536
8d227ac6d2a8b70e545845824caa561a34c35483
/P08/full_credit/tool.h
2841a07a3849db532a9f9d4c3fb297ccbd32c8cb
[]
no_license
zakyqalawi/cse1325
91585e7202773a33fa1d015b2b8f43e5484d2a1c
eedfa02fe0e9cce384b73ba6a92e027a7acf0e98
refs/heads/master
2023-01-24T17:56:21.288902
2020-12-08T06:32:53
2020-12-08T06:32:53
292,068,396
0
0
null
null
null
null
UTF-8
C++
false
false
176
h
#ifndef __TOOL_H #define __TOOL_H #include "product.h" class Tool : public Product { public: Tool(std::string name, double price, std::string description); }; #endif
[ "zaky.qalawi@mavs.uta.edu" ]
zaky.qalawi@mavs.uta.edu
c54ebe53971e408f526576a1bfe102d150a21a05
948f2d98cde85de3f5463fbd8fbdfd58d44b3a0e
/Stack/Valid Parentheses.cpp
58faac3dd6b6128d63d039b640a5add6baa692f0
[]
no_license
AlmoonYsl/Algorithm
1391a72bc59b09a874a4acb485e0de81d7223f8d
f9e1305e738751afc93d0212071484ac474d9d89
refs/heads/master
2022-12-25T10:19:16.670388
2020-09-30T00:12:42
2020-09-30T00:12:42
247,688,359
1
0
null
null
null
null
UTF-8
C++
false
false
637
cpp
/** * leetcode no.20 * */ bool isValid(string s) { int len = s.length(); if (len % 2 != 0) return false; stack<char> stack; for (int i = 0; i < len; ++i) { switch (s[i]){ case '(': stack.push(')'); break; case '{': stack.push('}'); break; case '[': stack.push(']'); break; default: if (stack.empty() || stack.size() > len / 2 || stack.top() != s[i]) return false; else stack.pop(); } } return stack.empty(); }
[ "784748497@qq.com" ]
784748497@qq.com
4a5a5e80dd1736321548c9d91bd47a9543a5aebd
d9066a9b731c1b46f2d21bd91ad2238e83d9c786
/ServiceDayDlg.cpp
e4313e67796b60fac3df54eab28fe6a6f950879f
[]
no_license
agonnet/PlanMaker
5b9617d4a46d772b1a5396eb08c3d0e70a4f3abe
bdaea05a9d088e46de096015fa4a5f9b0625094c
refs/heads/master
2021-04-15T18:08:23.758100
2018-03-25T15:27:19
2018-03-25T15:27:19
126,708,644
0
0
null
null
null
null
UTF-8
C++
false
false
9,808
cpp
// ServiceDayDlg.cpp : implementation file // #include "stdafx.h" #include "PlanMaker.h" #include "ServiceDayDlg.h" #include "PlanMakerDoc.h" #include "PlanMakerView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CServiceDayDlg dialog CServiceDayDlg::CServiceDayDlg(CWnd* pParent /*=NULL*/) : CDialog(CServiceDayDlg::IDD, pParent) { //{{AFX_DATA_INIT(CServiceDayDlg) m_date = 0; m_note = _T(""); //}}AFX_DATA_INIT } void CServiceDayDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CServiceDayDlg) DDX_Control(pDX, IDC_EDIT1, m_edit1); DDX_Control(pDX, IDC_DELETE, m_delete); DDX_Control(pDX, IDC_LIST1, m_listctrl); DDX_Control(pDX, IDC_MONTHCALENDAR, m_datectrl); DDX_MonthCalCtrl(pDX, IDC_MONTHCALENDAR, m_date); DDX_Text(pDX, IDC_EDIT1, m_note); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CServiceDayDlg, CDialog) //{{AFX_MSG_MAP(CServiceDayDlg) ON_NOTIFY(MCN_SELECT, IDC_MONTHCALENDAR, OnSelectMonthcalendar) ON_LBN_SELCHANGE(IDC_LIST1, OnSelchangeList1) ON_BN_CLICKED(IDC_ADDNOTE, OnAddNote) ON_BN_CLICKED(IDC_DELETE, OnDelete) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CServiceDayDlg message handlers extern int nDay[32]; extern int nMonth[32]; extern int nYear[32]; extern int rows; extern int cols; extern int nPreachers; extern BOOL bAllocationDone; extern PINFO* pPInfoBase; extern SINFO* pSInfoBase; extern PINFO* pPInfo1Base; extern SINFO* pSInfo1Base; extern BOOL bEnableUndo; extern BOOL bEnableRedo; extern BOOL bPlanResized; extern BOOL bAllocPending; BOOL CServiceDayDlg::OnInitDialog() { CDialog::OnInitDialog(); pDoc = CPlanMakerDoc::GetDoc(); //store nDay, nMonth & nYear in row 0 of each col SINFO* pCol = pSInfo1Base + 1; for (int col = 1; col < cols; col++) { pCol->nDay = nDay[col]; pCol->nMonth = nMonth[col]; pCol->nYear = nYear[col]; pCol++; } m_datectrl.GetToday(&date); m_datectrl.SetCurSel(&date); //get date info from cols in row 0 (remove crlf) SINFO* pSInfo = pSInfo1Base + 1; for (col = 1; col < cols; col++) { CString str = pSInfo->date; str.Replace(0x0d, ' '); str.Replace(0x0a, ' '); m_listctrl.AddString(str); pSInfo++; } nOldCols = cols; pDoc = CPlanMakerDoc::GetDoc(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CServiceDayDlg::OnSelectMonthcalendar(NMHDR* pNMHDR, LRESULT* pResult) { nItems = m_listctrl.GetCount(); if (nItems == 32) { MessageBox("You have reached the maximum number of dates allowable and no more can be added. If you really need more dates, contact the program author to see if PlanMaker can be customised for you.", "PlanMaker", MB_OK | MB_ICONINFORMATION); return; } //add new item at end of list nItems++; m_datectrl.GetCurSel(&date); SINFO* pSInfo = pSInfo1Base + nItems; pSInfo->nDay = date.wDay; pSInfo->nMonth = date.wMonth; pSInfo->nYear = date.wYear; char ch[8]; _itoa(date.wDay, ch, 10); pSInfo->date = ch; pSInfo->date += " "; switch (date.wMonth) { case 1: pSInfo->date += "January"; break; case 2: pSInfo->date += "February"; break; case 3: pSInfo->date += "March"; break; case 4: pSInfo->date += "April"; break; case 5: pSInfo->date += "May"; break; case 6: pSInfo->date += "June"; break; case 7: pSInfo->date += "July"; break; case 8: pSInfo->date += "August"; break; case 9: pSInfo->date += "September"; break; case 10: pSInfo->date += "October"; break; case 11: pSInfo->date += "November"; break; case 12: pSInfo->date += "December"; break; } pSInfo->date += " "; _itoa(date.wYear, ch, 10); pSInfo->date += ch; //copy info into CALENDAR CALENDAR* pCalBase = new CALENDAR[nItems]; CALENDAR* pCal = pCalBase; pSInfo = pSInfo1Base + 1; //row0, col1 for (int col = 1; col <= nItems; col++) { pCal->row0Info = *pSInfo; pCal->nCol = col; pCal++; pSInfo++; } qsort(pCalBase, nItems, sizeof(CALENDAR), Compare); //find the new col int nCol = 0; SINFO newColInfo; pCal = pCalBase; for (col = 1; col <= nItems; col++) { if (pCal->nCol == nItems) { newColInfo = pCal->row0Info; nCol = col; } pCal++; } delete [] pCalBase; //move service info & preacher availability right if new col not at end if (nCol != nItems) { SINFO* pRow = pSInfo1Base + nItems; //row0, last col for (int row = 0; row < rows - 1; row++) { SINFO* pSInfo = pRow; for (int col = nItems; col > nCol; col--) { *pSInfo = *(pSInfo - 1); pSInfo--; } pRow += 32; } *(pSInfo1Base + nCol) = newColInfo; for (int col = nItems; col > nCol; col--) { PINFO* pPInfo = pPInfo1Base; for (int prch = 0; prch < nPreachers; prch++) { pPInfo->availability[col] = pPInfo->availability[col - 1]; pPInfo++; } } } //initialise SINFO for new col pSInfo = pSInfo1Base + 32 + nCol; for (int row = 1; row < rows - 1; row++) { pSInfo->communion = false; pSInfo->family = false; pSInfo->parade = false; pSInfo->baptism = false; pSInfo->united = false; pSInfo->no_service = false; pSInfo->reserved = false; pSInfo->group = 0; pSInfo->detail = ""; pSInfo->code = ""; pSInfo->date = ""; pSInfo->place_time = ""; pSInfo->preacher = ""; pSInfo += 32; } //initialise preacher availability for new col PINFO* pPInfo = pPInfo1Base; for (int prch = 0; prch < nPreachers; prch++) { pPInfo->availability[nCol] = 0; pPInfo++; } //display in listbox m_listctrl.ResetContent(); pSInfo = pSInfo1Base + 1; for (col = 1; col <= nItems; col++) { CString str; int find = pSInfo->date.Find(0x0d, 0); if (find != -1) { str = pSInfo->date.Left(find); str += " "; str += pSInfo->date.Mid(find + 2); } else str = pSInfo->date; m_listctrl.AddString(str); pSInfo++; } *pResult = 0; } void CServiceDayDlg::OnSelchangeList1() { m_edit1.EnableWindow(true); m_edit1.SetFocus(); m_delete.EnableWindow(true); //extract any note and copy to edit box SINFO* pSInfo = pSInfo1Base + m_listctrl.GetCurSel() + 1; CString str = pSInfo->date; //find the return 0x0d before note (there isn't one if no note present) int nNote = str.Find(0x0d); if (nNote != -1) SetDlgItemText(IDC_EDIT1, str.Mid(nNote + 2)); else SetDlgItemText(IDC_EDIT1, ""); } void CServiceDayDlg::OnAddNote() { int nItems = m_listctrl.GetCount(); //add note CString newnote; UpdateData(true); if (m_note != "") { newnote = (char)13; newnote += (char)10; newnote += m_note; } else newnote = ""; //remove any existing note SINFO* pSInfo = pSInfo1Base + m_listctrl.GetCurSel() + 1; int nNote = pSInfo->date.Find(0x0d); //if exists, already a note if (nNote != -1) pSInfo->date = pSInfo->date.Left(nNote); //add the new note pSInfo->date += newnote; //display in list box //clear the box first m_listctrl.ResetContent(); //then add the strings pSInfo = pSInfo1Base + 1; for (int col = 1; col <= nItems; col++) { CString str = pSInfo->date; str.Replace(0x0d, ' '); str.Replace(0x0a, ' '); m_listctrl.AddString(str); pSInfo++; } //clear the edit box and disable SetDlgItemText(IDC_EDIT1, ""); m_edit1.EnableWindow(false); } void CServiceDayDlg::OnDelete() { //delete a date nItems = m_listctrl.GetCount(); int nSelCol = m_listctrl.GetCurSel() + 1; m_listctrl.DeleteString(m_listctrl.GetCurSel()); //reduce prefs in rows where local ords appear in this col SINFO* pSInfo = pSInfo1Base + 32 + nSelCol; for (int row = 1; row < rows - 1; row++) { PINFO* pPInfo = pPInfo1Base; for (int prch = 0; prch < nPreachers; prch++) { if (pDoc->PreacherAppears(pPInfo, pSInfo) && pPInfo->ordained && !pPInfo->visitor) pPInfo->preferences[row]--; pPInfo++; } pSInfo += 32; } //move later plan entries left SINFO* pRow = pSInfo1Base;; //row0, col0 for (row = 0; row < rows - 1; row++) { SINFO* pSInfo = pRow + nSelCol; for (int col = nSelCol; col < nItems; col++) { *pSInfo = *(pSInfo + 1); pSInfo++; } pRow += 32; } //move availability left for (int col = nSelCol; col < nItems; col++) { PINFO* pPInfo = pPInfo1Base; for (int prch = 0; prch < nPreachers; prch++) { pPInfo->availability[col] = pPInfo->availability[col + 1]; pPInfo++; } } m_delete.EnableWindow(false); } void CServiceDayDlg::OnOK() { cols = m_listctrl.GetCount() + 1; SINFO* pSInfo = pSInfo1Base + 1; //row0 col1 for (int col = 1; col < cols; col++) { nDay[col] = pSInfo->nDay; nMonth[col] = pSInfo->nMonth; nYear[col] = pSInfo->nYear; pSInfo++; } if (cols != nOldCols) { bAllocPending = true; bPlanResized = true; } pDoc->SetModifiedFlag(); bEnableUndo = true; bEnableRedo = false; CDialog::OnOK(); } int CServiceDayDlg::Compare(const void *p1, const void *p2) { CALENDAR* pCal1 = (CALENDAR*)p1; CALENDAR* pCal2 = (CALENDAR*)p2; if (pCal1->row0Info.nYear < pCal2->row0Info.nYear) return -1; if (pCal1->row0Info.nYear > pCal2->row0Info.nYear) return 1; if (pCal1->row0Info.nMonth < pCal2->row0Info.nMonth) return -1; if (pCal1->row0Info.nMonth > pCal2->row0Info.nMonth) return 1; if (pCal1->row0Info.nDay < pCal2->row0Info.nDay) return -1; if (pCal1->row0Info.nDay > pCal2->row0Info.nDay) return 1; return 0; }
[ "noreply@github.com" ]
agonnet.noreply@github.com
108439f7fa1e281bc390d1af1a1d06c1d3cfaaa8
72d9009d19e92b721d5cc0e8f8045e1145921130
/iBATCGH/src/prXImixture.cpp
7d04ed9d86ad3d4cd8ee5d317fd47db0a270cf0d
[]
no_license
akhikolla/TestedPackages-NoIssues
be46c49c0836b3f0cf60e247087089868adf7a62
eb8d498cc132def615c090941bc172e17fdce267
refs/heads/master
2023-03-01T09:10:17.227119
2021-01-25T19:44:44
2021-01-25T19:44:44
332,027,727
1
0
null
null
null
null
UTF-8
C++
false
false
1,175
cpp
// [[Rcpp::depends(iBATCGH]] #include <prMixture.h> // [[Rcpp::interfaces(cpp)]] double pr2(int choice,int m,int chg,double add,double* mGam,double* mOm1,double* mOm2,double* mGamNew,double* mOm1New,double* mOm2New,int* mR, int mg){ arma::icolvec R(mR,mg,false); arma::colvec gamma(mGam,m,false); arma::colvec omega1(mOm1,m,false); arma::colvec omega2(mOm2,m,false); arma::colvec gammanew(mGamNew,m,false); arma::colvec omega1new(mOm1New,m,false); arma::colvec omega2new(mOm2New,m,false); double out=0; if(choice==0){ out=out+pRedge(gammanew[choice],omega2new[choice],R[chg+choice],R[chg+choice+1],add); out=out-pRedge(gamma[choice],omega2[choice],R[chg+choice],R[chg+choice+1],add); } if(choice==(m-1)){ out=out+pRedge(gammanew[choice],omega1new[choice],R[chg+choice],R[chg+choice-1],add); out=out-pRedge(gamma[choice],omega1[choice],R[chg+choice],R[chg+choice-1],add); } if(choice>0 && choice<(m-1)){ out=out+pRmiddle(gammanew[choice],omega1new[choice],omega2new[choice],R[chg+choice],R[chg+choice-1],R[chg+choice+1],add); out=out-pRmiddle(gamma[choice],omega1[choice],omega2[choice],R[chg+choice],R[chg+choice-1],R[chg+choice+1],add); } return out; }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
7bb0dc5645963cf0bb61414db3593dfda0716dfe
854a3640d1811db7ba5713cc08d0a85940bd9987
/Tutorial/STL/Set1.cpp
a16d4e15883a333a91e3587ff507e58e4f01f7ea
[]
no_license
Anupam-USP/CP
0c2f0f7aba7086f2abc2f260d9c1bb156a83e491
fb501111592f60c59bf47775b160d2fa26327f1b
refs/heads/main
2023-07-14T16:41:11.885280
2021-08-21T03:56:46
2021-08-21T03:56:46
366,267,553
0
0
null
null
null
null
UTF-8
C++
false
false
539
cpp
#include <bits/stdc++.h> using namespace std; ll main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ll arr[] = {10, 20, 30, 30, 40, 50}; ll n = sizeof(arr) / sizeof(ll); set<ll> s; for (ll i = 0; i < n; i++) s.insert(arr[i]); for (auto it = s.begin(); it != s.end(); it++) cout << *it << endl; s.erase(30); for (auto it = s.begin(); it != s.end(); it++) cout << *it << " -> "; return 0; }
[ "ianupam1509@gmail.com" ]
ianupam1509@gmail.com
ee7451640373244525b5ef7eeff2e54c58115d12
0af5f0cf42c45876acc531b1fb51544166ec43ae
/tests/sources/core/test_interpolation_utils.cpp
0daae8974b34cb69357efad0def846e6ce02cc85
[ "MIT" ]
permissive
nfrechette/acl
8cda80428ab81260d59611f2bf6848b2847897b5
427b948f87d43f666ac9983073790621c3848ae3
refs/heads/develop
2023-08-31T09:14:10.347985
2023-08-26T02:18:40
2023-08-26T11:16:11
91,615,309
1,172
89
MIT
2023-09-09T13:39:44
2017-05-17T20:02:25
C++
UTF-8
C++
false
false
21,689
cpp
//////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2018 Nicholas Frechette & Animation Compression Library contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //////////////////////////////////////////////////////////////////////////////// #include <catch2/catch.hpp> #include <acl/core/interpolation_utils.h> #include <rtm/scalarf.h> using namespace acl; using namespace rtm; TEST_CASE("interpolation utils", "[core][utils]") { const float error_threshold = 1.0E-6F; { // Clamped looping policy uint32_t key0; uint32_t key1; float alpha; find_linear_interpolation_samples_with_duration(31, 1.0F, 0.0F, sample_rounding_policy::none, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 1); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(31, 1.0F, 1.0F / 30.0F, sample_rounding_policy::none, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 1); CHECK(key1 == 2); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(31, 1.0F, 2.5F / 30.0F, sample_rounding_policy::none, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.5F, error_threshold)); find_linear_interpolation_samples_with_duration(31, 1.0F, 1.0F, sample_rounding_policy::none, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 30); CHECK(key1 == 30); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(31, 1.0F, 2.5F / 30.0F, sample_rounding_policy::floor, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(31, 1.0F, 2.5F / 30.0F, sample_rounding_policy::ceil, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 1.0F, error_threshold)); find_linear_interpolation_samples_with_duration(31, 1.0F, 2.4F / 30.0F, sample_rounding_policy::nearest, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(31, 1.0F, 2.6F / 30.0F, sample_rounding_policy::nearest, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 1.0F, error_threshold)); // Test a static pose find_linear_interpolation_samples_with_duration(1, 0.0F, 0.0F, sample_rounding_policy::none, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(1, 0.0F, 0.0F, sample_rounding_policy::floor, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(1, 0.0F, 0.0F, sample_rounding_policy::ceil, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 1.0F, error_threshold)); find_linear_interpolation_samples_with_duration(1, 0.0F, 0.0F, sample_rounding_policy::nearest, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); } { // Wrapping looping policy uint32_t key0; uint32_t key1; float alpha; find_linear_interpolation_samples_with_duration(30, 1.0F, 0.0F, sample_rounding_policy::none, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 1); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(30, 1.0F, 1.0F / 30.0F, sample_rounding_policy::none, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 1); CHECK(key1 == 2); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(30, 1.0F, 2.5F / 30.0F, sample_rounding_policy::none, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.5F, error_threshold)); find_linear_interpolation_samples_with_duration(30, 1.0F, 1.0F, sample_rounding_policy::none, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(30, 1.0F, 2.5F / 30.0F, sample_rounding_policy::floor, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(30, 1.0F, 2.5F / 30.0F, sample_rounding_policy::ceil, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 1.0F, error_threshold)); find_linear_interpolation_samples_with_duration(30, 1.0F, 2.4F / 30.0F, sample_rounding_policy::nearest, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(30, 1.0F, 2.6F / 30.0F, sample_rounding_policy::nearest, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 1.0F, error_threshold)); // Test a static pose find_linear_interpolation_samples_with_duration(1, 1.0F / 30.0F, 0.0F, sample_rounding_policy::none, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(1, 1.0F / 30.0F, 0.0F, sample_rounding_policy::floor, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(1, 1.0F / 30.0F, 0.0F, sample_rounding_policy::ceil, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 1.0F, error_threshold)); find_linear_interpolation_samples_with_duration(1, 1.0F / 30.0F, 0.0F, sample_rounding_policy::nearest, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); // When we wrap, even a static pose has some duration find_linear_interpolation_samples_with_duration(1, 1.0F / 30.0F, 1.0F / 30.0F, sample_rounding_policy::none, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK((scalar_near_equal(alpha, 0.0F, error_threshold) || scalar_near_equal(alpha, 1.0F, error_threshold))); find_linear_interpolation_samples_with_duration(1, 1.0F / 30.0F, 0.5F / 30.0F, sample_rounding_policy::none, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 0.5F, error_threshold)); find_linear_interpolation_samples_with_duration(1, 1.0F / 30.0F, 1.0F / 30.0F, sample_rounding_policy::floor, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_duration(1, 1.0F / 30.0F, 1.0F / 30.0F, sample_rounding_policy::ceil, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 1.0F, error_threshold)); find_linear_interpolation_samples_with_duration(1, 1.0F / 30.0F, 1.0F / 30.0F, sample_rounding_policy::nearest, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK((scalar_near_equal(alpha, 0.0F, error_threshold) || scalar_near_equal(alpha, 1.0F, error_threshold))); } ////////////////////////////////////////////////////////////////////////// { // Clamped looping policy uint32_t key0; uint32_t key1; float alpha; find_linear_interpolation_samples_with_sample_rate(31, 30.0F, 0.0F, sample_rounding_policy::none, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 1); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(31, 30.0F, 1.0F / 30.0F, sample_rounding_policy::none, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 1); CHECK(key1 == 2); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(31, 30.0F, 2.5F / 30.0F, sample_rounding_policy::none, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.5F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(31, 30.0F, 1.0F, sample_rounding_policy::none, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 30); CHECK(key1 == 30); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(31, 30.0F, 2.5F / 30.0F, sample_rounding_policy::floor, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(31, 30.0F, 2.5F / 30.0F, sample_rounding_policy::ceil, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 1.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(31, 30.0F, 2.4F / 30.0F, sample_rounding_policy::nearest, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(31, 30.0F, 2.6F / 30.0F, sample_rounding_policy::nearest, sample_looping_policy::clamp, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 1.0F, error_threshold)); } { // Wrapping looping policy uint32_t key0; uint32_t key1; float alpha; find_linear_interpolation_samples_with_sample_rate(30, 30.0F, 0.0F, sample_rounding_policy::none, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 1); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(30, 30.0F, 1.0F / 30.0F, sample_rounding_policy::none, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 1); CHECK(key1 == 2); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(30, 30.0F, 2.5F / 30.0F, sample_rounding_policy::none, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.5F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(30, 30.0F, 1.0F, sample_rounding_policy::none, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 0); CHECK(key1 == 0); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(30, 30.0F, 2.5F / 30.0F, sample_rounding_policy::floor, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(30, 30.0F, 2.5F / 30.0F, sample_rounding_policy::ceil, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 1.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(30, 30.0F, 2.4F / 30.0F, sample_rounding_policy::nearest, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 0.0F, error_threshold)); find_linear_interpolation_samples_with_sample_rate(30, 30.0F, 2.6F / 30.0F, sample_rounding_policy::nearest, sample_looping_policy::wrap, key0, key1, alpha); CHECK(key0 == 2); CHECK(key1 == 3); CHECK(scalar_near_equal(alpha, 1.0F, error_threshold)); } ////////////////////////////////////////////////////////////////////////// { // Clamping looping policy CHECK(scalar_near_equal(find_linear_interpolation_alpha(0.0F, 1, 1, sample_rounding_policy::none, sample_looping_policy::clamp), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 2, sample_rounding_policy::none, sample_looping_policy::clamp), 0.5F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 2, sample_rounding_policy::none, sample_looping_policy::clamp), 0.75F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 3, sample_rounding_policy::none, sample_looping_policy::clamp), 0.5F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 4, sample_rounding_policy::none, sample_looping_policy::clamp), 0.16666667F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(0.0F, 1, 1, sample_rounding_policy::floor, sample_looping_policy::clamp), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 2, sample_rounding_policy::floor, sample_looping_policy::clamp), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 2, sample_rounding_policy::floor, sample_looping_policy::clamp), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 3, sample_rounding_policy::floor, sample_looping_policy::clamp), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 4, sample_rounding_policy::floor, sample_looping_policy::clamp), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(0.0F, 1, 1, sample_rounding_policy::ceil, sample_looping_policy::clamp), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 2, sample_rounding_policy::ceil, sample_looping_policy::clamp), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 2, sample_rounding_policy::ceil, sample_looping_policy::clamp), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 3, sample_rounding_policy::ceil, sample_looping_policy::clamp), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 4, sample_rounding_policy::ceil, sample_looping_policy::clamp), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(0.0F, 1, 1, sample_rounding_policy::nearest, sample_looping_policy::clamp), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 2, sample_rounding_policy::nearest, sample_looping_policy::clamp), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 2, sample_rounding_policy::nearest, sample_looping_policy::clamp), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 3, sample_rounding_policy::nearest, sample_looping_policy::clamp), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 4, sample_rounding_policy::nearest, sample_looping_policy::clamp), 0.0F, error_threshold)); } { // Wrapping looping policy CHECK(scalar_near_equal(find_linear_interpolation_alpha(0.0F, 1, 1, sample_rounding_policy::none, sample_looping_policy::wrap), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 2, sample_rounding_policy::none, sample_looping_policy::wrap), 0.5F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 2, sample_rounding_policy::none, sample_looping_policy::wrap), 0.75F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 3, sample_rounding_policy::none, sample_looping_policy::wrap), 0.5F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 4, sample_rounding_policy::none, sample_looping_policy::wrap), 0.16666667F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(2.5F, 2, 0, sample_rounding_policy::none, sample_looping_policy::wrap), 0.5F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(0.0F, 1, 1, sample_rounding_policy::floor, sample_looping_policy::wrap), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 2, sample_rounding_policy::floor, sample_looping_policy::wrap), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 2, sample_rounding_policy::floor, sample_looping_policy::wrap), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 3, sample_rounding_policy::floor, sample_looping_policy::wrap), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 4, sample_rounding_policy::floor, sample_looping_policy::wrap), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(2.5F, 2, 0, sample_rounding_policy::floor, sample_looping_policy::wrap), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(0.0F, 1, 1, sample_rounding_policy::ceil, sample_looping_policy::wrap), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 2, sample_rounding_policy::ceil, sample_looping_policy::wrap), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 2, sample_rounding_policy::ceil, sample_looping_policy::wrap), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 3, sample_rounding_policy::ceil, sample_looping_policy::wrap), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 4, sample_rounding_policy::ceil, sample_looping_policy::wrap), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(2.5F, 2, 0, sample_rounding_policy::ceil, sample_looping_policy::wrap), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(0.0F, 1, 1, sample_rounding_policy::nearest, sample_looping_policy::wrap), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 2, sample_rounding_policy::nearest, sample_looping_policy::wrap), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 2, sample_rounding_policy::nearest, sample_looping_policy::wrap), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 0, 3, sample_rounding_policy::nearest, sample_looping_policy::wrap), 1.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(1.5F, 1, 4, sample_rounding_policy::nearest, sample_looping_policy::wrap), 0.0F, error_threshold)); CHECK(scalar_near_equal(find_linear_interpolation_alpha(2.5F, 2, 0, sample_rounding_policy::nearest, sample_looping_policy::wrap), 1.0F, error_threshold)); } ////////////////////////////////////////////////////////////////////////// CHECK(scalar_near_equal(apply_rounding_policy(0.2F, sample_rounding_policy::none), 0.2F, error_threshold)); CHECK(apply_rounding_policy(0.2F, sample_rounding_policy::floor) == 0.0F); CHECK(apply_rounding_policy(0.2F, sample_rounding_policy::ceil) == 1.0F); CHECK(apply_rounding_policy(0.2F, sample_rounding_policy::nearest) == 0.0F); CHECK(scalar_near_equal(apply_rounding_policy(0.2F, sample_rounding_policy::per_track), 0.2F, error_threshold)); CHECK(scalar_near_equal(apply_rounding_policy(0.8F, sample_rounding_policy::none), 0.8F, error_threshold)); CHECK(apply_rounding_policy(0.8F, sample_rounding_policy::floor) == 0.0F); CHECK(apply_rounding_policy(0.8F, sample_rounding_policy::ceil) == 1.0F); CHECK(apply_rounding_policy(0.8F, sample_rounding_policy::nearest) == 1.0F); CHECK(scalar_near_equal(apply_rounding_policy(0.8F, sample_rounding_policy::per_track), 0.8F, error_threshold)); }
[ "zeno490@gmail.com" ]
zeno490@gmail.com
3dc68864596b71dda8c442bdac177670ecc593c4
48d5dbf4475448f5df6955f418d7c42468d2a165
/SDK/SoT_BP_hair_col_brown_03_Desc_parameters.hpp
4191a0a2b810f5184f05df1d424dd64e8433e048
[]
no_license
Outshynd/SoT-SDK-1
80140ba84fe9f2cdfd9a402b868099df4e8b8619
8c827fd86a5a51f3d4b8ee34d1608aef5ac4bcc4
refs/heads/master
2022-11-21T04:35:29.362290
2020-07-10T14:50:55
2020-07-10T14:50:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
380
hpp
#pragma once // Sea of Thieves (1.4.16) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_hair_col_brown_03_Desc_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "53855178+Shat-sky@users.noreply.github.com" ]
53855178+Shat-sky@users.noreply.github.com
afac4dcbaf61694d1c00e8aea61c10d557252a5f
eb69a246a9dbd9d12512db28513e54e56ed5461f
/src/eeprom_emu.h
d1a9079a52261f408870a2f4361bdb6d9901bd57
[ "MIT" ]
permissive
erwzqsdsdsf/dispenser
9c0de83ac6248c4b81df86c6eee5c1ef7201b83b
e0283af232a65a840dedb15feaaccf1294a3a7cb
refs/heads/master
2023-02-26T00:26:58.783689
2021-01-21T23:51:58
2021-01-21T23:51:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,678
h
#ifndef __EEPROM_EMU__ #define __EEPROM_EMU__ #include <stdint.h> /* Driver class FlashDriver { public: enum { BankSize = XXXX }; static void erase(uint8_t bank) {}; static uint32_t read(uint8_t bank, uint16_t addr); // If 32bit write requires multiple operations, those MUST follow from // least significant bits to most significant bits. static uint32_t write(uint8_t bank, uint16_t addr, uint32_t data); } */ /* Bank structure: [ 8 bytes bank marker ] [ 8 bytes record ] [ 8 bytes record ]... Bank Marker: - [ 0x77EE, 0xFFFF, 0xFFFF, 0xFFFF ] => active, current - [ 0x77EE, NOT_EMPTY, 0xFFFF, 0xFFFF ] => ready to erase (!active) - [ 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF ] => erased OR on progress of transfer Data record: [ 0x55AA, address_16, data_lo_16, data_hi_16 ] 2-phase commits used to guarantee data consistency. Commit mark (0x55AA) is stored separate, because many modern flashes use additional ECC bits and not allow old data partial override with zero bits. Value 0x55AA at record start means write was completed with success */ template <typename FLASH_DRIVER> class EepromEmu { enum { EMPTY = 0xFFFF, RECORD_SIZE = 8, BANK_HEADER_SIZE = 8, COMMIT_MARK = 0x55AA, BANK_MARK = 0x77EE, BANK_DIRTY_MARK = 0x5555 }; bool initialized = false; uint8_t current_bank = 0; uint32_t next_write_offset; bool is_clear(uint8_t bank) { for (uint32_t i = 0; i < FLASH_DRIVER::BankSize; i += 2) { if (flash.read_u16(bank, i) != EMPTY) return false; } return true; } bool is_active(uint8_t bank) { if ((flash.read_u16(bank, 0) == BANK_MARK) && (flash.read_u16(bank, 2) == EMPTY) && (flash.read_u16(bank, 4) == EMPTY) && (flash.read_u16(bank, 6) == EMPTY)) return true; return false; } uint32_t find_write_offset() { uint32_t ofs = BANK_HEADER_SIZE; for (; ofs <= FLASH_DRIVER::BankSize - RECORD_SIZE; ofs += RECORD_SIZE) { if ((flash.read_u16(current_bank, ofs + 0) == EMPTY) && (flash.read_u16(current_bank, ofs + 2) == EMPTY) && (flash.read_u16(current_bank, ofs + 4) == EMPTY) && (flash.read_u16(current_bank, ofs + 6) == EMPTY)) break; } return ofs; } void move_bank(uint8_t from, uint8_t to, uint16_t ignore_addr=UINT16_MAX) { if (!is_clear(to)) flash.erase(to); uint32_t dst_end_addr = BANK_HEADER_SIZE; for (uint32_t ofs = BANK_HEADER_SIZE; ofs < next_write_offset; ofs += RECORD_SIZE) { // Skip invalid records if (flash.read_u16(from, ofs + 0) != COMMIT_MARK) continue; uint16_t addr = flash.read_u16(from, ofs + 2); // Skip variable with ignored address if (addr == ignore_addr) continue; uint16_t lo = flash.read_u16(from, ofs + 4); uint16_t hi = flash.read_u16(from, ofs + 6); bool more_fresh_exists = false; // Check if more fresh record exists for (uint32_t i = ofs + RECORD_SIZE; i < next_write_offset; i += RECORD_SIZE) { // Skip invalid records if (flash.read_u16(from, i + 0) != COMMIT_MARK) continue; // Skip different addresses if (flash.read_u16(from, i + 2) != addr) continue; // More fresh (=> already copied) found more_fresh_exists = true; break; } if (more_fresh_exists) continue; flash.write_u16(to, dst_end_addr + 2, addr); flash.write_u16(to, dst_end_addr + 4, lo); flash.write_u16(to, dst_end_addr + 6, hi); flash.write_u16(to, dst_end_addr + 0, COMMIT_MARK); dst_end_addr += RECORD_SIZE; } // Mark new bank active flash.write_u16(to, 0, BANK_MARK); current_bank = to; next_write_offset = dst_end_addr; // Clean old bank in 2 steps to avoid UB: destroy header & run erase flash.write_u16(from, 2, BANK_DIRTY_MARK); flash.write_u16(from, 4, BANK_DIRTY_MARK); flash.write_u16(from, 6, BANK_DIRTY_MARK); flash.erase(from); } void init() { initialized = true; if (is_active(0)) current_bank = 0; else if (is_active(1)) current_bank = 1; else { // Both banks have no valid markers => prepare first one if (!is_clear(0)) flash.erase(0); flash.write_u16(0, 0, BANK_MARK); current_bank = 0; } next_write_offset = find_write_offset(); return; } public: FLASH_DRIVER flash; uint32_t read_u32(uint16_t addr, uint32_t dflt) { if (!initialized) init(); // Reverse scan, stop on first valid for (uint32_t ofs = next_write_offset;;) { if (ofs <= BANK_HEADER_SIZE) break; ofs -= RECORD_SIZE; if (flash.read_u16(current_bank, ofs + 0) != COMMIT_MARK) continue; if (flash.read_u16(current_bank, ofs + 2) != addr) continue; uint16_t lo = flash.read_u16(current_bank, ofs + 4); uint16_t hi = flash.read_u16(current_bank, ofs + 6); return (hi << 16) + lo; } return dflt; } void write_u32(uint16_t addr, uint32_t val) { if (!initialized) init(); uint8_t bank = current_bank; // Don't write the same value uint32_t previous = read_u32(addr, val+1); if (previous == val) return; // Check free space and swap banks if needed if (next_write_offset + RECORD_SIZE > FLASH_DRIVER::BankSize) { move_bank(bank, bank ^ 1, addr); bank ^= 1; } // Write data flash.write_u16(bank, next_write_offset + 2, addr); flash.write_u16(bank, next_write_offset + 4, val & 0xFFFF); flash.write_u16(bank, next_write_offset + 6, (uint16_t)(val >> 16) & 0xFFFF); flash.write_u16(bank, next_write_offset + 0, COMMIT_MARK); next_write_offset += RECORD_SIZE; } float read_float(uint16_t addr, float dflt) { union { uint32_t i; float f; } x; x.f = dflt; x.i = read_u32(addr, x.i); return x.f; } void write_float(uint16_t addr, float val) { union { uint32_t i; float f; } x; x.f = val; write_u32(addr, x.i); } }; #endif
[ "vitaly@rcdesign.ru" ]
vitaly@rcdesign.ru
68f6d61195a7babf5d64e8a165b6e1cec5ade918
a2c03109b555a0bc988e08d22203836eb9e2fde3
/11.12.2017.Praktikum10/Problem1.cpp
22a47d66fd647269d56c88cac039fab2963e1b82
[]
no_license
fmi-lab/sdp-2017-kn-group3-n-4
7b79b1a8690feda90818f3769710d9347c74b4fe
49e998707efa9847721d6c5ff9a3417412049120
refs/heads/master
2021-05-16T05:09:42.515778
2018-01-15T17:41:48
2018-01-15T17:41:48
106,302,430
5
2
null
2017-12-20T11:26:20
2017-10-09T15:37:00
C++
UTF-8
C++
false
false
1,425
cpp
#include "../templates/tree.cpp" #include <iostream> using namespace std; struct OpNode { char operation; int value; OpNode() { this->operation = 0; this->value = 0; } OpNode(char operation) { this->operation = operation; this->value = 0; } OpNode(int value) { this->operation = 0; this->value = value; } bool isOperation() { return this->operation != 0; } }; int calculate(const tree<OpNode>& t) { if (t.empty()) { return 0; } if (!(t.getRoot()->inf).isOperation()) { return (t.getRoot()->inf).value; } int left = calculate(t.LeftTree()); int right = calculate(t.RightTree()); switch ((t.getRoot()->inf).operation) { case '*': return left * right; case '+': return left + right; case '-': return left - right; case '/': return right == 0 ? 0 : left / right; default: return 0; } } int main() { tree<OpNode> t10; t10.Create3(OpNode(10), tree<OpNode>(), tree<OpNode>()); tree<OpNode> t3; t3.Create3(OpNode(3), tree<OpNode>(), tree<OpNode>()); tree<OpNode> t5; t5.Create3(OpNode(5), tree<OpNode>(), tree<OpNode>()); tree<OpNode> t2; t2.Create3(OpNode(2), tree<OpNode>(), tree<OpNode>()); tree<OpNode> t_1; t_1.Create3(OpNode('-'), t10, t3); tree<OpNode> t_2; t_2.Create3(OpNode('+'), t2, t5); tree<OpNode> t; t.Create3(OpNode('*'), t_2, t_1); cout << calculate(t) << " == 49" << endl; }
[ "noreply@github.com" ]
fmi-lab.noreply@github.com
2dccb6ce2484c676f9e117a75dd28d887d43ebad
8b4525741a33753a982788fdee97dc3d6c9d2789
/src/net.h
d4bf5c31e6b2675f7ebbf3b2665c7c4082dc1d96
[ "MIT" ]
permissive
ygtars/revu
b6fb59628cd9bf67aac86786b4cfee865feb3e4b
b824a844b8b8f508a00b05e09915b44ece32a844
refs/heads/master
2020-04-22T18:25:48.229140
2019-02-15T17:58:01
2019-02-15T17:58:01
170,576,715
0
0
null
null
null
null
UTF-8
C++
false
false
21,093
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_NET_H #define BITCOIN_NET_H #include "bloom.h" #include "compat.h" #include "hash.h" #include "limitedmap.h" #include "mruset.h" #include "netbase.h" #include "protocol.h" #include "random.h" #include "streams.h" #include "sync.h" #include "uint256.h" #include "utilstrencodings.h" #include <deque> #include <stdint.h> #ifndef WIN32 #include <arpa/inet.h> #endif #include <boost/filesystem/path.hpp> #include <boost/foreach.hpp> #include <boost/signals2/signal.hpp> class CAddrMan; class CBlockIndex; class CNode; namespace boost { class thread_group; } // namespace boost /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */ static const int PING_INTERVAL = 2 * 60; /** Time after which to disconnect, after waiting for a ping response (or inactivity). */ static const int TIMEOUT_INTERVAL = 20 * 60; /** The maximum number of entries in an 'inv' protocol message */ static const unsigned int MAX_INV_SZ = 50000; /** The maximum number of new addresses to accumulate before announcing. */ static const unsigned int MAX_ADDR_TO_SEND = 1000; /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */ static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 2 * 1024 * 1024; /** -listen default */ static const bool DEFAULT_LISTEN = true; /** -upnp default */ #ifdef USE_UPNP static const bool DEFAULT_UPNP = USE_UPNP; #else static const bool DEFAULT_UPNP = false; #endif /** The maximum number of entries in mapAskFor */ static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ; unsigned int ReceiveFloodSize(); unsigned int SendBufferSize(); void AddOneShot(std::string strDest); bool RecvLine(SOCKET hSocket, std::string& strLine); void AddressCurrentlyConnected(const CService& addr); CNode* FindNode(const CNetAddr& ip); CNode* FindNode(const std::string& addrName); CNode* FindNode(const CService& ip); CNode* ConnectNode(CAddress addrConnect, const char* pszDest = NULL, bool obfuScationMaster = false); bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant* grantOutbound = NULL, const char* strDest = NULL, bool fOneShot = false); void MapPort(bool fUseUPnP); unsigned short GetListenPort(); bool BindListenPort(const CService& bindAddr, std::string& strError, bool fWhitelisted = false); void StartNode(boost::thread_group& threadGroup); bool StopNode(); void SocketSendData(CNode* pnode); typedef int NodeId; // Signals for message handling struct CNodeSignals { boost::signals2::signal<int()> GetHeight; boost::signals2::signal<bool(CNode*)> ProcessMessages; boost::signals2::signal<bool(CNode*, bool)> SendMessages; boost::signals2::signal<void(NodeId, const CNode*)> InitializeNode; boost::signals2::signal<void(NodeId)> FinalizeNode; }; CNodeSignals& GetNodeSignals(); enum { LOCAL_NONE, // unknown LOCAL_IF, // address a local interface listens on LOCAL_BIND, // address explicit bound to LOCAL_UPNP, // address reported by UPnP LOCAL_MANUAL, // address explicitly specified (-externalip=) LOCAL_MAX }; bool IsPeerAddrLocalGood(CNode* pnode); void AdvertizeLocal(CNode* pnode); void SetLimited(enum Network net, bool fLimited = true); bool IsLimited(enum Network net); bool IsLimited(const CNetAddr& addr); bool AddLocal(const CService& addr, int nScore = LOCAL_NONE); bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE); bool RemoveLocal(const CService& addr); bool SeenLocal(const CService& addr); bool IsLocal(const CService& addr); bool GetLocal(CService& addr, const CNetAddr* paddrPeer = NULL); bool IsReachable(enum Network net); bool IsReachable(const CNetAddr& addr); void SetReachable(enum Network net, bool fFlag = true); CAddress GetLocalAddress(const CNetAddr* paddrPeer = NULL); extern bool fDiscover; extern bool fListen; extern uint64_t nLocalServices; extern uint64_t nLocalHostNonce; extern CAddrMan addrman; extern int nMaxConnections; extern std::vector<CNode*> vNodes; extern CCriticalSection cs_vNodes; extern std::map<CInv, CDataStream> mapRelay; extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration; extern CCriticalSection cs_mapRelay; extern limitedmap<CInv, int64_t> mapAlreadyAskedFor; extern std::vector<std::string> vAddedNodes; extern CCriticalSection cs_vAddedNodes; extern NodeId nLastNodeId; extern CCriticalSection cs_nLastNodeId; struct LocalServiceInfo { int nScore; int nPort; }; extern CCriticalSection cs_mapLocalHost; extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost; class CNodeStats { public: NodeId nodeid; uint64_t nServices; int64_t nLastSend; int64_t nLastRecv; int64_t nTimeConnected; std::string addrName; int nVersion; std::string cleanSubVer; bool fInbound; int nStartingHeight; uint64_t nSendBytes; uint64_t nRecvBytes; bool fWhitelisted; double dPingTime; double dPingWait; std::string addrLocal; }; class CNetMessage { public: bool in_data; // parsing header (false) or data (true) CDataStream hdrbuf; // partially received header CMessageHeader hdr; // complete header unsigned int nHdrPos; CDataStream vRecv; // received message data unsigned int nDataPos; int64_t nTime; // time (in microseconds) of message receipt. CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) { hdrbuf.resize(24); in_data = false; nHdrPos = 0; nDataPos = 0; nTime = 0; } bool complete() const { if (!in_data) return false; return (hdr.nMessageSize == nDataPos); } void SetVersion(int nVersionIn) { hdrbuf.SetVersion(nVersionIn); vRecv.SetVersion(nVersionIn); } int readHeader(const char* pch, unsigned int nBytes); int readData(const char* pch, unsigned int nBytes); }; /** Information about a peer */ class CNode { public: // socket uint64_t nServices; SOCKET hSocket; CDataStream ssSend; size_t nSendSize; // total size of all vSendMsg entries size_t nSendOffset; // offset inside the first vSendMsg already sent uint64_t nSendBytes; std::deque<CSerializeData> vSendMsg; CCriticalSection cs_vSend; std::deque<CInv> vRecvGetData; std::deque<CNetMessage> vRecvMsg; CCriticalSection cs_vRecvMsg; uint64_t nRecvBytes; int nRecvVersion; int64_t nLastSend; int64_t nLastRecv; int64_t nTimeConnected; CAddress addr; std::string addrName; CService addrLocal; int nVersion; // strSubVer is whatever byte array we read from the revu. However, this field is intended // to be printed out, displayed to humans in various forms and so on. So we sanitize it and // store the sanitized version in cleanSubVer. The original should be used when dealing with // the network or revu types and the cleaned string used when displayed or logged. std::string strSubVer, cleanSubVer; bool fWhitelisted; // This peer can bypass DoS banning. bool fOneShot; bool fClient; bool fInbound; bool fNetworkNode; bool fSuccessfullyConnected; bool fDisconnect; // We use fRelayTxes for two purposes - // a) it allows us to not relay tx invs before receiving the peer's version message // b) the peer may tell us in their version message that we should not relay tx invs // until they have initialized their bloom filter. bool fRelayTxes; // Should be 'true' only if we connected to this node to actually mix funds. // In this case node will be released automatically via CMasternodeMan::ProcessMasternodeConnections(). // Connecting to verify connectability/status or connecting for sending/relaying single message // (even if it's relative to mixing e.g. for blinding) should NOT set this to 'true'. // For such cases node should be released manually (preferably right after corresponding code). bool fObfuScationMaster; CSemaphoreGrant grantOutbound; CCriticalSection cs_filter; CBloomFilter* pfilter; int nRefCount; NodeId id; protected: // Denial-of-service detection/prevention // Key is IP address, value is banned-until-time static std::map<CNetAddr, int64_t> setBanned; static CCriticalSection cs_setBanned; std::vector<std::string> vecRequestsFulfilled; //keep track of what client has asked for // Whitelisted ranges. Any node connecting from these is automatically // whitelisted (as well as those connecting to whitelisted binds). static std::vector<CSubNet> vWhitelistedRange; static CCriticalSection cs_vWhitelistedRange; // Basic fuzz-testing void Fuzz(int nChance); // modifies ssSend public: uint256 hashContinue; int nStartingHeight; // flood relay std::vector<CAddress> vAddrToSend; mruset<CAddress> setAddrKnown; bool fGetAddr; std::set<uint256> setKnown; // inventory based relay mruset<CInv> setInventoryKnown; std::vector<CInv> vInventoryToSend; CCriticalSection cs_inventory; std::multimap<int64_t, CInv> mapAskFor; std::vector<uint256> vBlockRequested; // Ping time measurement: // The pong reply we're expecting, or 0 if no pong expected. uint64_t nPingNonceSent; // Time (in usec) the last ping was sent, or 0 if no ping was ever sent. int64_t nPingUsecStart; // Last measured round-trip time. int64_t nPingUsecTime; // Whether a ping is requested. bool fPingQueued; CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn = false); ~CNode(); private: // Network usage totals static CCriticalSection cs_totalBytesRecv; static CCriticalSection cs_totalBytesSent; static uint64_t nTotalBytesRecv; static uint64_t nTotalBytesSent; CNode(const CNode&); void operator=(const CNode&); public: NodeId GetId() const { return id; } int GetRefCount() { assert(nRefCount >= 0); return nRefCount; } // requires LOCK(cs_vRecvMsg) unsigned int GetTotalRecvSize() { unsigned int total = 0; BOOST_FOREACH (const CNetMessage& msg, vRecvMsg) total += msg.vRecv.size() + 24; return total; } // requires LOCK(cs_vRecvMsg) bool ReceiveMsgBytes(const char* pch, unsigned int nBytes); // requires LOCK(cs_vRecvMsg) void SetRecvVersion(int nVersionIn) { nRecvVersion = nVersionIn; BOOST_FOREACH (CNetMessage& msg, vRecvMsg) msg.SetVersion(nVersionIn); } CNode* AddRef() { nRefCount++; return this; } void Release() { nRefCount--; } void AddAddressKnown(const CAddress& addr) { setAddrKnown.insert(addr); } void PushAddress(const CAddress& addr) { // Known checking here is only to save space from duplicates. // SendMessages will filter it again for knowns that were added // after addresses were pushed. if (addr.IsValid() && !setAddrKnown.count(addr)) { if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) { vAddrToSend[insecure_rand() % vAddrToSend.size()] = addr; } else { vAddrToSend.push_back(addr); } } } void AddInventoryKnown(const CInv& inv) { { LOCK(cs_inventory); setInventoryKnown.insert(inv); } } void PushInventory(const CInv& inv) { { LOCK(cs_inventory); if (!setInventoryKnown.count(inv)) vInventoryToSend.push_back(inv); } } void AskFor(const CInv& inv); // TODO: Document the postcondition of this function. Is cs_vSend locked? void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend); // TODO: Document the precondition of this function. Is cs_vSend locked? void AbortMessage() UNLOCK_FUNCTION(cs_vSend); // TODO: Document the precondition of this function. Is cs_vSend locked? void EndMessage() UNLOCK_FUNCTION(cs_vSend); void PushVersion(); void PushMessage(const char* pszCommand) { try { BeginMessage(pszCommand); EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1> void PushMessage(const char* pszCommand, const T1& a1) { try { BeginMessage(pszCommand); ssSend << a1; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2) { try { BeginMessage(pszCommand); ssSend << a1 << a2; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9, const T10& a10) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9, const T10& a10, const T11& a11) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10 << a11; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9, const T10& a10, const T11& a11, const T12& a12) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10 << a11 << a12; EndMessage(); } catch (...) { AbortMessage(); throw; } } bool HasFulfilledRequest(std::string strRequest) { BOOST_FOREACH (std::string& type, vecRequestsFulfilled) { if (type == strRequest) return true; } return false; } void ClearFulfilledRequest(std::string strRequest) { std::vector<std::string>::iterator it = vecRequestsFulfilled.begin(); while (it != vecRequestsFulfilled.end()) { if ((*it) == strRequest) { vecRequestsFulfilled.erase(it); return; } ++it; } } void FulfilledRequest(std::string strRequest) { if (HasFulfilledRequest(strRequest)) return; vecRequestsFulfilled.push_back(strRequest); } bool IsSubscribed(unsigned int nChannel); void Subscribe(unsigned int nChannel, unsigned int nHops = 0); void CancelSubscribe(unsigned int nChannel); void CloseSocketDisconnect(); bool DisconnectOldProtocol(int nVersionRequired, std::string strLastCommand = ""); // Denial-of-service detection/prevention // The idea is to detect peers that are behaving // badly and disconnect/ban them, but do it in a // one-coding-mistake-won't-shatter-the-entire-network // way. // IMPORTANT: There should be nothing I can give a // node that it will forward on that will make that // node's peers drop it. If there is, an attacker // can isolate a node and/or try to split the network. // Dropping a node for sending stuff that is invalid // now but might be valid in a later version is also // dangerous, because it can cause a network split // between nodes running old code and nodes running // new code. static void ClearBanned(); // needed for unit testing static bool IsBanned(CNetAddr ip); static bool Ban(const CNetAddr& ip); void copyStats(CNodeStats& stats); static bool IsWhitelistedRange(const CNetAddr& ip); static void AddWhitelistedRange(const CSubNet& subnet); // Network stats static void RecordBytesRecv(uint64_t bytes); static void RecordBytesSent(uint64_t bytes); static uint64_t GetTotalBytesRecv(); static uint64_t GetTotalBytesSent(); }; class CExplicitNetCleanup { public: static void callCleanup(); }; class CTransaction; void RelayTransaction(const CTransaction& tx); void RelayTransaction(const CTransaction& tx, const CDataStream& ss); void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll = false); void RelayInv(CInv& inv); /** Access to the (IP) address database (peers.dat) */ class CAddrDB { private: boost::filesystem::path pathAddr; public: CAddrDB(); bool Write(const CAddrMan& addr); bool Read(CAddrMan& addr); }; #endif // BITCOIN_NET_H
[ "arslanyigit357@gmail.com" ]
arslanyigit357@gmail.com
ef8c3bcb0722068fc2eb384eb45b5827cbd3a6e2
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/MuonSpectrometer/MuonCalib/MdtCalib/MdtCalibData/MdtCalibData/MdtSlewCorFuncHardcoded.h
c97f039df854215943acd3baa8020c2f3fb39411
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
797
h
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #ifndef MUONCALIB_MdtSlewCorFuncHardcoded_H #define MUONCALIB_MdtSlewCorFuncHardcoded_H #include "MdtCalibData/IMdtSlewCorFunc.h" #include "map" namespace MuonCalib { /** implementation of a slewing correction function */ class MdtSlewCorFuncHardcoded : public IMdtSlewCorFunc { public: explicit MdtSlewCorFuncHardcoded( const CalibFunc::ParVec& vec ) : IMdtSlewCorFunc(vec){} inline virtual std::string name() const { return "MdtSlewCorFuncHardCoded"; } static unsigned int nUsedPar() { return 0; } virtual double correction(double t, double adc) const; double calibrated_p(const double & adc) const; static std::map<short, float> m_LUT; }; } //namespace MuonCalib #endif
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
bddf6454464696764ba67e4ee039e54a55cb26cb
2399db04cc7e656106cc65fa5121d47e02413a0a
/Stack.cpp
c3d999fbd3e4430dee2cf9df5b711a69cca601d7
[]
no_license
ChoiSunPil/dataStructure
b0fd5bd88c1ecf8812831aa57ad0a2b7ee06b931
9a16782390c99aad7562ac36ffc9dbeecc38f36d
refs/heads/master
2020-04-20T17:18:47.871072
2019-02-07T11:08:44
2019-02-07T11:08:44
168,985,332
0
0
null
null
null
null
UTF-8
C++
false
false
856
cpp
// // Created by 최선필 on 03/02/2019. // #include "Stack.h" using namespace std; template <typename T> int Stack<T>::getSize() { return top+1; } template <typename T> bool Stack<T>::isEmpty() { if(top == -1) return true; else return false; } template <typename T> T Stack<T>::pop() { if(!isEmpty()) return array[top--]; else return 0; } template <typename T> void Stack<T>::push(T node) { top++; array[top] = node; if(getSize() == capacity) { T * tmp = new T[capacity*2]; for(int i = 0 ; i < capacity ; i++) { tmp[i] = array[i]; } delete array; array = tmp; } } template <typename T> Stack<T>::Stack() { top = -1; capacity =20; array = new T[capacity]; } template <typename T> Stack<T>::~Stack() { delete array; cout<<"delete stack"<<endl; }
[ "roung4119@gmail.com" ]
roung4119@gmail.com
662b1f422f8c45987a133372f672e295c509c9a7
af8f0279f0a89b91bbe17fe6f13c4f5c72a45a13
/UVa/uva1588.cpp
93629c5caebb2be2e2df6a6b9fcedaa9bb438edd
[]
no_license
duguyue100/acm-training
3669a5e80093c9fa4040dfa9ba433330acf9fe8d
c0911c6a12d578c0da7458a68db586926bc594c0
refs/heads/master
2022-09-18T17:40:24.837083
2022-08-20T13:20:08
2022-08-20T13:20:08
11,473,607
62
43
null
2020-09-30T19:28:19
2013-07-17T10:41:42
C++
UTF-8
C++
false
false
1,540
cpp
// UVa 1588 Kickdown #include<bits/stdc++.h> using namespace std; int main() { // freopen("input.in", "r", stdin); // freopen("output.out", "w", stdout); string line1, line2; while (cin >> line1 >> line2) { if (line1.size() < line2.size()) { swap(line1, line2); } size_t lin1_l = line1.size(); size_t lin2_l = line2.size(); string padding(line2.size()-1, '0'); line1 = padding+line1+padding; int min_len = lin1_l+lin2_l; for (size_t i=0; i<lin1_l+lin2_l-1; i++) { int flag = true; for (size_t j=0; j<lin2_l; j++) { if ((line2[j]-'0')+(line1[i+j]-'0') > 3) { flag = false; break; } } if (flag == true) { int len = 0; // output length if (i >= lin2_l-1 && i<= lin1_l-1) { len = lin1_l; min_len = len; break; } else if (i<lin2_l-1) { len = lin1_l+lin2_l-1-i; } else if (i>lin1_l-2) { len = i+1; } if (min_len > len) { min_len = len; } } } cout << min_len << endl; } return 0; }
[ "duguyue100@gmail.com" ]
duguyue100@gmail.com
a955ed7762bb7bcf1e8a2e1e253468b64aeccb8d
39586ec324eb4f52bb98c92fa385096c70cc97f5
/RNet/Socket.h
99f9d68594beb75321a4c87678e93467092723e2
[]
no_license
rvdweerd/RNet
5da7945931e1d38b24a2f3d01a41b95e414f9582
fff9942f237e1dedd75f0e0abbf98d1c939426a6
refs/heads/master
2020-09-25T08:10:37.697166
2019-12-07T14:16:24
2019-12-07T14:16:24
225,958,809
0
0
null
null
null
null
UTF-8
C++
false
false
523
h
#pragma once #include "SocketHandle.h" #include "RResult.h" #include "IPVersion.h" #include "SocketOptions.h" #include "IPEndPoint.h" namespace RNet { class Socket { public: Socket( IPVersion ipversion = IPVersion::IPv4, SocketHandle handle = INVALID_SOCKET); RResult Create(); RResult Close(); SocketHandle GetHandle(); IPVersion GetIPVersion(); private: RResult SetSocketOption(SocketOption option, BOOL value); IPVersion ipversion = IPVersion::IPv4; SocketHandle handle = INVALID_SOCKET; }; }
[ "rogerscode@gmail.com" ]
rogerscode@gmail.com
8614ee9feff99902c965061d6f458799fd4656fe
988d2a132be3d3f36a985d848f6d4cc54748d5e7
/experimental/Pomdog.Experimental/Utility/UserPreferences.cpp
8bc0e49b96564c4e1d006d792dfb84b8ea7c30fc
[ "MIT" ]
permissive
ValtoForks/pomdog
24336f3342c51a25a0260144bdc72f6bf0bb4a35
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
refs/heads/master
2021-05-03T15:47:12.979889
2019-01-04T15:42:05
2019-01-04T15:42:05
120,486,114
0
0
NOASSERTION
2019-01-04T15:42:06
2018-02-06T16:15:53
C++
UTF-8
C++
false
false
6,384
cpp
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #include "UserPreferences.hpp" #include "Pomdog/Content/Utility/BinaryFileStream.hpp" #include "Pomdog/Content/Utility/BinaryReader.hpp" #include "Pomdog/Utility/Assert.hpp" #include "Pomdog/Utility/Exception.hpp" #include "Pomdog/Utility/FileSystem.hpp" #include "Pomdog/Utility/PathHelper.hpp" #include "Pomdog/Logging/Log.hpp" #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <fstream> namespace Pomdog { namespace { template <typename T> rapidjson::Value ToJsonValue(T const& v) { auto value = rapidjson::Value(v); return value; } rapidjson::Value ToJsonValue(std::string const& s) { auto value = rapidjson::Value( s.c_str(), static_cast<rapidjson::SizeType>(s.size())); return value; } template <typename T, typename Func> std::optional<T> GetJsonValue(const std::string& jsonData, const std::string& key, Func func) { POMDOG_ASSERT(!key.empty()); if (jsonData.empty()) { return std::nullopt; } rapidjson::Document doc; doc.Parse(jsonData.data()); POMDOG_ASSERT(!doc.HasParseError()); POMDOG_ASSERT(doc.IsObject()); if (!doc.HasMember(key.c_str())) { return std::nullopt; } auto & v = doc[key.c_str()]; return func(v); } template <typename T> void SetJsonValue(std::string& jsonData, const std::string& key, const T& value) { POMDOG_ASSERT(!key.empty()); rapidjson::Document doc; if (!jsonData.empty()) { doc.Parse(jsonData.data()); POMDOG_ASSERT(!doc.HasParseError()); POMDOG_ASSERT(doc.IsObject()); } if (!doc.HasMember(key.c_str())) { doc.AddMember(ToJsonValue(key), ToJsonValue(value), doc.GetAllocator()); } else { doc[key.c_str()] = ToJsonValue(value); } rapidjson::StringBuffer buf; rapidjson::Writer<rapidjson::StringBuffer> writer(buf); doc.Accept(writer); jsonData.clear(); jsonData.assign(buf.GetString(), buf.GetSize()); } } // unnamed namespace UserPreferences::UserPreferences() : needToSave(false) { using Detail::BinaryReader; const auto directory = FileSystem::GetLocalAppDataDirectoryPath(); filePath = PathHelper::Join(directory, "UserPreferences.json"); if (!FileSystem::IsDirectory(directory)) { if (!FileSystem::CreateDirectory(directory)) { POMDOG_THROW_EXCEPTION(std::runtime_error, "Failed to create directory: " + directory); } } if (FileSystem::Exists(filePath)) { auto binaryFile = PathHelper::OpenStream(filePath); if (!binaryFile.Stream) { POMDOG_THROW_EXCEPTION(std::runtime_error, "Failed to open file"); } if (binaryFile.SizeInBytes > 0) { auto data = BinaryReader::ReadString<char>( binaryFile.Stream, binaryFile.SizeInBytes); jsonData.assign(data.data(), data.size()); POMDOG_ASSERT(!jsonData.empty()); } } if (!jsonData.empty()) { rapidjson::Document doc; doc.Parse(jsonData.data()); if (doc.HasParseError() || !doc.IsObject()) { // FUS RO DAH POMDOG_THROW_EXCEPTION(std::runtime_error, "Failed to parse JSON"); } } else { jsonData = "{}"; } Log::Internal("UserPreferences path: " + filePath); } std::optional<bool> UserPreferences::GetBool(const std::string& key) const { POMDOG_ASSERT(!key.empty()); return GetJsonValue<bool>(jsonData, key, [](const rapidjson::Value& v) -> std::optional<bool> { if (v.IsBool()) { return v.GetBool(); } return std::nullopt; }); } std::optional<float> UserPreferences::GetFloat(const std::string& key) const { POMDOG_ASSERT(!key.empty()); return GetJsonValue<float>(jsonData, key, [](const rapidjson::Value& v) -> std::optional<float> { if (v.IsNumber()) { return static_cast<float>(v.GetDouble()); } return std::nullopt; }); } std::optional<int> UserPreferences::GetInt(const std::string& key) const { return GetJsonValue<int>(jsonData, key, [](const rapidjson::Value& v) -> std::optional<int> { if (v.IsInt()) { return v.GetInt(); } if (v.IsUint()) { return v.GetUint(); } return std::nullopt; }); } std::optional<std::string> UserPreferences::GetString(const std::string& key) const { return GetJsonValue<std::string>(jsonData, key, [](const rapidjson::Value& v) -> std::optional<std::string> { if (v.IsString()) { std::string value = v.GetString(); return std::move(value); } return std::nullopt; }); } bool UserPreferences::HasKey(std::string const& key) { POMDOG_ASSERT(!key.empty()); if (jsonData.empty()) { return false; } rapidjson::Document doc; doc.Parse(jsonData.data()); POMDOG_ASSERT(!doc.HasParseError()); POMDOG_ASSERT(doc.IsObject()); return doc.HasMember(key.c_str()); } void UserPreferences::SetBool(std::string const& key, bool value) { POMDOG_ASSERT(!key.empty()); SetJsonValue(jsonData, key, value); needToSave = true; } void UserPreferences::SetFloat(std::string const& key, float value) { POMDOG_ASSERT(!key.empty()); SetJsonValue(jsonData, key, value); needToSave = true; } void UserPreferences::SetInt(std::string const& key, int value) { POMDOG_ASSERT(!key.empty()); SetJsonValue(jsonData, key, value); needToSave = true; } void UserPreferences::SetString(std::string const& key, std::string const& value) { POMDOG_ASSERT(!key.empty()); SetJsonValue(jsonData, key, value); needToSave = true; } void UserPreferences::Save() { POMDOG_ASSERT(!filePath.empty()); if (!needToSave) { return; } if (jsonData.empty()) { return; } std::ofstream stream(filePath, std::ios_base::out | std::ios_base::binary); if (!stream) { // FUS RO DAH POMDOG_THROW_EXCEPTION(std::runtime_error, "Cannot open file: " + filePath); } stream << jsonData; needToSave = false; } } // namespace Pomdog
[ "mogemimi@enginetrouble.net" ]
mogemimi@enginetrouble.net
b8378fad4c7804af04710d83efe0461dbee3bcf3
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/vc7addon/vs/src/vc/ide/pkgs/projbld/stdconversion/dirmgr.cpp
8d2e38484ec236c68f57eb09532bdba8cc5a7040
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,034
cpp
// DIRMGR.CPP // ---------- // Implementation of CDirMgr and CToolset class. // // History // ======= // 28-Aug-93 mattg Created // 10-Jan-94 colint Added CToolset class // //////////////////////////////////////////////////////////// // Include files #include "stdafx.h" #pragma hdrstop #include "dirmgr.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif //////////////////////////////////////////////////////////// // Global variables CDirMgr g_theDirMgr; // The one and only CDirMgr CDirMgr * GetDirMgr() {return &g_theDirMgr;} //////////////////////////////////////////////////////////// // Helper routines static VOID DestroyListContents ( CObList * pList ) { POSITION pos = pList->GetHeadPosition(); while (pos != NULL) delete pList->GetNext(pos); pList->RemoveAll(); } //////////////////////////////////////////////////////////// // CToolset Class //////////////////////////////////////////////////////////// // Constructors, destructors CToolset::CToolset ( ) { INT type; for (type=0; type<C_DIRLIST_TYPES ; ++type) m_Dirs[type] = new CObList; } CToolset::~CToolset ( ) { INT type; CObList * pList; for (type=0; type<C_DIRLIST_TYPES ; ++type) { if ((pList = m_Dirs[(DIRLIST_TYPE)type]) != NULL) { DestroyListContents(pList); delete pList; } } } //////////////////////////////////////////////////////////// // CToolset::GetDirList CObList * CToolset::GetDirList ( DIRLIST_TYPE type ) { VSASSERT((type >= (DIRLIST_TYPE)0) && (type < C_DIRLIST_TYPES), "DirList type out of bounds"); return (m_Dirs[type]); } ///////////////////////////////////////////////////////////// // CToolset::GetDirListString VOID CToolset::GetDirListString ( CString& str, DIRLIST_TYPE type ) { str.Empty(); VSASSERT((type >= (DIRLIST_TYPE)0) && (type < C_DIRLIST_TYPES), "DirList type out of bounds"); if (type < DIRLIST_PATH || type >= C_DIRLIST_TYPES) return; CObList* pList = GetDirList(type); if (pList == NULL) return; POSITION pos = pList->GetHeadPosition(); while (pos != (POSITION)NULL) { if (!str.IsEmpty()) str += _T(";"); str += (const TCHAR *)*(CDir *)pList->GetNext(pos); } } ///////////////////////////////////////////////////////////// // CToolset::RefreshAllCachedStrings VOID CToolset::RefreshAllCachedStrings ( ) { INT type; for ( type = 0; type < C_DIRLIST_TYPES ; ++type ) { CString &str = m_DirString[type]; CObList *pList = m_Dirs[type]; str.Empty(); if ( pList != NULL ) { POSITION pos = pList->GetHeadPosition(); while ( pos != NULL ) { if (!str.IsEmpty()) str += _T(';'); str += (const TCHAR *)*(CDir *)pList->GetNext(pos); } } } } //////////////////////////////////////////////////////////// // CToolset::SetDirList VOID CToolset::SetDirList ( DIRLIST_TYPE type, CObList * pListNew ) { VSASSERT((type >= (DIRLIST_TYPE)0) && (type < C_DIRLIST_TYPES), "DirList type out of bounds"); VSASSERT(pListNew != NULL, "Cannot add NULL list"); if (m_Dirs[type] != NULL) { DestroyListContents(m_Dirs[type]); delete m_Dirs[type]; } m_Dirs[type] = pListNew; RefreshAllCachedStrings( ); } //////////////////////////////////////////////////////////// // CDirMgr Class //////////////////////////////////////////////////////////// // Constructors, destructors CDirMgr::CDirMgr ( ) { m_nCurrentToolset = 0; } CDirMgr::~CDirMgr ( ) { POSITION pos; CToolset * pToolset; pos = m_Toolsets.GetHeadPosition(); while (pos != NULL) { pToolset = (CToolset *)m_Toolsets.GetNext(pos); delete pToolset; } m_Toolsets.RemoveAll(); } //////////////////////////////////////////////////////////// // CDirMgr::GetCurrentToolset // // This returns the current toolset for the project, if // one exists. If we don't have a project then we will // return whatever m_nCurrentToolset was last set to. INT CDirMgr::GetCurrentToolset ( ) { int nToolset = g_BldSysIFace.GetProjectToolset(ACTIVE_PROJECT); if( nToolset == -1 ) nToolset = m_nCurrentToolset; return nToolset; } //////////////////////////////////////////////////////////// // CDirMgr::SetCurrentToolset VOID CDirMgr::SetCurrentToolset ( INT nToolset ) { if (nToolset >= 0 && nToolset < m_Toolsets.GetCount()) m_nCurrentToolset = nToolset; } //////////////////////////////////////////////////////////// // CDirMgr::GetNumberOfToolsets INT CDirMgr::GetNumberOfToolsets ( ) { return (INT)m_Toolsets.GetCount(); } //////////////////////////////////////////////////////////// // CDirMgr::AddToolset INT CDirMgr::AddToolset ( const CString & strTargetPlatform ) { INT nToolset; CToolset * pToolset; nToolset = (INT)m_Toolsets.GetCount(); pToolset = new CToolset; m_Toolsets.AddTail(pToolset); m_ToolsetNames.AddTail(strTargetPlatform); return nToolset; } //////////////////////////////////////////////////////////// // CDirMgr::DeleteToolset VOID CDirMgr::DeleteToolset ( INT nToolset ) { POSITION pos; CToolset * pToolset; if (nToolset >= 0 && nToolset < m_Toolsets.GetCount()) { pos = m_Toolsets.FindIndex(nToolset); pToolset = (CToolset *)m_Toolsets.GetAt(pos); delete pToolset; m_Toolsets.RemoveAt(pos); m_ToolsetNames.RemoveAt(pos); } } //////////////////////////////////////////////////////////// // CDirMgr::GetToolset CToolset * CDirMgr::GetToolset ( INT nToolset ) { POSITION pos = m_Toolsets.FindIndex(nToolset); if (pos != NULL) return (CToolset *) (m_Toolsets.GetAt(pos)); else return NULL; } //////////////////////////////////////////////////////////// // CDirMgr::GetDirList const CObList * CDirMgr::GetDirList ( DIRLIST_TYPE type, INT nToolset /* = -1 */ ) { if (nToolset == -1) nToolset = GetCurrentToolset(); VSASSERT((type >= (DIRLIST_TYPE)0) && (type < C_DIRLIST_TYPES), "DirList type out of bounds"); CToolset * pToolset = GetToolset(nToolset); if (pToolset != NULL) return(pToolset->GetDirList(type)); else return NULL; } //////////////////////////////////////////////////////////// // CDirMgr::GetDirListString VOID CDirMgr::GetDirListString ( CString & strRet, DIRLIST_TYPE type, INT nToolset /* = -1 */ ) { if (nToolset == -1) nToolset = GetCurrentToolset(); VSASSERT((type >= (DIRLIST_TYPE)0) && (type < C_DIRLIST_TYPES), "DirList type out of bounds"); CToolset * pToolset = GetToolset(nToolset); if (pToolset != NULL) pToolset->GetDirListString(strRet, type); else strRet.Empty(); } //////////////////////////////////////////////////////////// // CDirMgr::CloneDirList CObList * CDirMgr::CloneDirList ( DIRLIST_TYPE type, INT nToolset ) { POSITION pos; CObList * pListSrc; CObList * pListDst; CDir * pDirSrc; CDir * pDirDst; VSASSERT((type >= (DIRLIST_TYPE)0) && (type < C_DIRLIST_TYPES), "DirList type out of bounds"); pListSrc = GetToolset(nToolset)->GetDirList(type); pListDst = new CObList; pos = pListSrc->GetHeadPosition(); while (pos != NULL) { pDirSrc = (CDir *)pListSrc->GetNext(pos); VSASSERT(pDirSrc->IsKindOf(RUNTIME_CLASS(CDir)), "DirList can only contain CDirs"); pDirDst = new CDir(*pDirSrc); pListDst->AddTail(pDirDst); } return(pListDst); } //////////////////////////////////////////////////////////// // CDirMgr::SetDirList VOID CDirMgr::SetDirList ( DIRLIST_TYPE type, INT nToolset, CObList * pListNew ) { CObList * pList; VSASSERT(pListNew != NULL, "Cannot set NULL list"); pList = GetToolset(nToolset)->GetDirList(type); GetToolset(nToolset)->SetDirList(type, pListNew); } //////////////////////////////////////////////////////////// // CDirMgr::SetDirListFromString VOID CDirMgr::SetDirListFromString ( DIRLIST_TYPE type, INT nToolset, const TCHAR * sz, BOOL fMustExist /* FALSE */ ) { TCHAR * pchCopy; TCHAR * pchDir; CString str = sz; CObList * pList; CDir * pDir; pList = GetToolset(nToolset)->GetDirList(type); if (pList == NULL) pList = new CObList; else DestroyListContents(pList); pchCopy = str.GetBuffer(1); pchDir = _tcstok(pchCopy, _T(";")); while (pchDir != NULL) { pDir = new CDir; if (!pDir->CreateFromString(pchDir)) { VSASSERT(FALSE, "Failed to create directory path!"); delete pDir; pchDir = _tcstok(NULL, _T(";")); continue; } // Check that the directory is not already // in the list. We do not add duplicates. BOOL fAddDir = TRUE; POSITION pos = pList->GetHeadPosition(); while (pos != NULL) { CDir * pTempDir = (CDir *)pList->GetNext(pos); if (*pTempDir == *pDir) { fAddDir = FALSE; break; // found, break-out } } // If we are to add this and it must exist, make // sure it does, otherwise don't add it if (fMustExist && fAddDir) fAddDir = pDir->ExistsOnDisk(); // If the directory is not a duplicate then add it, // else de-allocate if (fAddDir) pList->AddTail(pDir); else delete pDir; pchDir = _tcstok(NULL, _T(";")); } GetToolset(nToolset)->RefreshAllCachedStrings(); str.ReleaseBuffer(); } //////////////////////////////////////////////////////////// // CDirMgr::GetPlatformToolset INT CDirMgr::GetPlatformToolset ( const CString & strPlatform ) { POSITION pos; CString strToolsetName; INT nToolset = 0; pos = m_ToolsetNames.GetHeadPosition(); while (pos != NULL) { strToolsetName = m_ToolsetNames.GetNext(pos); if (strToolsetName == strPlatform) return nToolset; nToolset++; } return -1; } //////////////////////////////////////////////////////////// // CDirMgr::GetToolsetName CString & CDirMgr::GetToolsetName ( INT nToolset ) { POSITION pos = m_ToolsetNames.FindIndex(nToolset); VSASSERT (pos != NULL, "Toolset number not found!"); return m_ToolsetNames.GetAt(pos); } BOOL IsFileThere(const CString& strDir, const CString& strFName, CString& strFullPath) { VSASSERT(!strFName.IsEmpty(), "File name is blank!"); const TCHAR *pch = strFName; if ((strFName[0] != _T('\\')) && ((strFName.GetLength() < 2) || (*_tcsinc(pch) != _T(':')))) { if (strDir.IsEmpty()) return FALSE; strFullPath = strDir; // Add a backslash between path and fname if needed // chauv - crystal 1529 // can't use CString.Right(1).Compare("\\")) since this won't work with trailing backslash char in MBCS // if (strFullPath.Right(1).Compare("\\")) if ( _tcsrchr(strFullPath, '\\') != strFullPath.Right(1) ) strFullPath += "\\"; } strFullPath += strFName; if (_access(strFullPath, 04) == 0) // check for read privs return TRUE; return FALSE; }
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
e796cb7efc760d95844dd307fb94e9bf9a268d75
42ab733e143d02091d13424fb4df16379d5bba0d
/third_party/spirv-tools/source/fuzz/transformation.cpp
70a302b752aaaacf59e830d79565fbbbcba8551e
[ "Apache-2.0", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-generic-cla" ]
permissive
google/filament
11cd37ac68790fcf8b33416b7d8d8870e48181f0
0aa0efe1599798d887fa6e33c412c09e81bea1bf
refs/heads/main
2023-08-29T17:58:22.496956
2023-08-28T17:27:38
2023-08-28T17:27:38
143,455,116
16,631
1,961
Apache-2.0
2023-09-14T16:23:39
2018-08-03T17:26:00
C++
UTF-8
C++
false
false
23,427
cpp
// Copyright (c) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "source/fuzz/transformation.h" #include <cassert> #include "source/fuzz/fuzzer_util.h" #include "source/fuzz/transformation_access_chain.h" #include "source/fuzz/transformation_add_bit_instruction_synonym.h" #include "source/fuzz/transformation_add_constant_boolean.h" #include "source/fuzz/transformation_add_constant_composite.h" #include "source/fuzz/transformation_add_constant_null.h" #include "source/fuzz/transformation_add_constant_scalar.h" #include "source/fuzz/transformation_add_copy_memory.h" #include "source/fuzz/transformation_add_dead_block.h" #include "source/fuzz/transformation_add_dead_break.h" #include "source/fuzz/transformation_add_dead_continue.h" #include "source/fuzz/transformation_add_early_terminator_wrapper.h" #include "source/fuzz/transformation_add_function.h" #include "source/fuzz/transformation_add_global_undef.h" #include "source/fuzz/transformation_add_global_variable.h" #include "source/fuzz/transformation_add_image_sample_unused_components.h" #include "source/fuzz/transformation_add_local_variable.h" #include "source/fuzz/transformation_add_loop_preheader.h" #include "source/fuzz/transformation_add_loop_to_create_int_constant_synonym.h" #include "source/fuzz/transformation_add_no_contraction_decoration.h" #include "source/fuzz/transformation_add_opphi_synonym.h" #include "source/fuzz/transformation_add_parameter.h" #include "source/fuzz/transformation_add_relaxed_decoration.h" #include "source/fuzz/transformation_add_spec_constant_op.h" #include "source/fuzz/transformation_add_synonym.h" #include "source/fuzz/transformation_add_type_array.h" #include "source/fuzz/transformation_add_type_boolean.h" #include "source/fuzz/transformation_add_type_float.h" #include "source/fuzz/transformation_add_type_function.h" #include "source/fuzz/transformation_add_type_int.h" #include "source/fuzz/transformation_add_type_matrix.h" #include "source/fuzz/transformation_add_type_pointer.h" #include "source/fuzz/transformation_add_type_struct.h" #include "source/fuzz/transformation_add_type_vector.h" #include "source/fuzz/transformation_adjust_branch_weights.h" #include "source/fuzz/transformation_composite_construct.h" #include "source/fuzz/transformation_composite_extract.h" #include "source/fuzz/transformation_composite_insert.h" #include "source/fuzz/transformation_compute_data_synonym_fact_closure.h" #include "source/fuzz/transformation_duplicate_region_with_selection.h" #include "source/fuzz/transformation_equation_instruction.h" #include "source/fuzz/transformation_expand_vector_reduction.h" #include "source/fuzz/transformation_flatten_conditional_branch.h" #include "source/fuzz/transformation_function_call.h" #include "source/fuzz/transformation_inline_function.h" #include "source/fuzz/transformation_invert_comparison_operator.h" #include "source/fuzz/transformation_load.h" #include "source/fuzz/transformation_make_vector_operation_dynamic.h" #include "source/fuzz/transformation_merge_blocks.h" #include "source/fuzz/transformation_merge_function_returns.h" #include "source/fuzz/transformation_move_block_down.h" #include "source/fuzz/transformation_move_instruction_down.h" #include "source/fuzz/transformation_mutate_pointer.h" #include "source/fuzz/transformation_outline_function.h" #include "source/fuzz/transformation_permute_function_parameters.h" #include "source/fuzz/transformation_permute_phi_operands.h" #include "source/fuzz/transformation_propagate_instruction_down.h" #include "source/fuzz/transformation_propagate_instruction_up.h" #include "source/fuzz/transformation_push_id_through_variable.h" #include "source/fuzz/transformation_record_synonymous_constants.h" #include "source/fuzz/transformation_replace_add_sub_mul_with_carrying_extended.h" #include "source/fuzz/transformation_replace_boolean_constant_with_constant_binary.h" #include "source/fuzz/transformation_replace_branch_from_dead_block_with_exit.h" #include "source/fuzz/transformation_replace_constant_with_uniform.h" #include "source/fuzz/transformation_replace_copy_memory_with_load_store.h" #include "source/fuzz/transformation_replace_copy_object_with_store_load.h" #include "source/fuzz/transformation_replace_id_with_synonym.h" #include "source/fuzz/transformation_replace_irrelevant_id.h" #include "source/fuzz/transformation_replace_linear_algebra_instruction.h" #include "source/fuzz/transformation_replace_load_store_with_copy_memory.h" #include "source/fuzz/transformation_replace_opphi_id_from_dead_predecessor.h" #include "source/fuzz/transformation_replace_opselect_with_conditional_branch.h" #include "source/fuzz/transformation_replace_parameter_with_global.h" #include "source/fuzz/transformation_replace_params_with_struct.h" #include "source/fuzz/transformation_set_function_control.h" #include "source/fuzz/transformation_set_loop_control.h" #include "source/fuzz/transformation_set_memory_operands_mask.h" #include "source/fuzz/transformation_set_selection_control.h" #include "source/fuzz/transformation_split_block.h" #include "source/fuzz/transformation_store.h" #include "source/fuzz/transformation_swap_commutable_operands.h" #include "source/fuzz/transformation_swap_conditional_branch_operands.h" #include "source/fuzz/transformation_swap_function_variables.h" #include "source/fuzz/transformation_swap_two_functions.h" #include "source/fuzz/transformation_toggle_access_chain_instruction.h" #include "source/fuzz/transformation_vector_shuffle.h" #include "source/fuzz/transformation_wrap_early_terminator_in_function.h" #include "source/fuzz/transformation_wrap_region_in_selection.h" #include "source/fuzz/transformation_wrap_vector_synonym.h" #include "source/util/make_unique.h" namespace spvtools { namespace fuzz { Transformation::~Transformation() = default; std::unique_ptr<Transformation> Transformation::FromMessage( const protobufs::Transformation& message) { switch (message.transformation_case()) { case protobufs::Transformation::TransformationCase::kAccessChain: return MakeUnique<TransformationAccessChain>(message.access_chain()); case protobufs::Transformation::TransformationCase:: kAddBitInstructionSynonym: return MakeUnique<TransformationAddBitInstructionSynonym>( message.add_bit_instruction_synonym()); case protobufs::Transformation::TransformationCase::kAddConstantBoolean: return MakeUnique<TransformationAddConstantBoolean>( message.add_constant_boolean()); case protobufs::Transformation::TransformationCase::kAddConstantComposite: return MakeUnique<TransformationAddConstantComposite>( message.add_constant_composite()); case protobufs::Transformation::TransformationCase::kAddConstantNull: return MakeUnique<TransformationAddConstantNull>( message.add_constant_null()); case protobufs::Transformation::TransformationCase::kAddConstantScalar: return MakeUnique<TransformationAddConstantScalar>( message.add_constant_scalar()); case protobufs::Transformation::TransformationCase::kAddCopyMemory: return MakeUnique<TransformationAddCopyMemory>(message.add_copy_memory()); case protobufs::Transformation::TransformationCase::kAddDeadBlock: return MakeUnique<TransformationAddDeadBlock>(message.add_dead_block()); case protobufs::Transformation::TransformationCase::kAddDeadBreak: return MakeUnique<TransformationAddDeadBreak>(message.add_dead_break()); case protobufs::Transformation::TransformationCase::kAddDeadContinue: return MakeUnique<TransformationAddDeadContinue>( message.add_dead_continue()); case protobufs::Transformation::TransformationCase:: kAddEarlyTerminatorWrapper: return MakeUnique<TransformationAddEarlyTerminatorWrapper>( message.add_early_terminator_wrapper()); case protobufs::Transformation::TransformationCase::kAddFunction: return MakeUnique<TransformationAddFunction>(message.add_function()); case protobufs::Transformation::TransformationCase::kAddGlobalUndef: return MakeUnique<TransformationAddGlobalUndef>( message.add_global_undef()); case protobufs::Transformation::TransformationCase::kAddGlobalVariable: return MakeUnique<TransformationAddGlobalVariable>( message.add_global_variable()); case protobufs::Transformation::TransformationCase:: kAddImageSampleUnusedComponents: return MakeUnique<TransformationAddImageSampleUnusedComponents>( message.add_image_sample_unused_components()); case protobufs::Transformation::TransformationCase::kAddLocalVariable: return MakeUnique<TransformationAddLocalVariable>( message.add_local_variable()); case protobufs::Transformation::TransformationCase::kAddLoopPreheader: return MakeUnique<TransformationAddLoopPreheader>( message.add_loop_preheader()); case protobufs::Transformation::TransformationCase:: kAddLoopToCreateIntConstantSynonym: return MakeUnique<TransformationAddLoopToCreateIntConstantSynonym>( message.add_loop_to_create_int_constant_synonym()); case protobufs::Transformation::TransformationCase:: kAddNoContractionDecoration: return MakeUnique<TransformationAddNoContractionDecoration>( message.add_no_contraction_decoration()); case protobufs::Transformation::TransformationCase::kAddOpphiSynonym: return MakeUnique<TransformationAddOpPhiSynonym>( message.add_opphi_synonym()); case protobufs::Transformation::TransformationCase::kAddParameter: return MakeUnique<TransformationAddParameter>(message.add_parameter()); case protobufs::Transformation::TransformationCase::kAddRelaxedDecoration: return MakeUnique<TransformationAddRelaxedDecoration>( message.add_relaxed_decoration()); case protobufs::Transformation::TransformationCase::kAddSpecConstantOp: return MakeUnique<TransformationAddSpecConstantOp>( message.add_spec_constant_op()); case protobufs::Transformation::TransformationCase::kAddSynonym: return MakeUnique<TransformationAddSynonym>(message.add_synonym()); case protobufs::Transformation::TransformationCase::kAddTypeArray: return MakeUnique<TransformationAddTypeArray>(message.add_type_array()); case protobufs::Transformation::TransformationCase::kAddTypeBoolean: return MakeUnique<TransformationAddTypeBoolean>( message.add_type_boolean()); case protobufs::Transformation::TransformationCase::kAddTypeFloat: return MakeUnique<TransformationAddTypeFloat>(message.add_type_float()); case protobufs::Transformation::TransformationCase::kAddTypeFunction: return MakeUnique<TransformationAddTypeFunction>( message.add_type_function()); case protobufs::Transformation::TransformationCase::kAddTypeInt: return MakeUnique<TransformationAddTypeInt>(message.add_type_int()); case protobufs::Transformation::TransformationCase::kAddTypeMatrix: return MakeUnique<TransformationAddTypeMatrix>(message.add_type_matrix()); case protobufs::Transformation::TransformationCase::kAddTypePointer: return MakeUnique<TransformationAddTypePointer>( message.add_type_pointer()); case protobufs::Transformation::TransformationCase::kAddTypeStruct: return MakeUnique<TransformationAddTypeStruct>(message.add_type_struct()); case protobufs::Transformation::TransformationCase::kAddTypeVector: return MakeUnique<TransformationAddTypeVector>(message.add_type_vector()); case protobufs::Transformation::TransformationCase::kAdjustBranchWeights: return MakeUnique<TransformationAdjustBranchWeights>( message.adjust_branch_weights()); case protobufs::Transformation::TransformationCase::kCompositeConstruct: return MakeUnique<TransformationCompositeConstruct>( message.composite_construct()); case protobufs::Transformation::TransformationCase::kCompositeExtract: return MakeUnique<TransformationCompositeExtract>( message.composite_extract()); case protobufs::Transformation::TransformationCase::kCompositeInsert: return MakeUnique<TransformationCompositeInsert>( message.composite_insert()); case protobufs::Transformation::TransformationCase:: kComputeDataSynonymFactClosure: return MakeUnique<TransformationComputeDataSynonymFactClosure>( message.compute_data_synonym_fact_closure()); case protobufs::Transformation::TransformationCase:: kDuplicateRegionWithSelection: return MakeUnique<TransformationDuplicateRegionWithSelection>( message.duplicate_region_with_selection()); case protobufs::Transformation::TransformationCase::kEquationInstruction: return MakeUnique<TransformationEquationInstruction>( message.equation_instruction()); case protobufs::Transformation::TransformationCase::kExpandVectorReduction: return MakeUnique<TransformationExpandVectorReduction>( message.expand_vector_reduction()); case protobufs::Transformation::TransformationCase:: kFlattenConditionalBranch: return MakeUnique<TransformationFlattenConditionalBranch>( message.flatten_conditional_branch()); case protobufs::Transformation::TransformationCase::kFunctionCall: return MakeUnique<TransformationFunctionCall>(message.function_call()); case protobufs::Transformation::TransformationCase::kInlineFunction: return MakeUnique<TransformationInlineFunction>( message.inline_function()); case protobufs::Transformation::TransformationCase:: kInvertComparisonOperator: return MakeUnique<TransformationInvertComparisonOperator>( message.invert_comparison_operator()); case protobufs::Transformation::TransformationCase::kLoad: return MakeUnique<TransformationLoad>(message.load()); case protobufs::Transformation::TransformationCase:: kMakeVectorOperationDynamic: return MakeUnique<TransformationMakeVectorOperationDynamic>( message.make_vector_operation_dynamic()); case protobufs::Transformation::TransformationCase::kMergeBlocks: return MakeUnique<TransformationMergeBlocks>(message.merge_blocks()); case protobufs::Transformation::TransformationCase::kMergeFunctionReturns: return MakeUnique<TransformationMergeFunctionReturns>( message.merge_function_returns()); case protobufs::Transformation::TransformationCase::kMoveBlockDown: return MakeUnique<TransformationMoveBlockDown>(message.move_block_down()); case protobufs::Transformation::TransformationCase::kMoveInstructionDown: return MakeUnique<TransformationMoveInstructionDown>( message.move_instruction_down()); case protobufs::Transformation::TransformationCase::kMutatePointer: return MakeUnique<TransformationMutatePointer>(message.mutate_pointer()); case protobufs::Transformation::TransformationCase::kOutlineFunction: return MakeUnique<TransformationOutlineFunction>( message.outline_function()); case protobufs::Transformation::TransformationCase:: kPermuteFunctionParameters: return MakeUnique<TransformationPermuteFunctionParameters>( message.permute_function_parameters()); case protobufs::Transformation::TransformationCase::kPermutePhiOperands: return MakeUnique<TransformationPermutePhiOperands>( message.permute_phi_operands()); case protobufs::Transformation::TransformationCase:: kPropagateInstructionDown: return MakeUnique<TransformationPropagateInstructionDown>( message.propagate_instruction_down()); case protobufs::Transformation::TransformationCase::kPropagateInstructionUp: return MakeUnique<TransformationPropagateInstructionUp>( message.propagate_instruction_up()); case protobufs::Transformation::TransformationCase::kPushIdThroughVariable: return MakeUnique<TransformationPushIdThroughVariable>( message.push_id_through_variable()); case protobufs::Transformation::TransformationCase:: kRecordSynonymousConstants: return MakeUnique<TransformationRecordSynonymousConstants>( message.record_synonymous_constants()); case protobufs::Transformation::TransformationCase:: kReplaceAddSubMulWithCarryingExtended: return MakeUnique<TransformationReplaceAddSubMulWithCarryingExtended>( message.replace_add_sub_mul_with_carrying_extended()); case protobufs::Transformation::TransformationCase:: kReplaceBooleanConstantWithConstantBinary: return MakeUnique<TransformationReplaceBooleanConstantWithConstantBinary>( message.replace_boolean_constant_with_constant_binary()); case protobufs::Transformation::TransformationCase:: kReplaceBranchFromDeadBlockWithExit: return MakeUnique<TransformationReplaceBranchFromDeadBlockWithExit>( message.replace_branch_from_dead_block_with_exit()); case protobufs::Transformation::TransformationCase:: kReplaceConstantWithUniform: return MakeUnique<TransformationReplaceConstantWithUniform>( message.replace_constant_with_uniform()); case protobufs::Transformation::TransformationCase:: kReplaceCopyMemoryWithLoadStore: return MakeUnique<TransformationReplaceCopyMemoryWithLoadStore>( message.replace_copy_memory_with_load_store()); case protobufs::Transformation::TransformationCase:: kReplaceCopyObjectWithStoreLoad: return MakeUnique<TransformationReplaceCopyObjectWithStoreLoad>( message.replace_copy_object_with_store_load()); case protobufs::Transformation::TransformationCase::kReplaceIdWithSynonym: return MakeUnique<TransformationReplaceIdWithSynonym>( message.replace_id_with_synonym()); case protobufs::Transformation::TransformationCase::kReplaceIrrelevantId: return MakeUnique<TransformationReplaceIrrelevantId>( message.replace_irrelevant_id()); case protobufs::Transformation::TransformationCase:: kReplaceLinearAlgebraInstruction: return MakeUnique<TransformationReplaceLinearAlgebraInstruction>( message.replace_linear_algebra_instruction()); case protobufs::Transformation::TransformationCase:: kReplaceLoadStoreWithCopyMemory: return MakeUnique<TransformationReplaceLoadStoreWithCopyMemory>( message.replace_load_store_with_copy_memory()); case protobufs::Transformation::TransformationCase:: kReplaceOpselectWithConditionalBranch: return MakeUnique<TransformationReplaceOpSelectWithConditionalBranch>( message.replace_opselect_with_conditional_branch()); case protobufs::Transformation::TransformationCase:: kReplaceParameterWithGlobal: return MakeUnique<TransformationReplaceParameterWithGlobal>( message.replace_parameter_with_global()); case protobufs::Transformation::TransformationCase:: kReplaceParamsWithStruct: return MakeUnique<TransformationReplaceParamsWithStruct>( message.replace_params_with_struct()); case protobufs::Transformation::TransformationCase:: kReplaceOpphiIdFromDeadPredecessor: return MakeUnique<TransformationReplaceOpPhiIdFromDeadPredecessor>( message.replace_opphi_id_from_dead_predecessor()); case protobufs::Transformation::TransformationCase::kSetFunctionControl: return MakeUnique<TransformationSetFunctionControl>( message.set_function_control()); case protobufs::Transformation::TransformationCase::kSetLoopControl: return MakeUnique<TransformationSetLoopControl>( message.set_loop_control()); case protobufs::Transformation::TransformationCase::kSetMemoryOperandsMask: return MakeUnique<TransformationSetMemoryOperandsMask>( message.set_memory_operands_mask()); case protobufs::Transformation::TransformationCase::kSetSelectionControl: return MakeUnique<TransformationSetSelectionControl>( message.set_selection_control()); case protobufs::Transformation::TransformationCase::kSplitBlock: return MakeUnique<TransformationSplitBlock>(message.split_block()); case protobufs::Transformation::TransformationCase::kStore: return MakeUnique<TransformationStore>(message.store()); case protobufs::Transformation::TransformationCase::kSwapCommutableOperands: return MakeUnique<TransformationSwapCommutableOperands>( message.swap_commutable_operands()); case protobufs::Transformation::TransformationCase:: kSwapConditionalBranchOperands: return MakeUnique<TransformationSwapConditionalBranchOperands>( message.swap_conditional_branch_operands()); case protobufs::Transformation::TransformationCase::kSwapFunctionVariables: return MakeUnique<TransformationSwapFunctionVariables>( message.swap_function_variables()); case protobufs::Transformation::TransformationCase::kSwapTwoFunctions: return MakeUnique<TransformationSwapTwoFunctions>( message.swap_two_functions()); case protobufs::Transformation::TransformationCase:: kToggleAccessChainInstruction: return MakeUnique<TransformationToggleAccessChainInstruction>( message.toggle_access_chain_instruction()); case protobufs::Transformation::TransformationCase::kVectorShuffle: return MakeUnique<TransformationVectorShuffle>(message.vector_shuffle()); case protobufs::Transformation::TransformationCase:: kWrapEarlyTerminatorInFunction: return MakeUnique<TransformationWrapEarlyTerminatorInFunction>( message.wrap_early_terminator_in_function()); case protobufs::Transformation::TransformationCase::kWrapRegionInSelection: return MakeUnique<TransformationWrapRegionInSelection>( message.wrap_region_in_selection()); case protobufs::Transformation::TransformationCase::kWrapVectorSynonym: return MakeUnique<TransformationWrapVectorSynonym>( message.wrap_vector_synonym()); case protobufs::Transformation::TRANSFORMATION_NOT_SET: assert(false && "An unset transformation was encountered."); return nullptr; } assert(false && "Should be unreachable as all cases must be handled above."); return nullptr; } bool Transformation::CheckIdIsFreshAndNotUsedByThisTransformation( uint32_t id, opt::IRContext* ir_context, std::set<uint32_t>* ids_used_by_this_transformation) { if (!fuzzerutil::IsFreshId(ir_context, id)) { return false; } if (ids_used_by_this_transformation->count(id) != 0) { return false; } ids_used_by_this_transformation->insert(id); return true; } } // namespace fuzz } // namespace spvtools
[ "noreply@github.com" ]
google.noreply@github.com
5684490ce5484319bcc83ba2530e42e8df5d9e4c
513d32ec47f5c47a24e8b8fecd32e2c710617852
/png-write/png-write.cc
4cbad849cf859fee19cd64185da0beefc5cddb09
[]
no_license
stephen-opet/CPlusPlus-samples
6af4ddbd6438d59fbba4774a18006ba7c3e558b8
8d8d8ced7ee8d348f76c83df01f3525446324fc8
refs/heads/master
2022-08-10T18:01:17.479548
2020-05-24T05:49:16
2020-05-24T05:49:16
266,464,629
0
0
null
null
null
null
UTF-8
C++
false
false
7,228
cc
/* A Demonstration of Writing a PNG via NANOSVG library https://github.com/memononen/nanosvg/tree/master/example Written by Stephen Opet III, https://github.com/stephen-opet Published May 24, 2020 [in SARS-COV-2 quarentine :) ] This program demonstrates the following: Dynamic memory allocation via new/delete copy & move constructor implementation on bitmap class Writing a PNG via the nnosvg library operator overload The program uses a comprehensive and straightforward library to write a proper PNG image file!! Doing so from scratch is difficult and ugly - using a bitmap w/ this library is easy and fun! Designed and tested on UbuntuLinux w/ g++ compiler */ using namespace std; //seems to include swap()? used in operator= #include <iostream> #include <string> //using strings duh #include <cstring> //memcpy() #include <cmath> //round() -> Bresenham's_line_algorithm #define STB_IMAGE_WRITE_IMPLEMENTATION //writing to png lib #include "stb_image_write.h" inline void textcolor(char c){ switch(c) { case 'n': {cout << "\33[1;30m";break;} //black case 'r': {cout << "\33[1;31m";break;} //red case 'g': {cout << "\33[1;32m";break;} //green case 'b': {cout << "\33[1;34m";break;} //blue case 'y': {cout << "\33[1;33m";break;} //yellow case 'w': {cout << "\33[1;37m";break;} //white case 'd': {cout << "\33[0m";break;} //reset } } int endProgram(int v){ //eloquently abort main() textcolor('r'); cout << "\n\tEnd Program\n\n"; textcolor('d'); //restore defaults return v; } class DynamicBitmap { private: uint32_t w, h; uint32_t *p; public: //Constructor DynamicBitmap(uint32_t width, uint32_t height, uint32_t defaultBG) : w(width), h(height), p(new uint32_t[width*height]){ for(int k = 0; k < w*h; k++) //iterate through p(width) array p[k] = defaultBG; //set every pixel to default background color (black in our case) }//end constructor //Destructor ~DynamicBitmap(){ delete []p; }//end destructor //copy constructor DynamicBitmap(const DynamicBitmap& orig) : w(orig.w), h(orig.h), p(new uint32_t[orig.w * orig.h]) { memcpy(p, orig.p, orig.w * orig.h * sizeof(uint32_t)); }//end copy constructor //Operator = DynamicBitmap& operator =(DynamicBitmap copy){ // a2=a2 w = copy.w; h = copy.h; swap(p, copy.p); return *this; }//end operator= //move constructor DynamicBitmap(DynamicBitmap&& orig) : w(orig.w), h(orig.h), p(orig.p){ orig.p = nullptr; } uint32_t &operator ()(uint32_t x, uint32_t y){ cout << hex; //want to see hex value, not decimal return p[y*w + x]; } //set 1 | this is triggered by both get and set, for some reason??? //sets a pixel given coordinates & color //multiplication makes inefficient for simple shapes, but useful for complex algorithms void set(uint32_t x, uint32_t y, uint32_t color){ p[y*w + x] = color; } //set void horizLine(uint32_t x1, uint32_t x2, uint32_t y, uint32_t color){ uint32_t i = y*w+x1; //only uses multiplication once - more efficient than using set() for(; x1 <= x2; x1++) p[i++] = color; } void vertLine(uint32_t y1, uint32_t y2, uint32_t x, uint32_t color){ uint32_t index = y1*w+x; //only uses multiplication once - more efficient than using set() for(uint32_t i = 0; i < (y2-y1); i++){ p[index] = color; index+=w; } } //draws simple, hollow rectangle using horizontal & vertical line functions void drawRect(uint32_t x1, uint32_t y1, uint32_t rectW, uint32_t rectH, uint32_t color){ horizLine(x1,x1+rectW,y1,color); vertLine(y1,y1+rectH,x1,color); horizLine(x1,x1+rectW,y1+rectH,color); vertLine(y1,y1+rectH,x1+rectW,color); } //uses horzontal line function to fill in a rectangle void fillRect(uint32_t x1, uint32_t y1, uint32_t rectW, uint32_t rectH, uint32_t color){ for(uint32_t i = 0; i<=rectH; i++) horizLine(x1, x1+rectW, y1+i, color); } //assuming arguments are given as x0,y0,x1,y1,color - this order was not explicit void line(uint32_t x0, uint32_t y0, uint32_t x1, uint32_t y1, uint32_t color){ int64_t slope = 2 * (x1 - x0); //slope int64_t epsilon = slope - (y1 - y0); //error for (int64_t y = y0, x = x0; y <= y1; y++) { set(x,y,color); epsilon += slope; if (epsilon >= 0){ x++; epsilon -= 2*(y1 - y0); } } } //draw an ellipse void ellipse(int xcenter, int ycenter, int xd, int yd, uint32_t color){ double rad_conversion = 3.14159265359 / 180; //need conversion for C++ radian trig functions //compute angular eccentricity; //must account for either x or y acting as either major/minor axis double a,b; if(yd < xd){ b = yd/2; a = xd/2; } else{ b = xd/2; a = yd/2; } double alpha = acos(b/a); //arbitrarily choose to draw four points per degree about center of ellipse for (double theta = 0; theta < 360; theta += 0.25) { int64_t x = a * cos(rad_conversion * theta) * cos(rad_conversion * alpha) + b * sin(rad_conversion * theta) * sin(rad_conversion * alpha); int64_t y = b * sin(rad_conversion * theta) * cos(rad_conversion * alpha) - a * cos(rad_conversion * theta) * sin(rad_conversion * alpha); set(xcenter+x,ycenter-y,color); } } //write the PNG void save(string filename) const{ stbi_write_png(filename.c_str(), w, h, 4, p, w*4); cout << "\n\n\tData written to file, " + filename + "\n\n"; //formatting on main() textcolor('w'); } }; int main() { ///////////////////////////////////////////////////////////////////////////////////////////////////// Pretty Header textcolor('g'); cout << "\n\n_________________________________________________________________________________\n\n"; cout << "A Demonstration of Writing a PNG via NANOSVG library\n"; cout << "Written by Stephen Opet III\n"; cout << "https://github.com/stephen-opet\n\n\n"; textcolor('w'); constexpr uint32_t BLACK = 0xFF000000; // black opaque constexpr uint32_t RED = 0xFF0000FF; // red opaque constexpr uint32_t BLUE = 0xFFFF0000; // blue opaque constexpr uint32_t WHITE = 0xFFFFFFFF; // white opaque constexpr uint32_t YELLOW = 0xFF00FFFF; // yellow opaque constexpr uint32_t GREEN = 0xFF00FF00; // green opaque int xcenter = 100; int ycenter = 100; int xdiameter = 200; int ydiameter = 100; DynamicBitmap b(1024, 1024, BLACK); // Potentially dynamic size (Now: 1024 x 1024 pixels) b(32,32) = RED; cout << b(32,32); b.horizLine(0, 500, 200, RED); // Red horizontal line, from x=0 to x=500, at y = 200 b.vertLine(0, 399, 300, RED); // Red vertical line, from y=0 to y=399, at x = 300 b.drawRect(200,200, 100,50, BLUE); // Blue rectangle, TOP-LEFT at x=200, y=200. width=100, height=50 b.fillRect(201,201, 98,48, WHITE); // White rectangle, same rules as above, but filled with color b.line(400,0, 550,300, YELLOW); // Line drawn using https://en.wikipedia.org/wiki/Bresenham's_line_algorithm b.ellipse(xcenter, ycenter, xdiameter, ydiameter, GREEN); //Ellipse using specs from above b.save("bitmap2.png"); //create the png file endProgram(0); }
[ "slsh123456@gmail.com" ]
slsh123456@gmail.com
e82904aba1edc72a0597f4655d528bc09440da5d
0d32e5d45461a1edffd4c90cf63b915e9832eb6c
/assignment-7 Select Command/Attribute.cpp
1e8605c9d222dc8e8847eac82a87e9266ad46d47
[ "Apache-2.0" ]
permissive
Arda-Bati/Relational-Database
262c3ddf4b70a97cde6631872a7eb757ae5da65b
e3b121b5d8587552cc7177228ba5a5bea5c2cf68
refs/heads/main
2023-02-26T15:00:22.988177
2021-01-28T22:14:21
2021-01-28T22:14:21
310,962,752
3
0
null
null
null
null
UTF-8
C++
false
false
4,218
cpp
// // Attribute.cpp // Datatabase4 // // Created by rick gessner on 4/12/19. // Copyright © 2019 rick gessner. All rights reserved. // #include "Attribute.hpp" #include "Storage.hpp" #include "MemoryStream.hpp" #include "Helpers.hpp" namespace ECE141 { Attribute::Attribute(std::string aName, DataType aType, uint8_t aSize, bool autoIncr, bool aPrimary) : name(aName), type(aType), size(aSize) { autoIncrement=autoIncr; primary=aPrimary; nullable=true; } Attribute::Attribute(DataType aType) : type(aType) { autoIncrement=primary=false; nullable=true; } Attribute::Attribute(const Attribute &aCopy) : name(aCopy.name), type(aCopy.type), size(aCopy.size) { autoIncrement=aCopy.autoIncrement; nullable=aCopy.nullable; primary=aCopy.primary; } Attribute::~Attribute() { } Attribute& Attribute::setName(std::string &aName) {name=aName; return *this;} Attribute& Attribute::setType(DataType aType) {type=aType; return *this;} Attribute& Attribute::setSize(int aSize) {size=aSize; return *this;} Attribute& Attribute::setAutoIncrement(bool anAuto) {autoIncrement=anAuto; return *this;} Attribute& Attribute::setPrimaryKey(bool aPrimary) {primary=aPrimary; return *this;} Attribute& Attribute::setNullable(bool aNullable) {nullable=aNullable; return *this;} bool Attribute::isValid() { return true; } bool Attribute::isCompatible(DataType aType) const { return false; /* switch(aType) { case TokenType::number: return isNumericKeyword(type); case TokenType::identifier: case TokenType::string: return Keywords::varchar_kw==type; default: return false; } */ return false; } //how big a given attribute... size_t Attribute::getSize() const { switch(type) { case DataType::timestamp_type: case DataType::int_type: return sizeof(int32_t); case DataType::float_type: return sizeof(float); case DataType::varchar_type: return size; default: break; } return 0; } std::string Attribute::describeTabular() { std::string theResult; char theBuffer[100]; std::string nullableStr; std::string autoInc; nullable ? nullableStr = "Y" : nullableStr = "N"; autoIncrement ? autoInc = "auto" : autoInc = "" ; std::sprintf(theBuffer, "| %-17s |",name.c_str()); theResult+=theBuffer; std::sprintf(theBuffer," %-12s |", Helpers::dataTypeToString(type)); theResult+=theBuffer; std::sprintf(theBuffer," %-4s |", nullableStr.c_str()); theResult+=theBuffer; //nullable... static const char* keys[]={" ","PRI"}; const char *temp = keys[autoIncrement]; std::sprintf(theBuffer," %-4s |", temp); theResult+=theBuffer; //key... std::sprintf(theBuffer," %-14s |", " "); theResult+=theBuffer; std::sprintf(theBuffer," %-16s |", autoInc.c_str()); theResult+=theBuffer; return theResult; } bool Attribute::operator==(Attribute& anAttribute) { if (name==anAttribute.getName() && type==anAttribute.getType()) { return true; } return false; } // USE: read attribute properties from memory stream... BufferReader& operator >> (BufferReader& aReader, Attribute &aValue) { char theCharType; bool theIncr, thePrimary, theNull; uint8_t theSize; aReader >> aValue.name; aReader >> theCharType; aValue.type=static_cast<DataType>(theCharType); aReader >> theSize >> theIncr >> thePrimary >> theNull; aValue.size=theSize; aValue.autoIncrement=theIncr; aValue.primary=thePrimary; aValue.nullable=theNull; return aReader; } // USE: Write attribute properties into a memory stream... BufferWriter& operator << (BufferWriter& aWriter, const Attribute &aValue) { aWriter << aValue.name << static_cast<char>(aValue.type) << static_cast<uint8_t>(aValue.size) << static_cast<bool>(aValue.autoIncrement) << static_cast<bool>(aValue.primary) << static_cast<bool>(aValue.nullable); return aWriter; } }
[ "cankatbati@gmail.com" ]
cankatbati@gmail.com
b67f2d7cd85549439352b9f74792304e14d7c4b0
edf33c4335e8324250f590e1860a5030c2bb869e
/Tele_rec_TT.ino
a594d4a6ae2509bc59873a31ad8ce30b73f6be95
[]
no_license
Kulicheg/Tele_rec
786b3ce20388b1fb01a387321030a31c0e56d5e9
61e82c8a7eef66f7284a33dcb0b4b00f003689e4
refs/heads/master
2020-04-17T00:31:12.616387
2019-01-23T13:55:33
2019-01-23T13:55:33
166,052,580
0
0
null
null
null
null
UTF-8
C++
false
false
1,922
ino
// AA - 170 // AB - 171 // BA - 186 // BB - 187 #include <EEPROM.h> #include <AT24C256.h> #include <Wire.h> int Cycles = 400; int PackSize = 22; int NumRec = 12; byte JournalSize = 29; byte currentByte; byte header [4] = {170, 171, 186, 187}; byte command; int C_drive_c = EEPROM.length(); int C_drive_d = 32768; AT24C256 driveD(0x50); void setup() { Serial.begin(9600); Wire.begin(); EEPROM.put(945, 567); EEPROM.put(950, 330); EEPROM.put(947, 13); } void loop() { sendheader(01); Serial.write (NumRec); Serial.write (highByte(Cycles)); Serial.write (lowByte(Cycles)); Serial.flush(); delay (500); sendheader(02); //tone (3, 1000, 50); for ( int q = 0; q < Cycles * PackSize; q++) { byte Sendbyte = driveD.read (q); Serial.write (Sendbyte); } Serial.flush(); //tone (3, 1000, 50); for ( int q = 0; q < NumRec * JournalSize; q++) { byte Sendbyte = EEPROM.read (q); Serial.write (Sendbyte); } Serial.flush(); //tone (3, 1000, 50); for ( int q = 945; q < 1024 ; q++) { byte Sendbyte = EEPROM.read (q); Serial.write (Sendbyte); } Serial.flush(); //tone (3, 1000, 50); delay (10000); //Serial.println(eeprom_crc(), HEX); } unsigned long eeprom_crc(void) { const unsigned long crc_table[16] = { 0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; unsigned long crc = ~0L; for (int index = 0 ; index < EEPROM.length() ; ++index) { crc = crc_table[(crc ^ EEPROM[index]) & 0x0f] ^ (crc >> 4); crc = crc_table[(crc ^ (EEPROM[index] >> 4)) & 0x0f] ^ (crc >> 4); crc = ~crc; } return crc; } void sendheader(byte command) { for (byte q = 0; q < 4; q++) { Serial.write (header[q]); } Serial.write (command); }
[ "noreply@github.com" ]
Kulicheg.noreply@github.com
f08684476e3018d0ec5127442321cf4623e640d6
ebbe390ffdd7653730017fdb73dd5b4f6c15fd1e
/Tonya_earthquakescreens.ino
1e6de4cae2b1cec91545e79af6635aef244e87f9
[]
no_license
benthejack-vuw/Tonya-earthquakescreens
1b2719e4dba86d4f094fb4b62f8ef9240ec8d289
920ea70282e251c0b30c2cc7b55c29cdaf365541
refs/heads/master
2021-01-13T03:01:50.636689
2016-12-22T00:17:25
2016-12-22T00:17:25
77,018,217
0
0
null
null
null
null
UTF-8
C++
false
false
2,225
ino
//DONT CHANGE THESE, RATHER USE THE NAMES IN SETUP TO SET IT TO THE CORRECT ZONE //THE RASPBERRY PI USES THESE ADDRESSES SO IT'S IMPORTANT THAT THEY ARE LEFT AS IS #define ALASKA 1 #define CENTRAL_AMERICA 2 #define SOUTH_AMERICA 3 #define NEW_ZEALAND 4 #define JAPAN 5 //PINS USED FOR OLED SCREEN #define dc 9 #define rst 8 #define cs 7 // Color definitions #define BLACK 0x0000 #define BLUE 0x001F #define RED 0xF800 #define GREEN 0x07E0 #define CYAN 0x07FF #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define WHITE 0xFFFF #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1351.h> #include <SPI.h> //Option 2: use the hardware SPI pins (pins 11 & 13) Adafruit_SSD1351 tft = Adafruit_SSD1351(cs, dc, rst); bool motor = false; int earthquakeVibrationTime = 10; //time in seconds void setup() { //THE FOLLOWING LINE YOU NEED TO PUT IN THE CORRECT ZONE BEFORE UPLOADING TO THE ARDUINO Wire.begin(5`); Wire.onReceive(receiveEvent); // register event //-------------------------------------------------------------------------------------- tft.begin();//begins the OLED screen tft.fillScreen(BLACK); pinMode(2, OUTPUT); //for debugging LED - put an led between pin 9 and gnd with a 220ohm resistor for data testing digitalWrite(2, LOW); } void loop() { if(motor){ digitalWrite(2, HIGH); delay(earthquakeVibrationTime*1000); digitalWrite(2, LOW); motor = false; } delay(100); } void drawData(int data){ //YOUR EARTHQUAKE ELLIPSE DRAWING GOES HERE the data variable contains the magnitude of the quake //THIS FUNCTION WILL ONLY BE CALLED WHEN THERE IS A QUAKE IN THE CORRECT VICINITY //-------replace this drawing code, it currently only shows the data variable as text------------- tft.fillScreen(BLACK); tft.setCursor(0, 5); tft.setTextColor(BLUE); tft.setTextSize(3); tft.print(data); } // this function is registered as an event, it is triggered on an I2C commnication to this board. void receiveEvent(int howMany) { int x = Wire.read(); // receive byte as an integer drawData(x); motor = x > 0; }
[ "benthejack@gmail.com" ]
benthejack@gmail.com
527c4b8a3c882129936096c242e8500ee1ece0de
baf968b497038ae6e640fb2b71f32ae2e7befe4b
/celsiustofahrenheitconverter.hpp
eeeafe87e46aafe74062c8d35da392813cd07c8c
[]
no_license
elmeyer/software-engineering-ws15
3d86a94e1b68fbcea00183de9b6507ea89f11834
3e7d7f8a6a7c26548639b1b7e82e4758f35bcb87
refs/heads/master
2021-01-22T00:10:14.706519
2016-01-27T14:21:09
2016-01-27T14:21:09
44,805,521
0
0
null
2015-10-23T10:12:50
2015-10-23T10:12:49
C
UTF-8
C++
false
false
399
hpp
#ifndef CELSIUSTOFAHRENHEITCONVERTER_H #define CELSIUSTOFAHRENHEITCONVERTER_H #include "temperatureconverter.hpp" class celsiusToFahrenheitConverter: public temperatureConverter { public: celsiusToFahrenheitConverter(); celsiusToFahrenheitConverter(std::shared_ptr<UnitConverter> c); double convert(double inValue) const; // std::string toString() const; }; #endif
[ "lars.meyer@uni-weimar.de" ]
lars.meyer@uni-weimar.de
e35f3c89b0187d62ff14bc6bca00a194bff59133
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/third_party/WebKit/Source/core/html/custom/CustomElement.cpp
4b2a7e56b202431012d473eff0f3c81716e3e9c5
[ "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
10,215
cpp
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/html/custom/CustomElement.h" #include "core/dom/Document.h" #include "core/dom/QualifiedName.h" #include "core/frame/LocalDOMWindow.h" #include "core/html/HTMLElement.h" #include "core/html/HTMLUnknownElement.h" #include "core/html/custom/CEReactionsScope.h" #include "core/html/custom/CustomElementDefinition.h" #include "core/html/custom/CustomElementReactionStack.h" #include "core/html/custom/CustomElementRegistry.h" #include "core/html/custom/V0CustomElement.h" #include "core/html/custom/V0CustomElementRegistrationContext.h" #include "core/html_element_factory.h" #include "core/html_element_type_helpers.h" #include "platform/wtf/text/AtomicStringHash.h" namespace blink { CustomElementRegistry* CustomElement::Registry(const Element& element) { return Registry(element.GetDocument()); } CustomElementRegistry* CustomElement::Registry(const Document& document) { if (LocalDOMWindow* window = document.ExecutingWindow()) return window->customElements(); return nullptr; } static CustomElementDefinition* DefinitionForElementWithoutCheck( const Element& element) { DCHECK_EQ(element.GetCustomElementState(), CustomElementState::kCustom); return element.GetCustomElementDefinition(); } CustomElementDefinition* CustomElement::DefinitionForElement( const Element* element) { if (!element || element->GetCustomElementState() != CustomElementState::kCustom) return nullptr; return DefinitionForElementWithoutCheck(*element); } bool CustomElement::IsHyphenatedSpecElementName(const AtomicString& name) { // Even if Blink does not implement one of the related specs, (for // example annotation-xml is from MathML, which Blink does not // implement) we must prohibit using the name because that is // required by the HTML spec which we *do* implement. Don't remove // names from this list without removing them from the HTML spec // first. DEFINE_STATIC_LOCAL(HashSet<AtomicString>, hyphenated_spec_element_names, ({ "annotation-xml", "color-profile", "font-face", "font-face-src", "font-face-uri", "font-face-format", "font-face-name", "missing-glyph", })); return hyphenated_spec_element_names.Contains(name); } bool CustomElement::ShouldCreateCustomElement(const AtomicString& name) { return IsValidName(name); } bool CustomElement::ShouldCreateCustomElement(const QualifiedName& tag_name) { return ShouldCreateCustomElement(tag_name.LocalName()) && tag_name.NamespaceURI() == HTMLNames::xhtmlNamespaceURI; } bool CustomElement::ShouldCreateCustomizedBuiltinElement( const AtomicString& local_name) { return htmlElementTypeForTag(local_name) != HTMLElementType::kHTMLUnknownElement && RuntimeEnabledFeatures::CustomElementsBuiltinEnabled(); } bool CustomElement::ShouldCreateCustomizedBuiltinElement( const QualifiedName& tag_name) { return ShouldCreateCustomizedBuiltinElement(tag_name.LocalName()) && tag_name.NamespaceURI() == HTMLNames::xhtmlNamespaceURI; } static CustomElementDefinition* DefinitionFor( const Document& document, const CustomElementDescriptor desc) { if (CustomElementRegistry* registry = CustomElement::Registry(document)) return registry->DefinitionFor(desc); return nullptr; } HTMLElement* CustomElement::CreateCustomElementSync( Document& document, const QualifiedName& tag_name) { CustomElementDefinition* definition = nullptr; CustomElementRegistry* registry = CustomElement::Registry(document); if (registry) { definition = registry->DefinitionFor( CustomElementDescriptor(tag_name.LocalName(), tag_name.LocalName())); } return CreateCustomElementSync(document, tag_name, definition); } HTMLElement* CustomElement::CreateCustomElementSync( Document& document, const AtomicString& local_name, CustomElementDefinition* definition) { return CreateCustomElementSync( document, QualifiedName(g_null_atom, local_name, HTMLNames::xhtmlNamespaceURI), definition); } // https://dom.spec.whatwg.org/#concept-create-element HTMLElement* CustomElement::CreateCustomElementSync( Document& document, const QualifiedName& tag_name, CustomElementDefinition* definition) { DCHECK(ShouldCreateCustomElement(tag_name) || ShouldCreateCustomizedBuiltinElement(tag_name)); HTMLElement* element; if (definition && definition->Descriptor().IsAutonomous()) { // 6. If definition is non-null and we have an autonomous custom element element = definition->CreateElementSync(document, tag_name); } else if (definition) { // 5. If definition is non-null and we have a customized built-in element element = CreateUndefinedElement(document, tag_name); definition->Upgrade(element); } else { // 7. Otherwise element = CreateUndefinedElement(document, tag_name); } return element; } HTMLElement* CustomElement::CreateCustomElementAsync( Document& document, const QualifiedName& tag_name) { DCHECK(ShouldCreateCustomElement(tag_name)); // To create an element: // https://dom.spec.whatwg.org/#concept-create-element // 6. If definition is non-null, then: // 6.2. If the synchronous custom elements flag is not set: if (CustomElementDefinition* definition = DefinitionFor( document, CustomElementDescriptor(tag_name.LocalName(), tag_name.LocalName()))) return definition->CreateElementAsync(document, tag_name); return CreateUndefinedElement(document, tag_name); } // Create a HTMLElement HTMLElement* CustomElement::CreateUndefinedElement( Document& document, const QualifiedName& tag_name) { bool should_create_builtin = ShouldCreateCustomizedBuiltinElement(tag_name); DCHECK(ShouldCreateCustomElement(tag_name) || should_create_builtin); HTMLElement* element; if (V0CustomElement::IsValidName(tag_name.LocalName()) && document.RegistrationContext()) { Element* v0element = document.RegistrationContext()->CreateCustomTagElement( document, tag_name); SECURITY_DCHECK(v0element->IsHTMLElement()); element = ToHTMLElement(v0element); } else if (should_create_builtin) { element = HTMLElementFactory::createHTMLElement( tag_name.LocalName(), document, kCreatedByCreateElement); } else { element = HTMLElement::Create(tag_name, document); } element->SetCustomElementState(CustomElementState::kUndefined); return element; } HTMLElement* CustomElement::CreateFailedElement(Document& document, const QualifiedName& tag_name) { DCHECK(ShouldCreateCustomElement(tag_name)); // "create an element for a token": // https://html.spec.whatwg.org/multipage/syntax.html#create-an-element-for-the-token // 7. If this step throws an exception, let element be instead a new element // that implements HTMLUnknownElement, with no attributes, namespace set to // given namespace, namespace prefix set to null, custom element state set // to "failed", and node document set to document. HTMLElement* element = HTMLUnknownElement::Create(tag_name, document); element->SetCustomElementState(CustomElementState::kFailed); return element; } void CustomElement::Enqueue(Element* element, CustomElementReaction* reaction) { // To enqueue an element on the appropriate element queue // https://html.spec.whatwg.org/multipage/scripting.html#enqueue-an-element-on-the-appropriate-element-queue // If the custom element reactions stack is not empty, then // Add element to the current element queue. if (CEReactionsScope* current = CEReactionsScope::Current()) { current->EnqueueToCurrentQueue(element, reaction); return; } // If the custom element reactions stack is empty, then // Add element to the backup element queue. CustomElementReactionStack::Current().EnqueueToBackupQueue(element, reaction); } void CustomElement::EnqueueConnectedCallback(Element* element) { CustomElementDefinition* definition = DefinitionForElementWithoutCheck(*element); if (definition->HasConnectedCallback()) definition->EnqueueConnectedCallback(element); } void CustomElement::EnqueueDisconnectedCallback(Element* element) { CustomElementDefinition* definition = DefinitionForElementWithoutCheck(*element); if (definition->HasDisconnectedCallback()) definition->EnqueueDisconnectedCallback(element); } void CustomElement::EnqueueAdoptedCallback(Element* element, Document* old_owner, Document* new_owner) { DCHECK_EQ(element->GetCustomElementState(), CustomElementState::kCustom); CustomElementDefinition* definition = DefinitionForElementWithoutCheck(*element); if (definition->HasAdoptedCallback()) definition->EnqueueAdoptedCallback(element, old_owner, new_owner); } void CustomElement::EnqueueAttributeChangedCallback( Element* element, const QualifiedName& name, const AtomicString& old_value, const AtomicString& new_value) { CustomElementDefinition* definition = DefinitionForElementWithoutCheck(*element); if (definition->HasAttributeChangedCallback(name)) definition->EnqueueAttributeChangedCallback(element, name, old_value, new_value); } void CustomElement::TryToUpgrade(Element* element) { // Try to upgrade an element // https://html.spec.whatwg.org/multipage/scripting.html#concept-try-upgrade DCHECK_EQ(element->GetCustomElementState(), CustomElementState::kUndefined); CustomElementRegistry* registry = CustomElement::Registry(*element); if (!registry) return; if (CustomElementDefinition* definition = registry->DefinitionFor( CustomElementDescriptor(element->localName(), element->localName()))) definition->EnqueueUpgradeReaction(element); else registry->AddCandidate(element); } } // namespace blink
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com