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 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
53b2c42d486abb9bd608d3d2b63f6bcca4d8532a
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/chrome/browser/navigation_predictor/anchor_element_preloader.cc
|
7c5462136f4b33b5f08235427c9aa25c487eda48
|
[
"BSD-3-Clause"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C++
| false
| false
| 6,059
|
cc
|
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/navigation_predictor/anchor_element_preloader.h"
#include "base/functional/callback.h"
#include "base/metrics/histogram_functions.h"
#include "chrome/browser/predictors/loading_predictor.h"
#include "chrome/browser/predictors/loading_predictor_factory.h"
#include "chrome/browser/prefetch/prefetch_prefs.h"
#include "chrome/browser/preloading/chrome_preloading.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/preloading.h"
#include "content/public/browser/preloading_data.h"
#include "content/public/browser/web_contents.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "third_party/blink/public/common/features.h"
#include "ui/base/page_transition_types.h"
#include "url/scheme_host_port.h"
namespace {
bool is_match_for_preconnect(const url::SchemeHostPort& preconnected_origin,
const GURL& visited_url) {
return preconnected_origin == url::SchemeHostPort(visited_url);
}
} // anonymous namespace
const char kPreloadingAnchorElementPreloaderPreloadingTriggered[] =
"Preloading.AnchorElementPreloader.PreloadingTriggered";
content::PreloadingFailureReason ToFailureReason(
AnchorPreloadingFailureReason reason) {
return static_cast<content::PreloadingFailureReason>(reason);
}
AnchorElementPreloader::~AnchorElementPreloader() = default;
AnchorElementPreloader::AnchorElementPreloader(
content::RenderFrameHost& render_frame_host)
: render_frame_host_(render_frame_host) {
content::PreloadingData* preloading_data =
content::PreloadingData::GetOrCreateForWebContents(
content::WebContents::FromRenderFrameHost(&*render_frame_host_));
preloading_data->SetIsNavigationInDomainCallback(
chrome_preloading_predictor::kPointerDownOnAnchor,
base::BindRepeating(
[](content::NavigationHandle* navigation_handle) -> bool {
return ui::PageTransitionCoreTypeIs(
navigation_handle->GetPageTransition(),
ui::PageTransition::PAGE_TRANSITION_LINK) &&
ui::PageTransitionIsNewNavigation(
navigation_handle->GetPageTransition());
}));
}
void AnchorElementPreloader::MaybePreconnect(const GURL& target) {
content::PreloadingData* preloading_data =
content::PreloadingData::GetOrCreateForWebContents(
content::WebContents::FromRenderFrameHost(&*render_frame_host_));
url::SchemeHostPort scheme_host_port(target);
content::PreloadingURLMatchCallback match_callback =
base::BindRepeating(is_match_for_preconnect, scheme_host_port);
// For now we add a prediction with a confidence of 100. In the future we will
// likely compute the confidence by looking at different factors (e.g. anchor
// element dimensions, last time since scroll, etc.).
preloading_data->AddPreloadingPrediction(
chrome_preloading_predictor::kPointerDownOnAnchor,
/*confidence=*/100, match_callback);
content::PreloadingAttempt* attempt = preloading_data->AddPreloadingAttempt(
chrome_preloading_predictor::kPointerDownOnAnchor,
content::PreloadingType::kPreconnect, match_callback);
if (content::PreloadingEligibility eligibility =
prefetch::IsSomePreloadingEnabled(
*Profile::FromBrowserContext(
render_frame_host_->GetBrowserContext())
->GetPrefs());
eligibility != content::PreloadingEligibility::kEligible) {
attempt->SetEligibility(eligibility);
return;
}
auto* loading_predictor = predictors::LoadingPredictorFactory::GetForProfile(
Profile::FromBrowserContext(render_frame_host_->GetBrowserContext()));
if (!loading_predictor) {
attempt->SetEligibility(ToPreloadingEligibility(
ChromePreloadingEligibility::kUnableToGetLoadingPredictor));
return;
}
attempt->SetEligibility(content::PreloadingEligibility::kEligible);
RecordUmaPreloadedTriggered(AnchorElementPreloaderType::kPreconnect);
// In addition to the globally-controlled preloading config, check for the
// feature-specific holdback. We disable the feature if the user is in either
// of those holdbacks.
if (base::GetFieldTrialParamByFeatureAsBool(
blink::features::kAnchorElementInteraction, "preconnect_holdback",
false)) {
attempt->SetHoldbackStatus(content::PreloadingHoldbackStatus::kHoldback);
}
if (attempt->ShouldHoldback()) {
return;
}
if (preconnected_targets_.find(scheme_host_port) !=
preconnected_targets_.end()) {
// We've already preconnected to that origin.
attempt->SetTriggeringOutcome(
content::PreloadingTriggeringOutcome::kDuplicate);
return;
}
int max_preloading_attempts = base::GetFieldTrialParamByFeatureAsInt(
blink::features::kAnchorElementInteraction, "max_preloading_attempts",
-1);
if (max_preloading_attempts >= 0 &&
preconnected_targets_.size() >=
static_cast<size_t>(max_preloading_attempts)) {
attempt->SetFailureReason(
ToFailureReason(AnchorPreloadingFailureReason::kLimitExceeded));
return;
}
preconnected_targets_.insert(scheme_host_port);
attempt->SetTriggeringOutcome(
content::PreloadingTriggeringOutcome::kTriggeredButOutcomeUnknown);
net::SchemefulSite schemeful_site(target);
auto network_anonymization_key =
net::NetworkAnonymizationKey::CreateSameSite(schemeful_site);
loading_predictor->PreconnectURLIfAllowed(target, /*allow_credentials=*/true,
network_anonymization_key);
}
void AnchorElementPreloader::RecordUmaPreloadedTriggered(
AnchorElementPreloaderType preload) {
base::UmaHistogramEnumeration(
kPreloadingAnchorElementPreloaderPreloadingTriggered, preload);
}
|
[
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] |
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
|
53e185946ccce2f6de59f0adcf87542e8032f953
|
a94f689196fc0a40bbd97052ec5edb9668f4f250
|
/RX/other/air_compressor/air_compressor.ino
|
c8658f442d2c4bb5f4a114e71c689dff6a5bc6bc
|
[] |
no_license
|
troywiipongwii/Open-Source-RKS
|
59c0ed2311c75a7bc384557522d4edee1f085562
|
29c2022ef7864ac68b49cd0d1d837eb2d43ff816
|
refs/heads/master
| 2020-05-22T00:25:27.938863
| 2019-04-08T06:12:47
| 2019-04-08T06:12:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 27
|
ino
|
#include "air_compressor.h"
|
[
"fryefryefrye@foxmail.com"
] |
fryefryefrye@foxmail.com
|
a48022dab032488cbfd879d16e0d3e715f91c4c4
|
6ad8a1bd5ba4bd8d499fa95987e2a32f3811f841
|
/CPP_Problems/Skiena Programming Challenges/3n+1 Problem.cpp
|
4f938001bc3c23cf8da0e6eb9ead0fbe36cb5057
|
[] |
no_license
|
Huddie/CPP_Problems
|
1ef1c71c2346034f196d5e086b56a91a28df39a9
|
8028ff8c68d154f39de30462dce7f67baec3468c
|
refs/heads/master
| 2021-09-02T12:27:47.307104
| 2018-01-02T16:22:42
| 2018-01-02T16:22:42
| 105,211,946
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 676
|
cpp
|
#include <iostream>
int main() {
unsigned int inNum, start = 1, end, count, highCount;
while(std::cin >> start) {
highCount = 0;
std::cin >> end;
std::cout << start;
std::cout << " " << end;
for(; start <= end; start += 1) {
unsigned int cycle = start;
count = 0;
while (cycle != 1) {
if (cycle % 2 == 0) /* is even */
cycle /= 2;
else /* odd */
cycle = (3 * cycle) + 1;
count += 1;
// q.enque(cycle);
}
if(count > highCount) highCount = count;
}
// Memo[q.front()] = q.size()
// q.deque
std::cout << " " << ++highCount << std::endl;
}
return 0;
}
|
[
"easports96@gmail.com"
] |
easports96@gmail.com
|
f2e371e72f0d1de2190b694c2ca29a97e50e462a
|
3f3a42f429f8bcd769644148b24c3b0e6e2589ed
|
/GameProjectCopy/GameEngine/GameApp/Light/vecmap.h
|
e919de9e51e3c12771e3801eaf82efb2793c14f3
|
[] |
no_license
|
DanielNeander/my-3d-engine
|
d10ad3e57a205f6148357f47467b550c7e0e0f33
|
7f0babbfdf0b719ea4b114a89997d3e52bcb2b6c
|
refs/heads/master
| 2021-01-10T17:58:25.691360
| 2013-04-24T07:37:31
| 2013-04-24T07:37:31
| 53,236,587
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,452
|
h
|
/******************************************************************************
"Practical Methods for Precomputed Radiance Transfer Using Spherical Harmonics"
Jerome Ko - submatrix@gmail.com
Manchor Ko - man961.great@gmail.com
Matthias Zwicker - mzwicker@cs.ucsd.edu
******************************************************************************/
#ifndef VECMAP_H
#define VECMAP_H
#include <malloc.h> //_alloca
#include <map>
namespace GEOM
{
/*!
-- VecMap: maintains a map of unique objects
*/
template <class T>
class VecMap {
public:
VecMap() : m_next(0) {}
~VecMap() {}
void Reset() { m_map.clear(); m_next = 0; }
size_t Size() const { return m_map.size(); }
/// inserts if 'v' is new. Return index for the entry.
int Add( const T& v ) {
int index;
Map::const_iterator ubegin = m_map.find( v );
if (ubegin != m_map.end()) {
index = ubegin->second;
}
else {
index = Insert(v);
}
return index;
}
/// insert a new entry:
int Insert( const T& v ) {
int index = m_next++;
m_map.insert( std::make_pair(v, index) );
return index;
}
/// locates
int FindIndex( const T& v ) const {
Map::const_iterator ubegin = m_map.find( v );
if (ubegin != m_map.end()) {
return ubegin->second;
}
return -1;
}
public:
typedef std::map<T,int> Map;
Map m_map;
int m_next;
}; //end VecMap
};
#endif
|
[
"Sangyong79@gmail.com"
] |
Sangyong79@gmail.com
|
95b91db351b2d8c31022ccbdc0edd10a840ce39a
|
5671c626ee367c9aacb909cd76a06d2fadf941e2
|
/frameworks/core/accessibility/accessibility_utils.cpp
|
8eca508655ee0ca7b5d6a12e104ef62d3d0c33bc
|
[
"Apache-2.0"
] |
permissive
|
openharmony/ace_ace_engine
|
fa3f2abad9866bbb329524fb039fa89dd9517592
|
c9be21d0e8cb9662d5f4f93184fdfdb538c9d4e1
|
refs/heads/master
| 2022-07-21T19:32:59.377634
| 2022-05-06T11:18:20
| 2022-05-06T11:18:20
| 400,083,641
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,607
|
cpp
|
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 "core/accessibility/accessibility_utils.h"
namespace OHOS::Ace {
const char ACCESSIBILITY_TAG_DIV[] = "div";
const char ACCESSIBILITY_TAG_CALENDAR[] = "calendar";
const char ACCESSIBILITY_TAG_TEXT[] = "text";
const char ACCESSIBILITY_TAG_PICKER[] = "picker";
const char ACCESSIBILITY_TAG_OPTION[] = "option";
const char ACCESSIBILITY_TAG_POPUP[] = "popup";
const char ACCESSIBILITY_TAG_PROGRESS[] = "progress";
const char ACCESSIBILITY_TAG_SELECT[] = "select";
const char ACCESSIBILITY_TAG_MENU[] = "menu";
const char ACCESSIBILITY_TAG_SLIDER[] = "slider";
const char ACCESSIBILITY_TAG_SPAN[] = "span";
const char ACCESSIBILITY_TAG_STACK[] = "stack";
const char ACCESSIBILITY_TAG_SWIPER[] = "swiper";
const char ACCESSIBILITY_TAG_SWITCH[] = "switch";
const char ACCESSIBILITY_TAG_TABS[] = "tabs";
const char ACCESSIBILITY_TAG_TAB_BAR[] = "tab-bar";
const char ACCESSIBILITY_TAG_TAB_CONTENT[] = "tab-content";
const char ACCESSIBILITY_TAG_REFRESH[] = "refresh";
const char ACCESSIBILITY_TAG_IMAGE[] = "image";
const char ACCESSIBILITY_TAG_LIST[] = "list";
const char ACCESSIBILITY_TAG_LIST_ITEM[] = "list-item";
const char ACCESSIBILITY_TAG_LIST_ITEM_GROUP[] = "list-item-group";
const char ACCESSIBILITY_TAG_VIDEO[] = "video";
const char ACCESSIBILITY_TAG_RATING[] = "rating";
const char ACCESSIBILITY_TAG_MARQUEE[] = "marquee";
const char ACCESSIBILITY_TAG_NAVIGATION_BAR[] = "navigation-bar";
const char ACCESSIBILITY_TAG_NAVIGATION_MENU[] = "navigation-menu";
const char ACCESSIBILITY_TAG_TEXTAREA[] = "textarea";
const char ACCESSIBILITY_TAG_INPUT[] = "input";
const char ACCESSIBILITY_TAG_LABEL[] = "label";
const char ACCESSIBILITY_TAG_DIVIDER[] = "divider";
const char ACCESSIBILITY_TAG_CANVAS[] = "canvas";
const char ACCESSIBILITY_TAG_BUTTON[] = "button";
const char ACCESSIBILITY_TAG_CHART[] = "chart";
const char ACCESSIBILITY_TAG_CLOCK[] = "clock";
const char ACCESSIBILITY_TAG_DIALOG[] = "dialog";
const char ACCESSIBILITY_TAG_SEARCH[] = "search";
} // namespace OHOS::Ace
|
[
"mamingshuai1@huawei.com"
] |
mamingshuai1@huawei.com
|
3ac26185d4691476d721a666ea395d12887e9e47
|
ad57b429464a9571d98b9ff74e31a1cbf13c5a42
|
/avencoder/avencoder.cpp
|
780c1958a0290eb0edc852e88ff911f40a61c241
|
[] |
no_license
|
github188/avencoder_nvidia
|
9f4c236dd144b5877d18459636f2bf95d98a15e3
|
ff853db58e1f8295a57fc10faa9b75250c61672f
|
refs/heads/master
| 2020-03-19T07:19:46.785894
| 2015-09-22T09:00:51
| 2015-09-22T09:00:51
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 18,181
|
cpp
|
#include "videosource.h"
#include "videoencoder.h"
#include "audioencoder.h"
#include "audiosource.h"
#include "avmuxer.h"
#include "tssmooth.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <pthread.h>
#include <getopt.h>
#include <errno.h>
#define version_str "1.0.00.15"
const int delaytimeus = 40;
int first_frame = 1;
audio_source_t* p_audio_source = NULL;
video_source_t* p_video_source = NULL;
audio_encoder_t* p_audio_encoder = NULL;
video_encoder_t* p_video_encoder = NULL;
ts_muxer_t* p_avmuxer = NULL;
ts_smooth_t* p_tssmooth = NULL;
const int n_audio_source_sample_size = 1*1024*1024;
const int n_video_source_sample_size = 5*1024*1024;
char *p_audio_source_sample = NULL;
char *p_video_source_sample = NULL;
int n_audio_source_sample = 0;
int n_video_source_sample = 0;
const int n_audio_encode_sample_size = 1*1024*1024;
const int n_video_encode_sample_size = 5*1024*1024;
char *p_audio_encode_sample = NULL;
char *p_video_encode_sample = NULL;
int n_audio_encode_sample = 0;
int n_video_encode_sample = 0;
int write_video_frames();
int write_audio_frames();
void* statistics_process(void *param);
int m_index = 0;
int width = 1280;
int height = 720;
int encode_bitrate = 4*1024*1024;
int smooth_bitrate = 12*1024*1024;
char destip[32] = "127.0.0.1";
int destport = 14000;
char destip_record[32] = "127.0.0.1";
int destport_record = 14000;
int pmt_pid = 0x1000;
int service_id = 0x0001;
int video_pid = 0x100;
int audio_pid = 0x101;
int gopsize_min = 5;
int gopsize_max = 100;
int fps = 25;
char logfile[256] = "avencoder.log";
int main(int argc,char **argv)
{
const char *short_options = "i:w:h:b:d:p:s:g:f:l:?";
struct option long_options[] = {
{"help", no_argument, NULL, '?'},
{"index", required_argument, NULL, 'i'},
{"width", required_argument, NULL, 'w'},
{"height", required_argument, NULL, 'h'},
{"bitrate", required_argument, NULL, 'b'},
{"sbitrate",required_argument, NULL, 's'},
{"destaddr",required_argument, NULL, 'd'},
{"pids", required_argument, NULL, 'p'},
{"gopsize", required_argument, NULL, 'g'},
{"fps", required_argument, NULL, 'f'},
{"logfile", required_argument, NULL, 'l'},
{NULL, 0, NULL, 0},
};
int c = -1;
bool has_index = false;
bool has_destaddr = false;
bool has_ebitrate = false;
bool has_sbitrate = false;
while(1)
{
c = getopt_long(argc, argv, short_options, long_options, NULL);
if(c == -1)
break;
switch(c)
{
case '?':
printf("Usage:%s [options] index destaddr ....\n",argv[0]);
printf("avencoder version %s\n",version_str);
printf("-? --help Display this usage information.\n");
printf("-i --index Set the index.\n");
printf("-w --width Set the width.\n");
printf("-h --height Set the height.\n");
printf("-b --bitrate Set the encoder bitrate .\n");
printf("-s --sbitrate Set the smooth bitrate.\n");
printf("-d --destaddr Set the dest addr (ip:port).\n");
printf("-p --pids Set the service_id pmt_pid video_pid audio_pid (pmt_pid:service_id:video_pid:audio_pid).\n");
printf("-g --gopsize Set the video encode gopsize (gopsize_min:gopsize_max).\n");
printf("-l --logfile Set the log file path.\n");
printf("Example: %s --index 0 --width 1280 --height 720 --bitrate 4000000 --pids 1024:1:64:65 --gopsize 5:100 --destaddr 192.168.60.248:14000.\n",argv[0]);
printf("Example: %s -i 0 -w 1280 -h 720 -b 4000000 -p 1024:1:64:65 -g 5:100 -d 192.168.60.248:14000.\n",argv[0]);
return -1;
case 'i':
m_index = atoi(optarg);
has_index = true;
break;
case 'w':
width = atoi(optarg);
break;
case 'h':
height = atoi(optarg);
break;
case 'b':
encode_bitrate = atoi(optarg);
has_ebitrate = true;
break;
case 's':
smooth_bitrate = atoi(optarg);
has_sbitrate = true;
break;
case 'd':
if(sscanf(optarg,"%[^:]:%d",destip,&destport) != 2)
{
fprintf(stderr ,"avencoder: error destip:destport.%s.\n",optarg);
return -2;
}
strncpy(destip_record,destip,sizeof(destip_record));
destport_record = destport;
has_destaddr = true;
break;
case 'p':
if(sscanf(optarg,"%d:%d:%d:%d",&pmt_pid,&service_id,&video_pid,&audio_pid) != 4)
{
fprintf(stderr ,"avencoder: error pmt_pid:service_id:video_pid:audio_pid.%s.\n",optarg);
return -3;
}
break;
case 'g':
if(sscanf(optarg,"%d:%d",&gopsize_min,&gopsize_max) != 2)
{
gopsize_min = gopsize_max = atoi(optarg);
}
break;
case 'f':
fps = atoi(optarg);
break;
case 'l':
memset(logfile,0,sizeof(logfile));
strncpy(logfile,optarg,sizeof(logfile));
break;
}
}
if(has_index == false || has_destaddr == false)
{
fprintf(stderr ,"avencoder: index and destaddr is must,not empty.\n");
return -3;
}
if(has_ebitrate == true && has_sbitrate == false)
smooth_bitrate = encode_bitrate*3;
else if(has_ebitrate == false && has_sbitrate == true)
encode_bitrate = smooth_bitrate/3;
if(encode_bitrate < 0)
encode_bitrate = 4*1024*1024;
//TODO 检查各个参数的有效性
printf("avencoder version %s\n",version_str);
printf("++++++index=%d|width=%d|height=%d|smooth_bitrate=%d|encode_bitrate=%d|destip=%s|destport=%d++++++\n",m_index,width,height,smooth_bitrate,encode_bitrate,destip,destport);
printf("++++++pmt_pid=%d|service_id=%d|video_pid=%d|audio_pid=%d|gopsize_min=%d|gopsize_max=%d|logfile=%s++++++\n",pmt_pid,service_id,video_pid,audio_pid,gopsize_min,gopsize_max,logfile);
InputParams_audiosource audio_source_params;
InputParams_videosource video_source_params;
InputParams_videoencoder video_encoder_params;
InputParams_avmuxer avmuxer_params;
InputParams_tssmooth tssmooth_params;
audio_source_params.index = m_index;
p_audio_source = init_audio_source(&audio_source_params);
if(p_audio_source == NULL)
{
fprintf(stderr ,"avencoder: init_audio_source fail..\n");
return -1;
}
video_source_params.index = m_index;
video_source_params.width = width;
video_source_params.height = height;
p_video_source = init_video_source(&video_source_params);
if(p_video_source == NULL)
{
fprintf(stderr ,"avencoder: init_video_source fail..\n");
return -1;
}
p_audio_encoder = init_audio_encoder();
if(p_audio_encoder == NULL)
{
fprintf(stderr ,"avencoder: init_audio_encoder fail..\n");
return -1;
}
video_encoder_params.width = width;
video_encoder_params.height = height;
video_encoder_params.gopsize_min = gopsize_min;
video_encoder_params.gopsize_max = gopsize_max;
video_encoder_params.bitrate = encode_bitrate;
video_encoder_params.fps = fps;
p_video_encoder = init_video_encoder(&video_encoder_params);
if(p_video_encoder == NULL)
{
fprintf(stderr ,"avencoder: init_video_encoder fail..\n");
return -1;
}
#if 0
if(smooth_bitrate > 0)
{
memset(&tssmooth_params,0,sizeof(tssmooth_params));
tssmooth_params.index = m_index;
tssmooth_params.listen_udp_port = 0;
strcpy(tssmooth_params.dst_udp_ip,destip);
tssmooth_params.dst_udp_port = destport;
tssmooth_params.bit_rate = smooth_bitrate;
tssmooth_params.buffer_max_size = 10*1024*1024;
p_tssmooth = init_tssmooth(&tssmooth_params);
if(p_tssmooth == NULL)
{
fprintf(stderr ,"avencoder: init_smooth fail..\n");
return -1;
}
strcpy(destip,tssmooth_params.listen_udp_ip);
destport = tssmooth_params.listen_udp_port;
printf("++++++now dest addr is modify destip=%s|destport=%d++++++\n",destip,destport);
}
#endif
avmuxer_params.codecID = KY_CODEC_ID_H264;
avmuxer_params.nWidth = width;
avmuxer_params.nHeight = height;
avmuxer_params.nBitRate = encode_bitrate;
avmuxer_params.nPeakBitRate = smooth_bitrate;
avmuxer_params.nSamplerate = 48000;
avmuxer_params.nFramerate = fps;
snprintf(avmuxer_params.monitorName,sizeof(avmuxer_params.monitorName),"%d.monitor",m_index);
snprintf(avmuxer_params.appName,sizeof(avmuxer_params.appName),"%s",argv[0]);
strcpy(avmuxer_params.destip,destip);
avmuxer_params.destport = destport;
avmuxer_params.index = m_index;
avmuxer_params.pmt_pid = pmt_pid;
avmuxer_params.service_id = service_id;
avmuxer_params.video_pid = video_pid;
avmuxer_params.audio_pid = audio_pid;
p_avmuxer = init_ts_muxer(&avmuxer_params);
if(p_avmuxer == NULL)
{
fprintf(stderr ,"avencoder: init_ts_muxer fail..\n");
return -1;
}
p_audio_source_sample = (char *)malloc(n_audio_source_sample_size);
p_video_source_sample = (char *)malloc(n_video_source_sample_size);
if(p_audio_source_sample == NULL || p_video_source_sample == NULL)
{
fprintf(stderr ,"avencoder: malloc fail..\n");
return -2;
}
p_audio_encode_sample = (char *)malloc(n_audio_encode_sample_size);
p_video_encode_sample = (char *)malloc(n_video_encode_sample_size);
if(p_audio_encode_sample == NULL || p_video_encode_sample == NULL)
{
fprintf(stderr ,"avencoder: malloc fail..\n");
return -2;
}
pthread_t pthread;
int ret = pthread_create(&pthread, NULL, statistics_process, NULL);
if(ret != 0)
{
printf("avencoder: pthread_create fail!...\n");
return -3;
}
double videopts = 0.0;
double audiopts = 0.0;
struct timeval tv;
long start_time_us,end_time_us;
gettimeofday(&tv,NULL);
start_time_us = end_time_us = tv.tv_sec*1000 + tv.tv_usec/1000;
while(1)
{
gettimeofday(&tv,NULL);
start_time_us = tv.tv_sec*1000 + tv.tv_usec/1000;
write_video_frames();
video_pts(p_avmuxer,&videopts);
audio_pts(p_avmuxer,&audiopts);
//printf("++++++++++videopts = [%lf] audiopts = [%lf]+++++++++\n",videopts,audiopts);
while(audiopts < videopts)
{
write_audio_frames();
video_pts(p_avmuxer,&videopts);
audio_pts(p_avmuxer,&audiopts);
//printf("----------videopts = [%lf] audiopts = [%lf]---------\n",videopts,audiopts);
}
gettimeofday(&tv,NULL);
end_time_us = tv.tv_sec*1000 + tv.tv_usec/1000;
//if(end_time_us - start_time_us >= 40)
// printf("1++++++++++start_time_us = [%ld] end_time_us = [%ld]+++++diff=%ld++++\n",start_time_us,end_time_us,end_time_us - start_time_us);
if(end_time_us - start_time_us < delaytimeus)
usleep((delaytimeus-(end_time_us - start_time_us))*1000);
}
uninit_audio_source(p_audio_source);
uninit_video_source(p_video_source);
uninit_audio_encoder(p_audio_encoder);
uninit_video_encoder(p_video_encoder);
uninit_ts_muxer(p_avmuxer);
if(smooth_bitrate > 0 && p_tssmooth)
uninit_tssmooth(p_tssmooth);
return 0;
}
int write_video_frames()
{
int ret = -1;
int x = 0;
int y = 0;
int w = 0;
int h = 0;
//获取视频源
n_video_source_sample = n_video_source_sample_size;
if(first_frame == 0)
{
ret = get_video_sample_inc(p_video_source,p_video_source_sample,&n_video_source_sample,&x,&y,&w,&h);
if(ret < 0)
{
fprintf(stderr ,"avencoder: get_video_sample_inc fail..ret=%d\n",ret);
return -1;
}
}
else //first_frame
{
ret = get_video_sample_all(p_video_source,p_video_source_sample,&n_video_source_sample,&x,&y,&w,&h);
if(ret < 0)
{
fprintf(stderr ,"avencoder: get_video_sample_all fail..ret=%d\n",ret);
return -1;
}
first_frame = 0;
}
/*
struct timeval tv;
long time_us;
gettimeofday(&tv,NULL);
time_us = tv.tv_sec*1000 + tv.tv_usec/1000;
printf("time_us=%ld x=%d,y=%d,w=%d,h=%d, n_video_source_sample = %d\n",time_us,x,y,w,h,n_video_source_sample);
*/
//printf("n_video_source_sample = %d\n",n_video_source_sample);
//编码视频
n_video_encode_sample = n_video_encode_sample_size;
ret = encode_video_sample_inc(p_video_encoder,p_video_source_sample,n_video_source_sample,p_video_encode_sample,&n_video_encode_sample,x,y,w,h);
if(ret < 0)
{
fprintf(stderr ,"avencoder: encode_video_sample fail..\n");
return -2;
}
//printf("n_video_encode_sample = %d\n",n_video_encode_sample);
//写视频
ret = write_video_frame(p_avmuxer,p_video_encode_sample,n_video_encode_sample);
if(ret < 0)
{
fprintf(stderr ,"avencoder: write_video_frame fail..\n");
return -3;
}
return 0;
}
int write_audio_frames()
{
int ret = 0;
n_audio_source_sample = n_audio_source_sample_size;
ret = get_audio_sample(p_audio_source,p_audio_source_sample,&n_audio_source_sample);
if(ret < 0)
{
fprintf(stderr ,"avencoder: get_audio_sample fail..\n");
return -1;
}
else if(ret == 0)
{
//fprintf(stderr ,"avencoder: get_audio_sample no audio sample..\n");
n_audio_source_sample = 4608;
memset(p_audio_source_sample,0,n_audio_source_sample);
}
//else if(ret > 0)
// fprintf(stderr ,"avencoder: get_audio_sample yes audio sample..\n");
//printf("n_audio_source_sample = %d\n",n_audio_source_sample);
n_audio_encode_sample = n_audio_encode_sample_size;
ret = encode_audio_sample(p_audio_encoder,p_audio_source_sample,n_audio_source_sample,p_audio_encode_sample,&n_audio_encode_sample);
if(ret < 0)
{
fprintf(stderr ,"avencoder: encode_audio_sample fail..\n");
return -2;
}
//printf("n_audio_encode_sample = %d\n",n_audio_encode_sample);
ret = write_audio_frame(p_avmuxer,p_audio_encode_sample,n_audio_encode_sample);
if(ret < 0)
{
fprintf(stderr ,"avencoder: write_audio_frame fail..\n");
return -3;
}
return 0;
}
void* statistics_process(void *param)
{
unsigned long read_send_bytes1 = 0;
unsigned long read_count_fps1 = 0;
unsigned long read_send_bytes2 = 0;
unsigned long read_count_fps2 = 0;
unsigned long read_send_bytes_diff = 0;
unsigned long read_count_fps_diff = 0;
unsigned long mask_long = (unsigned long)(-1);
FILE *fp = NULL;
char filename[256];
snprintf(filename,sizeof(filename),"/tmp/avencoder.%d",m_index);
char tmp_buffer[1024];
while(1)
{
// if(smooth_bitrate > 0 && p_tssmooth)
// read_send_bytes1 = get_real_send_bytes(p_tssmooth);
if(p_avmuxer)
read_send_bytes1 = get_bbcvudp_real_send_bytes(p_avmuxer);
read_count_fps1 = get_real_count_fps(p_video_encoder);
usleep(1000*1000);
// if(smooth_bitrate > 0 && p_tssmooth)
// read_send_bytes2 = get_real_send_bytes(p_tssmooth);
if(p_avmuxer)
read_send_bytes2 = get_bbcvudp_real_send_bytes(p_avmuxer);
read_count_fps2 = get_real_count_fps(p_video_encoder);
if(read_send_bytes2 < read_send_bytes1)
read_send_bytes_diff = mask_long - read_send_bytes1 + read_send_bytes2;
else
read_send_bytes_diff = read_send_bytes2 - read_send_bytes1;
if(read_count_fps2 < read_count_fps1)
read_count_fps_diff = mask_long - read_count_fps1 + read_count_fps2;
else
read_count_fps_diff = read_count_fps2 - read_count_fps1;
//printf("read_send_bytes_rate = %lu read_count_fps = %lu\n",read_send_bytes_diff*8,read_count_fps_diff);
fp = fopen(filename,"w");
if(fp == NULL)
{
fprintf(stderr ,"avencoder: fopen filename %s fail.errno=%d.\n",filename,errno);
continue;
}
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"version=%s\n",version_str);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"index=%d\n",m_index);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"destaddr=%s:%d\n",destip_record,destport_record);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"destaddr_local=%s:%d\n",destip,destport);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"realbitrate=%lu\n",read_send_bytes_diff*8);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"realfps=%lu\n",read_count_fps_diff);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"encode_bitrate=%d\n",encode_bitrate);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"smooth_bitrate=%d\n",smooth_bitrate);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"fps=%d\n",fps);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"pmt_pid=%d\n",pmt_pid);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"service_id=%d\n",service_id);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"video_pid=%d\n",video_pid);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"audio_pid=%d\n",audio_pid);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"gopsize=%d:%d\n",gopsize_min,gopsize_max);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"width=%d\n",width);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
memset(tmp_buffer,0,sizeof(tmp_buffer));
snprintf(tmp_buffer,sizeof(tmp_buffer),"height=%d\n",height);
fwrite(tmp_buffer,strlen(tmp_buffer),1,fp);
fflush(fp);
fclose(fp);
}
}
|
[
"yydgame@163.com"
] |
yydgame@163.com
|
98e8139f5f6d1caf0efcd6a5421f1bbca5cdcfca
|
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
|
/cpp/A/C/D/B/A/AACDBA.h
|
17befe74563ec6dff62d1da082f7435138dc50f6
|
[] |
no_license
|
devsisters/2021-NDC-ICECREAM
|
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
|
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
|
refs/heads/master
| 2023-03-19T06:29:03.216461
| 2021-03-10T02:53:14
| 2021-03-10T02:53:14
| 341,872,233
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 67
|
h
|
#ifndef AACDBA_H
namespace AACDBA {
std::string run();
}
#endif
|
[
"nakhyun@devsisters.com"
] |
nakhyun@devsisters.com
|
0c596827c12f869019606e13b638c470699c7165
|
f20cc2b9207e71c21ea11141d941249913459c37
|
/include/nodoGenericImpl.cpp
|
f4acae48a2bb0b4e1582845f2598d0850c786c42
|
[] |
no_license
|
Dabit98/IC-Practice2
|
e8aaa7752115127be2640ffe0ba782bc6cd8ff9a
|
9d90a315b2cfc076bffe7aff2ed8ac95f96497ac
|
refs/heads/master
| 2020-07-31T23:59:27.529762
| 2019-10-23T19:30:14
| 2019-10-23T19:30:14
| 210,793,895
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 850
|
cpp
|
#include <iostream>
//Funciones de manipulacion
//Constructor nodo hijo
template <typename T>
Nodo<T>::Nodo(Nodo* padre, T dato) : Nodo<T>::Nodo(dato) {
this->padre = padre;
}
//Constructor nodo padre
template <typename T>
Nodo<T>::Nodo(T dato) {
this->padre = nullptr;
this->dato = dato;
}
//Creador de hijos
template <typename T>
Nodo<T>* Nodo<T>::crearHijo(T dato) {
Nodo<T>* hijo = new Nodo(this, dato);
hijos.push_back(hijo);
return hijo;
}
//Eliminadores de hijos
template <typename T>
void Nodo<T>::eliminarHijo(int hijo) {
Nodo* borrar = hijos[hijo];
hijos.erase(hijos.begin()+hijo);
delete borrar;
}
template <typename T>
void Nodo<T>::eliminarHijos() {
while(!hijos.empty()){
delete hijos.back();
hijos.pop_back();
}
}
//Destructor recursivo
template <typename T>
Nodo<T>::~Nodo() {
eliminarHijos();
}
|
[
"npj6@alu.ua.es"
] |
npj6@alu.ua.es
|
c29752ffa9200a51a604bdf5753aac1d3654afcf
|
57f1b61b9f71ebb642f9c55979788e18b490e19e
|
/gtr2/core-proxy/AuditReg.h
|
0b2b1c7295875df125b422b866ff8a30cd02593b
|
[] |
no_license
|
cash2one/5173.com
|
22ba887b5b620ed5a1ec8858de738593284ff2b3
|
b5b3b55c93e5e12076ebe01f8a439b464a11c32f
|
refs/heads/master
| 2021-01-12T16:51:01.592506
| 2016-04-08T06:46:05
| 2016-04-08T06:46:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 686
|
h
|
#pragma once
#include <wx\regex.h>
#include <map>
#include <list>
#include <vector>
#include <string>
#include <Windows.h>
using namespace std;
struct RegItemData
{
wstring ItemPropertyName;
wstring ItemAttrValue;
};
class AuditReg
{
map<wxString, wxRegEx*> _regItemAttr;
vector<wxRegEx*> _regItemType;
public:
AuditReg(void);
~AuditReg(void);
wstring GetItemType( list<string>& tip );
void GetItemAttr( list<string>& tip, vector<RegItemData>& itemdata );
wstring GetItemType( string& tip );
void GetItemAttr( string& tip, vector<RegItemData>& itemdata );
void AddRegular(wxString id,wxString exp);
void AddRegular(wxString exp);
};
|
[
"24509826@qq.com"
] |
24509826@qq.com
|
83dea1fb9c54b809bc3b64e9bb7ae72dd7e37e32
|
f8e473cfde05425d873e8138f854c248f95701ee
|
/CPP-08/ex01/Span.hpp
|
aca10c52b0466571d243abfe2b15d30625090bfd
|
[] |
no_license
|
Ourobore/CPP-Modules
|
cc29150d1c1dc8808c6d62d3c44190ce91ae0b80
|
a15c25dd3407c5ccdb7d67654e2009534c36d891
|
refs/heads/master
| 2023-07-15T18:35:59.999433
| 2021-08-25T08:50:59
| 2021-08-25T08:50:59
| 377,454,565
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,539
|
hpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Span.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: user42 <user42@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/20 10:30:18 by lchapren #+# #+# */
/* Updated: 2021/08/24 14:34:35 by user42 ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SPAN_HPP
# define SPAN_HPP
# include <iostream>
# include <climits>
# include <cstdlib>
# include <ctime>
# include <vector>
# include <algorithm>
class Span
{
private:
std::vector<int> _array;
unsigned int _N;
public:
Span(void);
Span(unsigned int N);
Span(Span const &rhs);
Span& operator=(Span const &rhs);
~Span(void);
void addNumber(int number);
void addNumber(int number, unsigned int range);
void addNumber(std::vector<int> range);
unsigned int shortestSpan(void);
unsigned int longestSpan(void);
std::vector<int>& getArray(void);
};
std::ostream& operator<<(std::ostream& o, Span &rhs);
#endif
|
[
"chaprenet.loic@gmail.com"
] |
chaprenet.loic@gmail.com
|
3f93728c5bade4a533c21e00a667849e35db976c
|
d0629b6c3bdb64a8346cbb5049edc90d66d646f2
|
/gfx/angle/src/tests/egl_tests/EGLSurfaceTest.cpp
|
19fe79c476fed8c2350035fcdf224610172dff7c
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
h4writer/oomrepo
|
ccd08c506796af9e7e3a3c8131179bd0a0ab3ac3
|
6c533b04356f7ac59915928282a95070dc45d08c
|
refs/heads/master
| 2022-08-03T20:40:49.348969
| 2015-10-06T09:29:56
| 2015-10-06T09:29:56
| 43,739,681
| 0
| 0
|
NOASSERTION
| 2022-03-29T21:55:20
| 2015-10-06T08:53:22
| null |
UTF-8
|
C++
| false
| false
| 14,504
|
cpp
|
//
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// EGLSurfaceTest:
// Tests pertaining to egl::Surface.
//
#include <gtest/gtest.h>
#include <vector>
#include "OSWindow.h"
#include "test_utils/ANGLETest.h"
namespace
{
class EGLSurfaceTest : public testing::Test
{
protected:
EGLSurfaceTest()
: mDisplay(EGL_NO_DISPLAY),
mWindowSurface(EGL_NO_SURFACE),
mPbufferSurface(EGL_NO_SURFACE),
mContext(EGL_NO_CONTEXT),
mSecondContext(EGL_NO_CONTEXT),
mOSWindow(nullptr)
{
}
void SetUp() override
{
mOSWindow = CreateOSWindow();
mOSWindow->initialize("EGLSurfaceTest", 64, 64);
}
// Release any resources created in the test body
void TearDown() override
{
if (mDisplay != EGL_NO_DISPLAY)
{
eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (mWindowSurface != EGL_NO_SURFACE)
{
eglDestroySurface(mDisplay, mWindowSurface);
mWindowSurface = EGL_NO_SURFACE;
}
if (mPbufferSurface != EGL_NO_SURFACE)
{
eglDestroySurface(mDisplay, mPbufferSurface);
mPbufferSurface = EGL_NO_SURFACE;
}
if (mContext != EGL_NO_CONTEXT)
{
eglDestroyContext(mDisplay, mContext);
mContext = EGL_NO_CONTEXT;
}
if (mSecondContext != EGL_NO_CONTEXT)
{
eglDestroyContext(mDisplay, mSecondContext);
mSecondContext = EGL_NO_CONTEXT;
}
eglTerminate(mDisplay);
mDisplay = EGL_NO_DISPLAY;
}
mOSWindow->destroy();
SafeDelete(mOSWindow);
ASSERT_TRUE(mWindowSurface == EGL_NO_SURFACE && mContext == EGL_NO_CONTEXT);
}
void initializeDisplay(EGLenum platformType)
{
PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT"));
ASSERT_TRUE(eglGetPlatformDisplayEXT != nullptr);
std::vector<EGLint> displayAttributes;
displayAttributes.push_back(EGL_PLATFORM_ANGLE_TYPE_ANGLE);
displayAttributes.push_back(platformType);
displayAttributes.push_back(EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE);
displayAttributes.push_back(EGL_DONT_CARE);
displayAttributes.push_back(EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE);
displayAttributes.push_back(EGL_DONT_CARE);
if (platformType == EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE || platformType == EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE)
{
displayAttributes.push_back(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE);
displayAttributes.push_back(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE);
}
displayAttributes.push_back(EGL_NONE);
mDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, mOSWindow->getNativeDisplay(), displayAttributes.data());
ASSERT_TRUE(mDisplay != EGL_NO_DISPLAY);
EGLint majorVersion, minorVersion;
ASSERT_TRUE(eglInitialize(mDisplay, &majorVersion, &minorVersion) == EGL_TRUE);
eglBindAPI(EGL_OPENGL_ES_API);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
}
void initializeSurface(EGLConfig config)
{
mConfig = config;
std::vector<EGLint> surfaceAttributes;
surfaceAttributes.push_back(EGL_NONE);
surfaceAttributes.push_back(EGL_NONE);
// Create first window surface
mWindowSurface = eglCreateWindowSurface(mDisplay, mConfig, mOSWindow->getNativeWindow(), &surfaceAttributes[0]);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
mPbufferSurface = eglCreatePbufferSurface(mDisplay, mConfig, &surfaceAttributes[0]);
EGLint contextAttibutes[] =
{
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
mContext = eglCreateContext(mDisplay, mConfig, nullptr, contextAttibutes);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
mSecondContext = eglCreateContext(mDisplay, mConfig, nullptr, contextAttibutes);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
}
void initializeSurfaceWithDefaultConfig()
{
const EGLint configAttributes[] =
{
EGL_RED_SIZE, EGL_DONT_CARE,
EGL_GREEN_SIZE, EGL_DONT_CARE,
EGL_BLUE_SIZE, EGL_DONT_CARE,
EGL_ALPHA_SIZE, EGL_DONT_CARE,
EGL_DEPTH_SIZE, EGL_DONT_CARE,
EGL_STENCIL_SIZE, EGL_DONT_CARE,
EGL_SAMPLE_BUFFERS, 0,
EGL_NONE
};
EGLint configCount;
EGLConfig config;
ASSERT_TRUE(eglChooseConfig(mDisplay, configAttributes, &config, 1, &configCount) || (configCount != 1) == EGL_TRUE);
initializeSurface(config);
}
GLuint createProgram()
{
const std::string testVertexShaderSource = SHADER_SOURCE
(
attribute highp vec4 position;
void main(void)
{
gl_Position = position;
}
);
const std::string testFragmentShaderSource = SHADER_SOURCE
(
void main(void)
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
);
return CompileProgram(testVertexShaderSource, testFragmentShaderSource);
}
void drawWithProgram(GLuint program)
{
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
GLint positionLocation = glGetAttribLocation(program, "position");
glUseProgram(program);
const GLfloat vertices[] =
{
-1.0f, 1.0f, 0.5f,
-1.0f, -1.0f, 0.5f,
1.0f, -1.0f, 0.5f,
-1.0f, 1.0f, 0.5f,
1.0f, -1.0f, 0.5f,
1.0f, 1.0f, 0.5f,
};
glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, 0, vertices);
glEnableVertexAttribArray(positionLocation);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(positionLocation);
glVertexAttribPointer(positionLocation, 4, GL_FLOAT, GL_FALSE, 0, NULL);
EXPECT_PIXEL_EQ(mOSWindow->getWidth() / 2, mOSWindow->getHeight() / 2, 255, 0, 0, 255);
}
void runMessageLoopTest(EGLSurface secondSurface, EGLContext secondContext)
{
eglMakeCurrent(mDisplay, mWindowSurface, mWindowSurface, mContext);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
// Make a second context current
eglMakeCurrent(mDisplay, secondSurface, secondSurface, secondContext);
eglDestroySurface(mDisplay, mWindowSurface);
// Create second window surface
std::vector<EGLint> surfaceAttributes;
surfaceAttributes.push_back(EGL_NONE);
surfaceAttributes.push_back(EGL_NONE);
mWindowSurface = eglCreateWindowSurface(mDisplay, mConfig, mOSWindow->getNativeWindow(), &surfaceAttributes[0]);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
eglMakeCurrent(mDisplay, mWindowSurface, mWindowSurface, mContext);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
mOSWindow->signalTestEvent();
mOSWindow->messageLoop();
ASSERT_TRUE(mOSWindow->didTestEventFire());
// Simple operation to test the FBO is set appropriately
glClear(GL_COLOR_BUFFER_BIT);
}
EGLDisplay mDisplay;
EGLSurface mWindowSurface;
EGLSurface mPbufferSurface;
EGLContext mContext;
EGLContext mSecondContext;
EGLConfig mConfig;
OSWindow *mOSWindow;
};
// Test a surface bug where we could have two Window surfaces active
// at one time, blocking message loops. See http://crbug.com/475085
TEST_F(EGLSurfaceTest, MessageLoopBug)
{
const char *extensionsString = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
if (strstr(extensionsString, "EGL_ANGLE_platform_angle_d3d") == nullptr)
{
std::cout << "D3D Platform not supported in ANGLE" << std::endl;
return;
}
initializeDisplay(EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE);
initializeSurfaceWithDefaultConfig();
runMessageLoopTest(EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
// Tests the message loop bug, but with setting a second context
// instead of null.
TEST_F(EGLSurfaceTest, MessageLoopBugContext)
{
const char *extensionsString = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
if (strstr(extensionsString, "EGL_ANGLE_platform_angle_d3d") == nullptr)
{
std::cout << "D3D Platform not supported in ANGLE" << std::endl;
return;
}
initializeDisplay(EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE);
initializeSurfaceWithDefaultConfig();
runMessageLoopTest(mPbufferSurface, mSecondContext);
}
// Test a bug where calling makeCurrent twice would release the surface
TEST_F(EGLSurfaceTest, MakeCurrentTwice)
{
initializeDisplay(EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE);
initializeSurfaceWithDefaultConfig();
eglMakeCurrent(mDisplay, mWindowSurface, mWindowSurface, mContext);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
eglMakeCurrent(mDisplay, mWindowSurface, mWindowSurface, mContext);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
// Simple operation to test the FBO is set appropriately
glClear(GL_COLOR_BUFFER_BIT);
}
// Test that the D3D window surface is correctly resized after calling swapBuffers
TEST_F(EGLSurfaceTest, ResizeD3DWindow)
{
const char *extensionsString = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
if (strstr(extensionsString, "EGL_ANGLE_platform_angle_d3d") == nullptr)
{
std::cout << "D3D Platform not supported in ANGLE" << std::endl;
return;
}
initializeDisplay(EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE);
initializeSurfaceWithDefaultConfig();
eglSwapBuffers(mDisplay, mWindowSurface);
ASSERT_EGL_SUCCESS();
EGLint height;
eglQuerySurface(mDisplay, mWindowSurface, EGL_HEIGHT, &height);
ASSERT_EGL_SUCCESS();
ASSERT_EQ(64, height); // initial size
// set window's height to 0
mOSWindow->resize(64, 0);
eglSwapBuffers(mDisplay, mWindowSurface);
ASSERT_EGL_SUCCESS();
eglQuerySurface(mDisplay, mWindowSurface, EGL_HEIGHT, &height);
ASSERT_EGL_SUCCESS();
ASSERT_EQ(0, height);
// restore window's height
mOSWindow->resize(64, 64);
eglSwapBuffers(mDisplay, mWindowSurface);
ASSERT_EGL_SUCCESS();
eglQuerySurface(mDisplay, mWindowSurface, EGL_HEIGHT, &height);
ASSERT_EGL_SUCCESS();
ASSERT_EQ(64, height);
}
// Test creating a surface that supports a EGLConfig with 16bit
// support GL_RGB565
TEST_F(EGLSurfaceTest, CreateWithEGLConfig5650Support)
{
const char *extensionsString = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
if (strstr(extensionsString, "EGL_ANGLE_platform_angle_d3d") == nullptr)
{
std::cout << "D3D Platform not supported in ANGLE" << std::endl;
return;
}
const EGLint configAttributes[] =
{
EGL_RED_SIZE, 5,
EGL_GREEN_SIZE, 6,
EGL_BLUE_SIZE, 5,
EGL_ALPHA_SIZE, 0,
EGL_DEPTH_SIZE, 0,
EGL_STENCIL_SIZE, 0,
EGL_SAMPLE_BUFFERS, 0,
EGL_NONE
};
initializeDisplay(EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE);
EGLConfig config;
if (EGLWindow::FindEGLConfig(mDisplay, configAttributes, &config) == EGL_FALSE)
{
std::cout << "EGLConfig for a GL_RGB565 surface is not supported, skipping test" << std::endl;
return;
}
initializeSurface(config);
eglMakeCurrent(mDisplay, mWindowSurface, mWindowSurface, mContext);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
GLuint program = createProgram();
drawWithProgram(program);
EXPECT_GL_NO_ERROR();
glDeleteProgram(program);
}
// Test creating a surface that supports a EGLConfig with 16bit
// support GL_RGBA4
TEST_F(EGLSurfaceTest, CreateWithEGLConfig4444Support)
{
const char *extensionsString = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
if (strstr(extensionsString, "EGL_ANGLE_platform_angle_d3d") == nullptr)
{
std::cout << "D3D Platform not supported in ANGLE" << std::endl;
return;
}
const EGLint configAttributes[] =
{
EGL_RED_SIZE, 4,
EGL_GREEN_SIZE, 4,
EGL_BLUE_SIZE, 4,
EGL_ALPHA_SIZE, 4,
EGL_DEPTH_SIZE, 0,
EGL_STENCIL_SIZE, 0,
EGL_SAMPLE_BUFFERS, 0,
EGL_NONE
};
initializeDisplay(EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE);
EGLConfig config;
if (EGLWindow::FindEGLConfig(mDisplay, configAttributes, &config) == EGL_FALSE)
{
std::cout << "EGLConfig for a GL_RGBA4 surface is not supported, skipping test" << std::endl;
return;
}
initializeSurface(config);
eglMakeCurrent(mDisplay, mWindowSurface, mWindowSurface, mContext);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
GLuint program = createProgram();
drawWithProgram(program);
EXPECT_GL_NO_ERROR();
glDeleteProgram(program);
}
// Test creating a surface that supports a EGLConfig with 16bit
// support GL_RGB5_A1
TEST_F(EGLSurfaceTest, CreateWithEGLConfig5551Support)
{
const char *extensionsString = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
if (strstr(extensionsString, "EGL_ANGLE_platform_angle_d3d") == nullptr)
{
std::cout << "D3D Platform not supported in ANGLE" << std::endl;
return;
}
const EGLint configAttributes[] =
{
EGL_RED_SIZE, 5,
EGL_GREEN_SIZE, 5,
EGL_BLUE_SIZE, 5,
EGL_ALPHA_SIZE, 1,
EGL_DEPTH_SIZE, 0,
EGL_STENCIL_SIZE, 0,
EGL_SAMPLE_BUFFERS, 0,
EGL_NONE
};
initializeDisplay(EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE);
EGLConfig config;
if (EGLWindow::FindEGLConfig(mDisplay, configAttributes, &config) == EGL_FALSE)
{
std::cout << "EGLConfig for a GL_RGB5_A1 surface is not supported, skipping test" << std::endl;
return;
}
initializeSurface(config);
eglMakeCurrent(mDisplay, mWindowSurface, mWindowSurface, mContext);
ASSERT_TRUE(eglGetError() == EGL_SUCCESS);
GLuint program = createProgram();
drawWithProgram(program);
EXPECT_GL_NO_ERROR();
glDeleteProgram(program);
}
}
|
[
"hv1989@gmail.com"
] |
hv1989@gmail.com
|
e5d5d251d02668ecde61fe7bfc1e632e7babd01a
|
0d60e85ea4a13eb3467cd1dd80ce31768cee02b4
|
/src/worker.cpp
|
6a36e6a0a254a9de25089f4e7b400ca223d0d43c
|
[
"OpenSSL",
"ISC",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
longamu/pipy
|
c6bd7e1b9d51f873c6284deb51195d89cade60bd
|
6f4ad83fad94e9cb67e9f43756df30e8b9ee8a94
|
refs/heads/main
| 2023-07-15T03:36:24.552356
| 2021-08-23T02:26:20
| 2021-08-23T02:26:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,743
|
cpp
|
/*
* Copyright (c) 2019 by flomesh.io
*
* Unless prior written consent has been obtained from the copyright
* owner, the following shall not be allowed.
*
* 1. The distribution of any source codes, header files, make files,
* or libraries of the software.
*
* 2. Disclosure of any source codes pertaining to the software to any
* additional parties.
*
* 3. Alteration or removal of any notices in or on the software or
* within the documentation included within the software.
*
* ALL SOURCE CODE AS WELL AS ALL DOCUMENTATION INCLUDED WITH THIS
* SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION, 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 "worker.hpp"
#include "module.hpp"
#include "task.hpp"
#include "event.hpp"
#include "message.hpp"
#include "session.hpp"
#include "api/algo.hpp"
#include "api/configuration.hpp"
#include "api/console.hpp"
#include "api/crypto.hpp"
#include "api/hessian.hpp"
#include "api/http.hpp"
#include "api/json.hpp"
#include "api/netmask.hpp"
#include "api/os.hpp"
#include "api/pipy.hpp"
#include "api/url.hpp"
#include "api/xml.hpp"
#include "logging.hpp"
#include <array>
#include <stdexcept>
extern void main_trigger_reload();
//
// Global
//
namespace pipy {
class Global : public pjs::ObjectTemplate<Global>
{
};
} // namespace pipy
namespace pjs {
using namespace pipy;
template<> void ClassDef<Global>::init() {
ctor();
// Object
variable("Object", class_of<Constructor<Object>>());
// Boolean
variable("Boolean", class_of<Constructor<Boolean>>());
// Number
variable("Number", class_of<Constructor<Number>>());
// String
variable("String", class_of<Constructor<String>>());
// Array
variable("Array", class_of<Constructor<Array>>());
// Date
variable("Date", class_of<Constructor<Date>>());
// RegExp
variable("RegExp", class_of<Constructor<RegExp>>());
// JSON
variable("JSON", class_of<JSON>());
// XML
variable("XML", class_of<XML>());
// Hessian
variable("Hessian", class_of<Hessian>());
// console
variable("console", class_of<Console>());
// os
variable("os", class_of<OS>());
// URL
variable("URL", class_of<Constructor<URL>>());
// Netmask
variable("Netmask", class_of<Constructor<Netmask>>());
// Session
variable("Session", class_of<Constructor<Session>>());
// Data
variable("Data", class_of<Constructor<pipy::Data>>());
// Message
variable("Message", class_of<Constructor<Message>>());
// MessageStart
variable("MessageStart", class_of<Constructor<MessageStart>>());
// MessageEnd
variable("MessageEnd", class_of<Constructor<MessageEnd>>());
// SessionEnd
variable("SessionEnd", class_of<Constructor<SessionEnd>>());
// http
variable("http", class_of<http::Http>());
// crypto
variable("crypto", class_of<crypto::Crypto>());
// algo
variable("algo", class_of<algo::Algo>());
// pipy
variable("pipy", class_of<Pipy>());
// repeat
method("repeat", [](Context &ctx, Object *obj, Value &ret) {
int count;
Function *f;
if (ctx.try_arguments(1, &f)) {
Value idx;
for (int i = 0;; i++) {
idx.set(i);
(*f)(ctx, 1, &idx, ret);
if (!ctx.ok()) break;
if (!ret.to_boolean()) break;
}
} else if (ctx.try_arguments(2, &count, &f)) {
Value idx;
for (int i = 0; i < count; i++) {
idx.set(i);
(*f)(ctx, 1, &idx, ret);
if (!ctx.ok()) break;
if (!ret.to_boolean()) break;
}
} else {
ctx.error_argument_type(0, "a function");
}
});
}
} // namespace pjs
//
// Worker
//
namespace pipy {
Worker* Worker::s_current = nullptr;
std::set<Worker*> Worker::s_all_workers;
Worker::Worker()
: m_global_object(Global::make())
{
s_all_workers.insert(this);
}
Worker::~Worker() {
if (s_current == this) s_current = nullptr;
s_all_workers.erase(this);
}
auto Worker::get_module(pjs::Str *filename) -> Module* {
auto i = m_module_name_map.find(filename);
if (i == m_module_name_map.end()) return nullptr;
return i->second;
}
auto Worker::find_module(const std::string &path) -> Module* {
auto i = m_module_map.find(path);
if (i == m_module_map.end()) return nullptr;
return i->second;
}
auto Worker::load_module(const std::string &path) -> Module* {
auto i = m_module_map.find(path);
if (i != m_module_map.end()) return i->second;
auto l = m_modules.size();
auto mod = new Module(this, l);
m_module_map[path] = mod;
m_module_name_map[pjs::Str::make(path)] = mod;
m_modules.push_back(mod);
if (!m_root) m_root = mod;
if (!mod->load(path)) return nullptr;
return mod;
}
void Worker::add_export(pjs::Str *ns, pjs::Str *name, Module *module) {
auto &names = m_namespaces[ns];
auto i = names.find(name);
if (i != names.end()) {
std::string msg("duplicated variable exporting name ");
msg += name->str();
msg += " from ";
msg += module->path();
throw std::runtime_error(msg);
}
names[name] = module;
}
auto Worker::get_export(pjs::Str *ns, pjs::Str *name) -> Module* {
auto i = m_namespaces.find(ns);
if (i == m_namespaces.end()) return nullptr;
auto j = i->second.find(name);
if (j == i->second.end()) return nullptr;
return j->second;
}
auto Worker::new_loading_context() -> Context* {
return new Context(nullptr, this, m_global_object);
}
auto Worker::new_runtime_context(Context *base) -> Context* {
auto data = ContextData::make(m_modules.size());
for (size_t i = 0; i < m_modules.size(); i++) {
pjs::Object *proto = nullptr;
if (base) proto = base->m_data->at(i);
data->at(i) = m_modules[i]->new_context_data(proto);
}
auto ctx = new Context(
base ? base->group() : nullptr,
this, m_global_object, data
);
if (base) ctx->m_inbound = base->m_inbound;
return ctx;
}
bool Worker::start() {
try {
for (auto i : m_modules) i->bind_exports();
for (auto i : m_modules) i->bind_imports();
for (auto i : m_modules) i->start();
s_current = this;
} catch (std::runtime_error &err) {
Log::error("%s", err.what());
return false;
}
for (auto *task : m_tasks) {
if (!task->start()) {
return false;
}
}
return true;
}
void Worker::stop() {
for (auto *task : m_tasks) {
task->stop();
}
m_tasks.clear();
}
} // namespace pipy
|
[
"pajamacoder@flomesh.io"
] |
pajamacoder@flomesh.io
|
55f6b4b4bf67d2735213257420e0d0d7fd0f3896
|
b1dabaf550797d09925e62962825e4018a00503b
|
/chart.h
|
5aebb3397245ef8b9d8d47bc7b41eef604f36caf
|
[] |
no_license
|
jodijhouranda/Kalingga
|
7e2b46020470a1a138175e3e0b2ce764a302c22f
|
bba16f48392e6a2d3414ec3029267061f7da46dd
|
refs/heads/master
| 2020-04-16T18:32:55.552285
| 2015-07-15T07:11:42
| 2015-07-15T07:11:42
| 33,490,872
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 697
|
h
|
#ifndef CHART_H
#define CHART_H
#include <QFile>
#include <QGraphicsSvgItem>
#include <QTextStream>
#include <QGraphicsScene>
#include <QDebug>
#include <QGraphicsView>
#include <resultviewitem.h>
#include <QHBoxLayout>
#include <QSvgWidget>
#include <RInside.h>
class Chart
{
public:
Chart();
~Chart();
void setupChartView(QString chartName ,QString variable,QWidget* configWidget);
void filterSVGFile();
void setTempFile(RInside& rconn);
void printGraph(RInside& rconn);
void printGraph(RInside& rconn,int width,int height);
QSvgWidget* graph;
private:
QString m_tempfile;
QString m_svgfile;
QString tfile;
QString sfile;
};
#endif // CHART_H
|
[
"jwst.28@gmail.com"
] |
jwst.28@gmail.com
|
188caa720ef449ba95de968837f33415b26fbadf
|
783fbeabbc7fc8090ee9e6765d26b38aa5db2efb
|
/src/ublox/src/comms/field/ArrayList.h
|
a7c6965924bccca3cbdda54a723cd7b2a3d8e842
|
[] |
no_license
|
salkinium/navimet
|
760cd876987012f274429cb285efe329451f9ca0
|
833fc426c66401348315d66baee2a54ae6142834
|
refs/heads/master
| 2022-01-08T19:17:33.009843
| 2019-08-04T23:27:28
| 2019-08-04T23:27:28
| 164,520,548
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 19,606
|
h
|
//
// Copyright 2014 - 2018 (C). Alex Robenko. All rights reserved.
//
// This file is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#pragma once
#include <vector>
#include "comms/ErrorStatus.h"
#include "comms/options.h"
#include "comms/util/StaticVector.h"
#include "comms/util/ArrayView.h"
#include "basic/ArrayList.h"
#include "details/AdaptBasicField.h"
#include "details/OptionsParser.h"
#include "tag.h"
namespace comms
{
namespace field
{
namespace details
{
template <bool THasOrigDataViewStorage>
struct ArrayListOrigDataViewStorageType;
template <>
struct ArrayListOrigDataViewStorageType<true>
{
template <typename TElement>
using Type = comms::util::ArrayView<TElement>;
};
template <>
struct ArrayListOrigDataViewStorageType<false>
{
template <typename TElement>
using Type = std::vector<TElement>;
};
template <bool THasSequenceFixedSizeUseFixedSizeStorage>
struct ArrayListSequenceFixedSizeUseFixedSizeStorageType;
template <>
struct ArrayListSequenceFixedSizeUseFixedSizeStorageType<true>
{
template <typename TElement, typename TOpt>
using Type = comms::util::StaticVector<TElement, TOpt::SequenceFixedSize>;
};
template <>
struct ArrayListSequenceFixedSizeUseFixedSizeStorageType<false>
{
template <typename TElement, typename TOpt>
using Type =
typename ArrayListOrigDataViewStorageType<
TOpt::HasOrigDataView && std::is_integral<TElement>::value && (sizeof(TElement) == sizeof(std::uint8_t))
>::template Type<TElement>;
};
template <bool THasFixedSizeStorage>
struct ArrayListFixedSizeStorageType;
template <>
struct ArrayListFixedSizeStorageType<true>
{
template <typename TElement, typename TOpt>
using Type = comms::util::StaticVector<TElement, TOpt::FixedSizeStorage>;
};
template <>
struct ArrayListFixedSizeStorageType<false>
{
template <typename TElement, typename TOpt>
using Type =
typename ArrayListSequenceFixedSizeUseFixedSizeStorageType<TOpt::HasSequenceFixedSizeUseFixedSizeStorage>
::template Type<TElement, TOpt>;
};
template <bool THasCustomStorage>
struct ArrayListCustomArrayListStorageType;
template <>
struct ArrayListCustomArrayListStorageType<true>
{
template <typename TElement, typename TOpt>
using Type = typename TOpt::CustomStorageType;
};
template <>
struct ArrayListCustomArrayListStorageType<false>
{
template <typename TElement, typename TOpt>
using Type =
typename ArrayListFixedSizeStorageType<TOpt::HasFixedSizeStorage>::template Type<TElement, TOpt>;
};
template <typename TElement, typename TOpt>
using ArrayListStorageTypeT =
typename ArrayListCustomArrayListStorageType<TOpt::HasCustomStorageType>::template Type<TElement, TOpt>;
template <typename TFieldBase, typename TElement, typename... TOptions>
using ArrayListBase =
AdaptBasicFieldT<
comms::field::basic::ArrayList<
TFieldBase,
ArrayListStorageTypeT<TElement, OptionsParser<TOptions...> >
>,
TOptions...
>;
} // namespace details
/// @brief Field that represents a sequential collection of fields.
/// @details By default uses
/// <a href="http://en.cppreference.com/w/cpp/container/vector">std::vector</a>,
/// for internal storage, unless comms::option::FixedSizeStorage option is used,
/// which forces usage of comms::util::StaticVector instead.
/// @tparam TFieldBase Base class for this field, expected to be a variant of
/// comms::Field.
/// @tparam TElement Element of the collection, can be either basic integral value
/// (such as std::uint8_t) or any other field from comms::field namespace.@n
/// For example:
/// @code
/// using MyFieldBase = comms::Field<comms::option::BigEndian>;
/// using RawDataSeqField =
/// comms::field::ArrayList<
/// MyFieldBase,
/// std::uint8_t
/// >;
/// using CollectionOfBundlesField =
/// comms::field::ArrayList<
/// MyFieldBase,
/// std::field::Bundle<
/// MyFieldBase,
/// std::tuple<
/// comms::field::IntValue<MyFieldBase, std::uint16_t>
/// comms::field::IntValue<MyFieldBase, std::uint8_t>
/// comms::field::IntValue<MyFieldBase, std::uint8_t>
/// >
/// >
/// >;
/// @endcode
/// @tparam TOptions Zero or more options that modify/refine default behaviour
/// of the field.@n
/// Supported options are:
/// @li @ref comms::option::FixedSizeStorage
/// @li @ref comms::option::CustomStorageType
/// @li @ref comms::option::SequenceSizeFieldPrefix
/// @li @ref comms::option::SequenceSerLengthFieldPrefix
/// @li @ref comms::option::SequenceElemSerLengthFieldPrefix
/// @li @ref comms::option::SequenceElemFixedSerLengthFieldPrefix
/// @li @ref comms::option::SequenceSizeForcingEnabled
/// @li @ref comms::option::SequenceLengthForcingEnabled
/// @li @ref comms::option::SequenceFixedSize
/// @li @ref comms::option::SequenceTerminationFieldSuffix
/// @li @ref comms::option::SequenceTrailingFieldSuffix
/// @li @ref comms::option::DefaultValueInitialiser
/// @li @ref comms::option::ContentsValidator
/// @li @ref comms::option::ContentsRefresher
/// @li @ref comms::option::HasCustomRead
/// @li @ref comms::option::HasCustomRefresh
/// @li @ref comms::option::FailOnInvalid
/// @li @ref comms::option::IgnoreInvalid
/// @li @ref comms::option::OrigDataView (valid only if TElement is integral type
/// of 1 byte size.
/// @li @ref comms::option::EmptySerialization
/// @li @ref comms::option::VersionStorage
/// @extends comms::Field
/// @headerfile comms/field/ArrayList.h
template <typename TFieldBase, typename TElement, typename... TOptions>
class ArrayList : private details::ArrayListBase<TFieldBase, TElement, TOptions...>
{
using BaseImpl = details::ArrayListBase<TFieldBase, TElement, TOptions...>;
public:
/// @brief Endian used for serialisation.
using Endian = typename BaseImpl::Endian;
/// @brief Version type
using VersionType = typename BaseImpl::VersionType;
/// @brief All the options provided to this class bundled into struct.
using ParsedOptions = details::OptionsParser<TOptions...>;
/// @brief Tag indicating type of the field
using Tag = typename std::conditional<
std::is_integral<TElement>::value,
tag::RawArrayList,
tag::ArrayList
>::type;
/// @brief Type of underlying value.
/// @details If comms::option::FixedSizeStorage option is NOT used, the
/// ValueType is std::vector<TElement>, otherwise it becomes
/// comms::util::StaticVector<TElement, TSize>, where TSize is a size
/// provided to comms::option::FixedSizeStorage option.
using ValueType = typename BaseImpl::ValueType;
/// @brief Type of the element.
using ElementType = typename BaseImpl::ElementType;
/// @brief Default constructor
ArrayList() = default;
/// @brief Value constructor
explicit ArrayList(const ValueType& val)
: BaseImpl(val)
{
}
/// @brief Value constructor
explicit ArrayList(ValueType&& val)
: BaseImpl(std::move(val))
{
}
/// @brief Copy constructor
ArrayList(const ArrayList&) = default;
/// @brief Move constructor
ArrayList(ArrayList&&) = default;
/// @brief Destructor
~ArrayList() noexcept = default;
/// @brief Copy assignment
ArrayList& operator=(const ArrayList&) = default;
/// @brief Move assignment
ArrayList& operator=(ArrayList&&) = default;
/// @brief Get access to the value storage.
ValueType& value()
{
return BaseImpl::value();
}
/// @brief Get access to the value storage.
const ValueType& value() const
{
return BaseImpl::value();
}
/// @brief Get length of serialised data
constexpr std::size_t length() const
{
return BaseImpl::length();
}
/// @brief Read field value from input data sequence
/// @details By default, the read operation will try to consume all the
/// data available, unless size limiting option (such as
/// comms::option::SequenceSizeFieldPrefix, comms::option::SequenceFixedSize,
/// comms::option::SequenceSizeForcingEnabled,
/// comms::option::SequenceLengthForcingEnabled) is used.
/// @param[in, out] iter Iterator to read the data.
/// @param[in] len Number of bytes available for reading.
/// @return Status of read operation.
/// @post Iterator is advanced.
template <typename TIter>
ErrorStatus read(TIter& iter, std::size_t len)
{
return BaseImpl::read(iter, len);
}
/// @brief Read field value from input data sequence without error check and status report.
/// @details Similar to @ref read(), but doesn't perform any correctness
/// checks and doesn't report any failures.
/// @param[in, out] iter Iterator to read the data.
/// @post Iterator is advanced.
template <typename TIter>
void readNoStatus(TIter& iter)
{
BaseImpl::readNoStatus(iter);
}
/// @brief Write current field value to output data sequence
/// @details By default, the write operation will write all the
/// elements the field contains. If comms::option::SequenceFixedSize option
/// is used, the number of elements, that is going to be written, is
/// exactly as the option specifies. If underlying vector storage
/// doesn't contain enough data, the default constructed elements will
/// be appended to the written sequence until the required amount of
/// elements is reached.
/// @param[in, out] iter Iterator to write the data.
/// @param[in] len Maximal number of bytes that can be written.
/// @return Status of write operation.
/// @post Iterator is advanced.
template <typename TIter>
ErrorStatus write(TIter& iter, std::size_t len) const
{
return BaseImpl::write(iter, len);
}
/// @brief Write current field value to output data sequence without error check and status report.
/// @details Similar to @ref write(), but doesn't perform any correctness
/// checks and doesn't report any failures.
/// @param[in, out] iter Iterator to write the data.
/// @post Iterator is advanced.
template <typename TIter>
void writeNoStatus(TIter& iter) const
{
BaseImpl::writeNoStatus(iter);
}
/// @brief Check validity of the field value.
/// @details The collection is valid if all the elements are valid. In case
/// comms::option::ContentsValidator option is used, the validator,
/// it provides, is invoked IN ADDITION to the validation of the elements.
/// @return true in case the field's value is valid, false otherwise.
bool valid() const
{
return BaseImpl::valid();
}
/// @brief Refresh the field.
/// @details Calls refresh() on all the elements (if they are fields and not raw bytes).
/// @brief Returns true if any of the elements has been updated, false otherwise.
bool refresh()
{
return BaseImpl::refresh();
}
/// @brief Get minimal length that is required to serialise field of this type.
static constexpr std::size_t minLength()
{
return BaseImpl::minLength();
}
/// @brief Get maximal length that is required to serialise field of this type.
static constexpr std::size_t maxLength()
{
return BaseImpl::maxLength();
}
/// @brief Force number of elements that must be read in the next read()
/// invocation.
/// @details Exists only if comms::option::SequenceSizeForcingEnabled option has been
/// used.
/// @param[in] count Number of elements to read during following read operation.
void forceReadElemCount(std::size_t count)
{
return BaseImpl::forceReadElemCount(count);
}
/// @brief Clear forcing of the number of elements that must be read in the next read()
/// invocation.
/// @details Exists only if comms::option::SequenceSizeForcingEnabled option has been
/// used.
void clearReadElemCount()
{
return BaseImpl::clearReadElemCount();
}
/// @brief Force available length for the next read() invocation.
/// @details Exists only if @ref comms::option::SequenceLengthForcingEnabled option has been
/// used.
/// @param[in] count Number of elements to read during following read operation.
void forceReadLength(std::size_t count)
{
return BaseImpl::forceReadLength(count);
}
/// @brief Clear forcing of the available length in the next read()
/// invocation.
/// @details Exists only if @ref comms::option::SequenceLengthForcingEnabled option has been
/// used.
void clearReadLengthForcing()
{
return BaseImpl::clearReadLengthForcing();
}
/// @brief Force serialisation length of a single element.
/// @details The function can be used to force a serialisation length of a
/// single element within the ArrayList.
/// Exists only if @ref comms::option::SequenceElemLengthForcingEnabled option has been
/// used.
/// @param[in] count Number of elements to read during following read operation.
void forceReadElemLength(std::size_t count)
{
return BaseImpl::forceReadElemLength(count);
}
/// @brief Clear forcing the serialisation length of the single element.
/// @details Exists only if comms::option::SequenceElemLengthForcingEnabled option has been
/// used.
void clearReadElemLengthForcing()
{
return BaseImpl::clearReadElemLengthForcing();
}
/// @brief Compile time check if this class is version dependent
static constexpr bool isVersionDependent()
{
return ParsedOptions::HasCustomVersionUpdate || BaseImpl::isVersionDependent();
}
/// @brief Get version of the field.
/// @details Exists only if @ref comms::option::VersionStorage option has been provided.
VersionType getVersion() const
{
return BaseImpl::getVersion();
}
/// @brief Default implementation of version update.
/// @return @b true in case the field contents have changed, @b false otherwise
bool setVersion(VersionType version)
{
return BaseImpl::setVersion(version);
}
protected:
using BaseImpl::readData;
using BaseImpl::writeData;
private:
static_assert(!ParsedOptions::HasSerOffset,
"comms::option::NumValueSerOffset option is not applicable to ArrayList field");
static_assert(!ParsedOptions::HasFixedLengthLimit,
"comms::option::FixedLength option is not applicable to ArrayList field");
static_assert(!ParsedOptions::HasFixedBitLengthLimit,
"comms::option::FixedBitLength option is not applicable to ArrayList field");
static_assert(!ParsedOptions::HasVarLengthLimits,
"comms::option::VarLength option is not applicable to ArrayList field");
static_assert(!ParsedOptions::HasScalingRatio,
"comms::option::ScalingRatio option is not applicable to ArrayList field");
static_assert(!ParsedOptions::HasUnits,
"comms::option::Units option is not applicable to ArrayList field");
static_assert(!ParsedOptions::HasMultiRangeValidation,
"comms::option::ValidNumValueRange (or similar) option is not applicable to ArrayList field");
static_assert((!ParsedOptions::HasOrigDataView) || (std::is_integral<TElement>::value && (sizeof(TElement) == sizeof(std::uint8_t))),
"Usage of comms::option::OrigDataView option is allowed only for raw binary data (std::uint8_t) types.");
static_assert(!ParsedOptions::HasVersionsRange,
"comms::option::ExistsBetweenVersions (or similar) option is not applicable to ArrayList field");
static_assert(!ParsedOptions::HasInvalidByDefault,
"comms::option::InvalidByDefault option is not applicable to ArrayList field");
};
/// @brief Equivalence comparison operator.
/// @details Performs lexicographical compare of two array fields.
/// @param[in] field1 First field.
/// @param[in] field2 Second field.
/// @return true in case first field is less than second field.
/// @related ArrayList
template <typename TFieldBase, typename TElement, typename... TOptions>
bool operator<(
const ArrayList<TFieldBase, TElement, TOptions...>& field1,
const ArrayList<TFieldBase, TElement, TOptions...>& field2)
{
return std::lexicographical_compare(
field1.value().begin(), field1.value().end(),
field2.value().begin(), field2.value().end());
}
/// @brief Non-equality comparison operator.
/// @param[in] field1 First field.
/// @param[in] field2 Second field.
/// @return true in case fields are NOT equal, false otherwise.
/// @related ArrayList
template <typename TFieldBase, typename TElement, typename... TOptions>
bool operator!=(
const ArrayList<TFieldBase, TElement, TOptions...>& field1,
const ArrayList<TFieldBase, TElement, TOptions...>& field2)
{
return (field1 < field2) || (field2 < field1);
}
/// @brief Equality comparison operator.
/// @param[in] field1 First field.
/// @param[in] field2 Second field.
/// @return true in case fields are equal, false otherwise.
/// @related ArrayList
template <typename TFieldBase, typename TElement, typename... TOptions>
bool operator==(
const ArrayList<TFieldBase, TElement, TOptions...>& field1,
const ArrayList<TFieldBase, TElement, TOptions...>& field2)
{
return !(field1 != field2);
}
/// @brief Compile time check function of whether a provided type is any
/// variant of comms::field::ArrayList.
/// @tparam T Any type.
/// @return true in case provided type is any variant of @ref ArrayList
/// @related comms::field::ArrayList
template <typename T>
constexpr bool isArrayList()
{
return std::is_same<typename T::Tag, tag::ArrayList>::value;
}
/// @brief Upcast type of the field definition to its parent comms::field::ArrayList type
/// in order to have access to its internal types.
/// @related comms::field::ArrayList
template <typename TFieldBase, typename TElement, typename... TOptions>
inline
ArrayList<TFieldBase, TElement, TOptions...>&
toFieldBase(ArrayList<TFieldBase, TElement, TOptions...>& field)
{
return field;
}
/// @brief Upcast type of the field definition to its parent comms::field::ArrayList type
/// in order to have access to its internal types.
/// @related comms::field::ArrayList
template <typename TFieldBase, typename TElement, typename... TOptions>
inline
const ArrayList<TFieldBase, TElement, TOptions...>&
toFieldBase(const ArrayList<TFieldBase, TElement, TOptions...>& field)
{
return field;
}
} // namespace field
} // namespace comms
|
[
"niklas.hauser@rwth-aachen.de"
] |
niklas.hauser@rwth-aachen.de
|
d69c6db72b6012f6652c6e9267d192c01d8b3b4e
|
8e28be5cc8af1fd494ae44174b0a1e7692d2673f
|
/robot/src-ori/RobotSystem.h
|
0f938bf8b4723f325d73d85b02684d45517f240c
|
[] |
no_license
|
xiaochun-yang/19-ID
|
e10a17964aa7291deed991b453bc2ab565140b88
|
e446b1fa8bdbcbe4ae13aca439cc807faaae74ac
|
refs/heads/master
| 2021-05-26T07:46:29.105890
| 2019-01-08T20:34:28
| 2019-01-08T20:34:28
| 127,952,810
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,615
|
h
|
#ifndef __ROBOT_SYSTEM_H__
#define __ROBOT_SYSTEM_H__
#include "xos.h"
#include "DcsMessageManager.h"
#include "DcsMessageService.h"
#include "RobotService.h"
#include "activeObject.h"
#include "DcsConfig.h"
#include <string>
class CRobotSystem: public Observer
{
public:
CRobotSystem();
~CRobotSystem();
void RunFront( ); //will block until signal by other thread through OnStop()
void OnStop( );
//implement Observer
virtual void ChangeNotification( activeObject* pSubject );
// static CRobotSystem* getInstance();
// bool loadProperties(const std::string& name);
// const DcsConfig& getConfig() const
// {
// return m_config;
// }
private:
//help function
BOOL WaitAllStart( );
void WaitAllStop( );
BOOL OnInit( );
void Cleanup( );
////////////////////////////////////DATA////////////////////
private:
//create managers first
DcsMessageManager m_MsgManager;
//create services
DcsMessageService m_DcsServer;
RobotService m_RobotServer;
//wait signal to quit
xos_event_t m_EvtStop;
int m_FlagStop;
//to wait both console and message service to start and stop
xos_semaphore_t m_SemWaitStatus;
activeObject::Status volatile m_DcsStatus;
activeObject::Status volatile m_RobotStatus;
// DcsConfig m_config;
};
#endif //#ifndef __ROBOT_SYSTEM_H__
|
[
"root@yangxc.(none)"
] |
root@yangxc.(none)
|
2576de9d880446a5456eda28e35e396468852ba6
|
6fd7591f7911dbe7a31c0af14f94ba009f1f23cb
|
/NumberGuessingGame/util.h
|
73b4386508d697db7aaba51d62cb7b807b083db2
|
[] |
no_license
|
RichardMSullivan/TerminalGame
|
bdd481401442c991e097c38316691581edb0bda3
|
b341cc74c8640ff0916a5a8e5afa0dd106f01419
|
refs/heads/master
| 2020-03-29T22:57:40.075936
| 2018-10-08T07:49:01
| 2018-10-08T07:49:01
| 150,449,690
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 157
|
h
|
#ifndef UTIL_H
#define UTIL_H
int checkInRange(int guess, int MIN, int MAX);
int strToNum(std::string string);
int randomNum( int MIN, int MAX );
#endif
|
[
"richard.sullivan2@g.austincc.edu"
] |
richard.sullivan2@g.austincc.edu
|
7d5f82629ef70061fe92747e2188fe097e9822db
|
314314c74fc749f3224bcb33a477c2bdeb260cd2
|
/src/appleseedmaya/exporters/shadingnetworkexporter.h
|
df7b34437eaa1771bf8e7a587d7bf6c065a2bfc0
|
[
"MIT"
] |
permissive
|
nyue/appleseed-maya2
|
aabbc35ace375cf2371369dd1d2f234bc4402a13
|
9f3db31cde58dc65296c3895fef04b328b39f5d5
|
refs/heads/master
| 2020-06-14T20:10:43.320103
| 2016-11-30T17:31:17
| 2016-11-30T17:31:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,243
|
h
|
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2016 Esteban Tovagliari, The appleseedhq Organization
//
// 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 APPLESEED_MAYA_EXPORTERS_SHADING_NETWORK_EXPORTER_H
#define APPLESEED_MAYA_EXPORTERS_SHADING_NETWORK_EXPORTER_H
// Standard headers.
#include <set>
// Maya headers.
#include <maya/MPlug.h>
// appleseed.renderer headers.
#include "renderer/api/shadergroup.h"
// appleseed.maya headers.
#include "appleseedmaya/exporters/mpxnodeexporter.h"
#include "appleseedmaya/shadingnoderegistry.h"
#include "appleseedmaya/utils.h"
class ShadingNetworkExporter
: public MPxNodeExporter
{
public:
enum Context
{
SurfaceContext,
DisplacementContext
};
MString shaderGroupName() const;
virtual void createEntity(const AppleseedSession::Options& options);
virtual void flushEntity();
private:
friend class ShadingEngineExporter;
ShadingNetworkExporter(
const Context context,
const MObject& object,
renderer::Project& project,
AppleseedSession::SessionMode sessionMode);
void exportShader(const MObject& node);
void exportAttributeValue(
const MPlug& plug,
const OSLParamInfo& paramInfo,
renderer::ParamArray& shaderParams);
void exportArrayAttributeValue(
const MPlug& plug,
const OSLParamInfo& paramInfo,
renderer::ParamArray& shaderParams);
void exportConnections(const MObject& node);
void createCompoundChildConnectionAdapterShader(
const MPlug& plug,
const OSLParamInfo& paramInfo);
Context m_context;
AppleseedEntityPtr<renderer::ShaderGroup> m_shaderGroup;
std::set<MString, MStringCompareLess> m_shadersExported;
size_t m_numAdaptersCreated;
};
typedef boost::shared_ptr<ShadingNetworkExporter> ShadingNetworkExporterPtr;
#endif // !APPLESEED_MAYA_EXPORTERS_SHADING_ENGINE_EXPORTER_H
|
[
"ramenhdr@gmail.com"
] |
ramenhdr@gmail.com
|
e348a81aad280ba10d8fe7579ecb459375e24727
|
cfe48cd7ac1ec158e389d8c821c8ffaa37265f38
|
/aeda1920_fp10/Tests/caixa.cpp
|
0464c973786398f579b28cbf7b553fddc5c29445
|
[] |
no_license
|
goncaloacteixeira/feup-aeda
|
b2e69cad54149d851b11c8800c78a21b15ba7b41
|
33a39f023a704f2536a49647d5988ed85af599c8
|
refs/heads/master
| 2023-08-18T10:05:22.592545
| 2020-01-13T18:49:35
| 2020-01-13T18:49:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,290
|
cpp
|
#include "caixa.h"
#include <sstream>
Objeto::Objeto(unsigned idObj, unsigned pesoObj): id(idObj), peso(pesoObj)
{}
unsigned Objeto::getID() const {
return id;
}
unsigned Objeto::getPeso() const {
return peso;
}
Caixa::Caixa(unsigned cap): id(ultimoId++), capacidade(cap), cargaLivre(cap)
{}
unsigned Caixa::getID() const {
return id;
}
unsigned Caixa::getCargaLivre() const {
return cargaLivre;
}
void Caixa::addObjeto(Objeto& obj) {
cargaLivre -= obj.getPeso();
objetos.push(obj);
}
void Caixa::resetID(){
ultimoId = 1;
}
unsigned Caixa::getSize() const {
return objetos.size();
}
ostream& operator<<(ostream& os, Objeto obj) {
os << "O" << obj.id << ": " << obj.peso;
return os;
}
unsigned Caixa::ultimoId = 1;
bool Objeto::operator<(const Objeto& o1) const {
return this->getPeso() < o1.getPeso();
}
bool Caixa::operator<(const Caixa& c1) const {
return this->getCargaLivre() > c1.getCargaLivre();
}
string Caixa::imprimeConteudo() const {
if (!this->objetos.empty()) {
stringstream ss;
ss << "C" << this->id << "[ ";
STACK_OBJS copy = objetos;
while (!copy.empty()) {
ss << copy.top() << " ";
copy.pop();
}
ss << "]";
return ss.str();
}
return "Caixa " + to_string(this->id) + " vazia!\n";
}
|
[
"Teixeira_2000"
] |
Teixeira_2000
|
3aab77ca920114001af534f7da15fd33304d438b
|
80b6e0535ed5bfb54e64c4aa37df233b71053511
|
/View/ViewContext/TreeView.cpp
|
9a8d8f3307fd9f774cbec2e28e56c54393fb2399
|
[] |
no_license
|
IRETD/TestSystemStudent
|
4911cf6ba298499c7a6e92988baf194dba86c66c
|
2b4140ee9476fb9786357271fe310fe34c388d81
|
refs/heads/master
| 2021-09-10T02:49:55.220737
| 2018-03-20T19:44:51
| 2018-03-20T19:44:51
| 126,067,097
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,027
|
cpp
|
#include "TreeView.h"
#include <Enum/View/ViewContext/DisciplineView/DisciplineViewIconSize.h>
#include <QHeaderView>
TreeView::TreeView( ViewContextType viewContextType ) : ViewContext( viewContextType ) {
setIconSize( QSize( DisciplineViewIconSize::WIDTH,
DisciplineViewIconSize::HEGITH ) );
header() -> resizeSections( QHeaderView::ResizeToContents );
}
QWidget *TreeView::getViewWidget() {
return this;
}
void TreeView::createConnections() {
connect( this,
&QTreeView::doubleClicked,
m_p_Model -> getDisciplineModel().data(),
&TreeStandartItemBaseModel::modelItemSelected
);
connect ( this,
&QTreeView::expanded,
m_p_Model -> getDisciplineModel().data(),
&TreeStandartItemBaseModel::itemIsExpanded );
connect ( this,
&QTreeView::collapsed,
m_p_Model -> getDisciplineModel().data(),
&TreeStandartItemBaseModel::itemIsCollapsed );
}
|
[
"zanzarah92@gmail.com"
] |
zanzarah92@gmail.com
|
8550d9762b9fc92c89e56c5dd8fce556953c1a1b
|
15b30861877807094a5974ab892c72d25e487d19
|
/database/field_names.cpp
|
c2721d8652f7afd93a93bb10c110c5d7d5a0a97d
|
[] |
no_license
|
LuaxY/Linxemu
|
0a4775b5d3273b5a56f622fbf6132b688f842ca0
|
407f4024c523657b826fd62dc783483393f80544
|
refs/heads/master
| 2016-09-06T13:32:57.339527
| 2013-08-21T14:30:58
| 2013-08-21T14:30:58
| 17,882,652
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,010
|
cpp
|
/***********************************************************************
field_names.cpp - Implements the FieldNames class.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and
(c) 2004-2010 by Educational Technology Resources, Inc. Others may
also hold copyrights on code in this file. See the CREDITS.txt file
in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
MySQL++ is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public
License along with MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#define MYSQLPP_NOT_HEADER
#include "common.h"
#include "field_names.h"
#include "result.h"
#include <algorithm>
namespace mysqlpp
{
namespace internal
{
extern void str_to_lwr(std::string& s);
}
void
FieldNames::init(const ResultBase* res)
{
size_t num = res->num_fields();
reserve(num);
for (size_t i = 0; i < num; i++)
{
push_back(res->fields().at(i).name());
}
}
unsigned int
FieldNames::operator [](const std::string& s) const
{
std::string temp1(s);
internal::str_to_lwr(temp1);
for (const_iterator it = begin(); it != end(); ++it)
{
std::string temp2(*it);
internal::str_to_lwr(temp2);
if (temp2.compare(temp1) == 0)
{
return it - begin();
}
}
return end() - begin();
}
} // end namespace mysqlpp
|
[
"yann.guineau@gmail.com"
] |
yann.guineau@gmail.com
|
9c0425aa75c9db05a355bbf976bb76ebe39d04ed
|
8e567498a9224d7c6bf71cfe66ec5360e056ec02
|
/mars/boost/range/algorithm/equal_range.hpp
|
a6ac171d966e288bf45db928484e5aa7ffac812c
|
[
"MIT",
"Zlib",
"LicenseRef-scancode-unknown-license-reference",
"OpenSSL",
"BSD-3-Clause",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"BSL-1.0",
"Apache-2.0",
"BSD-2-Clause"
] |
permissive
|
Tencent/mars
|
db31afeeb5c0325bfceede594038381bce3c1635
|
6c7028fffe01e2b49a66c221b1ac2f548649053f
|
refs/heads/master
| 2023-08-31T07:29:50.430084
| 2023-08-09T07:24:42
| 2023-08-09T07:24:42
| 76,222,419
| 18,118
| 3,828
|
NOASSERTION
| 2023-09-12T07:37:07
| 2016-12-12T04:39:54
|
C++
|
UTF-8
|
C++
| false
| false
| 2,963
|
hpp
|
// Copyright Neil Groves 2009. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_ALGORITHM_EQUAL_RANGE_HPP_INCLUDED
#define BOOST_RANGE_ALGORITHM_EQUAL_RANGE_HPP_INCLUDED
#include <boost/concept_check.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/concepts.hpp>
#include <algorithm>
namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost
{
namespace range
{
/// \brief template function equal_range
///
/// range-based version of the equal_range std algorithm
///
/// \pre ForwardRange is a model of the ForwardRangeConcept
/// \pre SortPredicate is a model of the BinaryPredicateConcept
template<class ForwardRange, class Value>
inline std::pair<
BOOST_DEDUCED_TYPENAME mars_boost::range_iterator<ForwardRange>::type,
BOOST_DEDUCED_TYPENAME mars_boost::range_iterator<ForwardRange>::type
>
equal_range(ForwardRange& rng, const Value& val)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<ForwardRange> ));
return std::equal_range(mars_boost::begin(rng), mars_boost::end(rng), val);
}
/// \overload
template<class ForwardRange, class Value>
inline std::pair<
BOOST_DEDUCED_TYPENAME mars_boost::range_iterator<const ForwardRange>::type,
BOOST_DEDUCED_TYPENAME mars_boost::range_iterator<const ForwardRange>::type
>
equal_range(const ForwardRange& rng, const Value& val)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> ));
return std::equal_range(mars_boost::begin(rng), mars_boost::end(rng), val);
}
/// \overload
template<class ForwardRange, class Value, class SortPredicate>
inline std::pair<
BOOST_DEDUCED_TYPENAME mars_boost::range_iterator<ForwardRange>::type,
BOOST_DEDUCED_TYPENAME mars_boost::range_iterator<ForwardRange>::type
>
equal_range(ForwardRange& rng, const Value& val, SortPredicate pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<ForwardRange> ));
return std::equal_range(mars_boost::begin(rng), mars_boost::end(rng), val, pred);
}
/// \overload
template<class ForwardRange, class Value, class SortPredicate>
inline std::pair<
BOOST_DEDUCED_TYPENAME mars_boost::range_iterator<const ForwardRange>::type,
BOOST_DEDUCED_TYPENAME mars_boost::range_iterator<const ForwardRange>::type
>
equal_range(const ForwardRange& rng, const Value& val, SortPredicate pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> ));
return std::equal_range(mars_boost::begin(rng), mars_boost::end(rng), val, pred);
}
} // namespace range
using range::equal_range;
} // namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost
#endif // include guard
|
[
"garryyan@tencent.com"
] |
garryyan@tencent.com
|
09086a30a8080d91171f35147baabc84181564a5
|
b8f5694f4b31d6414d340b55808aea5106a3dad5
|
/xcore/xcam_mutex.h
|
ee6780b2ce8f0cac565028c668b863c63984f9c4
|
[
"Apache-2.0"
] |
permissive
|
wenqingfu/libxcam
|
ae69e123df12802ab3a2f1162873e2bf23e6d78d
|
8873f20503e40bda79666131c36203fb8887e6c8
|
refs/heads/master
| 2020-12-25T08:37:33.484311
| 2016-09-12T00:09:04
| 2016-09-12T00:09:04
| 32,378,292
| 0
| 0
| null | 2015-03-17T07:35:16
| 2015-03-17T07:35:14
|
C++
|
UTF-8
|
C++
| false
| false
| 2,319
|
h
|
/*
* xcam_mutex.h - Lock
*
* Copyright (c) 2014 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Wind Yuan <feng.yuan@intel.com>
*/
#ifndef XCAM_MUTEX_H
#define XCAM_MUTEX_H
#include "xcam_utils.h"
#include <pthread.h>
#include <sys/time.h>
namespace XCam {
class Mutex {
friend class Cond;
private:
XCAM_DEAD_COPY (Mutex);
public:
Mutex () {
pthread_mutex_init (&_mutex, NULL);
}
virtual ~Mutex () {
pthread_mutex_destroy (&_mutex);
}
void lock() {
pthread_mutex_lock (&_mutex);
}
void unlock() {
pthread_mutex_unlock (&_mutex);
}
private:
pthread_mutex_t _mutex;
};
class Cond {
private:
XCAM_DEAD_COPY (Cond);
public:
Cond () {
pthread_cond_init (&_cond, NULL);
}
~Cond () {
pthread_cond_destroy (&_cond);
}
int wait (Mutex &mutex) {
return pthread_cond_wait (&_cond, &mutex._mutex);
}
int timedwait (Mutex &mutex, uint32_t time_in_us) {
struct timeval now;
struct timespec abstime;
gettimeofday (&now, NULL);
now.tv_usec += time_in_us;
abstime.tv_sec += now.tv_sec + now.tv_usec / 1000000;
abstime.tv_nsec = (now.tv_usec % 1000000) * 1000;
return pthread_cond_timedwait (&_cond, &mutex._mutex, &abstime);
}
int signal() {
return pthread_cond_signal (&_cond);
}
int broadcast() {
return pthread_cond_broadcast (&_cond);
}
private:
pthread_cond_t _cond;
};
class SmartLock {
private:
XCAM_DEAD_COPY (SmartLock);
public:
SmartLock (XCam::Mutex &mutex): _mutex(mutex) {
_mutex.lock();
}
virtual ~SmartLock () {
_mutex.unlock();
}
private:
XCam::Mutex &_mutex;
};
};
#endif //XCAM_MUTEX_H
|
[
"feng.yuan@intel.com"
] |
feng.yuan@intel.com
|
f6785ca63b503e995a710ad9cc19a9b0f8d6316d
|
d64737d31ae9caba2820ea1048be3f9bce708b42
|
/cpp/linked-list-cycle.cpp
|
d1864bf8ff63ab8fa8e2faee7534aa82178b1608
|
[] |
no_license
|
ldcduc/leetcode-training
|
2453ec13e69160bc29e8e516e19544c2b25bf945
|
40db37375372f14dd45d0a069c8b86fe36221f09
|
refs/heads/master
| 2023-08-05T01:46:52.993542
| 2021-09-18T16:47:54
| 2021-09-18T16:47:54
| 271,736,046
| 9
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 838
|
cpp
|
/* Problem url: https://leetcode.com/problems/linked-list-cycle
* Code by: ldcduc
* */
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* node1 = head, * node2 = head;
if (head == NULL) {
return false;
}
while (true) {
if (node1->next == NULL || node2->next == NULL || node2->next->next == NULL) {
break;
}
node1 = node1->next;
node2 = node2->next->next;
if (node1 == node2) {
return true;
}
}
return false;
}
};
/*
* Comment by ldcduc
* Suggested tags: linked list, fun, easy
*
* */
|
[
"ldcduc@apcs.vn"
] |
ldcduc@apcs.vn
|
5af0e4abfd6f1ae4f2604b96834f841f339dd055
|
b296af8325e1964e8c1d82d74bfc4d84fcd49feb
|
/Classes/ui_layer.cpp
|
afdcb186233661eb2f5f38523fc4e19569da84d1
|
[] |
no_license
|
jj918160/GreatMonster
|
3c0f8c53e2652a0cd41968e83763c9237050a7a8
|
fda2989d0f370c0aefa184c21c277d1a43ac3086
|
refs/heads/master
| 2016-09-13T05:34:25.446673
| 2016-04-25T00:04:16
| 2016-04-25T00:04:16
| 56,599,046
| 0
| 1
| null | 2016-04-24T12:49:27
| 2016-04-19T13:27:48
|
Java
|
UTF-8
|
C++
| false
| false
| 7,308
|
cpp
|
//
// ui_layer.cpp
// 3D_fight
//
// Created by mac on 15-10-7.
//
//
#include "ui_layer.h"
#include "City_layer.h"
#include "GameScene.h"
#include "Charecter1.h"
#include "SimpleAudioEngine.h"
using namespace CocosDenshion;
int ui_layer::fight_fit=0;
bool ui_layer::init()
{
if ( !Layer::init() )
{
return false;
}
SimpleAudioEngine::getInstance()->playBackgroundMusic("voice/048.mp3",true);
SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(0.2);
SimpleAudioEngine::getInstance()->setEffectsVolume(1.f);
run=false;
deltax=0.f;
deltaz=0.f;
rokerPosition=Vec2(200,150);
Sprite *spRockerBG=CCSprite::create("CG-1086.png");
spRockerBG->setPosition(rokerPosition);
spRockerBG->setOpacity(50);
addChild(spRockerBG,1);
rockerBGR=spRockerBG->getContentSize().width*0.5;
auto spRockerF = Sprite::create("CG-7005.png");
spRockerF->setPosition(rokerPosition);
addChild(spRockerF, 2,1);
auto attlistener=EventListenerTouchOneByOne::create();
attlistener->onTouchBegan=[=](Touch*touch,Event*event){
auto target=static_cast<Sprite*>(event->getCurrentTarget());
Vec2 locationInNode=target->convertToNodeSpace(touch->getLocation());
Size s=target->getContentSize();//点到判断碰撞
Rect rect=Rect(0,0,s.width,s.height);
if (rect.containsPoint(locationInNode)) {
ui_layer::fight_fit=0;
City_layer*gm=(City_layer*)this->getParent()->getChildByTag(1);
Charecter1*spp=static_cast<Charecter1*>(gm->getChildByTag(9));
if (run)
{
spp->run();
SimpleAudioEngine::getInstance()->playEffect("voice/runn.wav",true,0.6f);
}
else
{
spp->walk();
SimpleAudioEngine::getInstance()->playEffect("voice/walk.wav",true,0.6f);
}
return true;
}
return false;
};
attlistener->onTouchMoved=[&](Touch*touch,Event*event){
Vec2 point=touch->getLocation();
auto target=static_cast<Sprite*>(event->getCurrentTarget());
if (sqrt(pow((rokerPosition.x-point.x),2)+pow((rokerPosition.y-point.y),2))>=rockerBGR){
float angle=getRad(point);
target->setPosition(ccpAdd(getAnglePosition(rockerBGR, angle),rokerPosition));
}else{
target->setPosition(target->getPosition()+touch->getDelta());
}
float px=point.x-rokerPosition.x;
float pz=point.y-rokerPosition.y;
Vec2 temp=Vec2(px,pz);
temp.normalize();
deltax=temp.x;
deltaz=-temp.y;
//玩家变向
City_layer*gm=(City_layer*)this->getParent()->getChildByTag(1);
float dx=deltax*cos(gm->_rotation)+deltaz*sin(gm->_rotation);
float dy=-deltax*sin(gm->_rotation)+deltaz*cos(gm->_rotation);
if (dy<=0) {
gm->_firstrotation=-CC_RADIANS_TO_DEGREES(asin(dx))-90;
}
else{
gm->_firstrotation=CC_RADIANS_TO_DEGREES(asin(dx))+90;
}
gm->getChildByTag(9)->setRotation3D(Vec3(0,gm->_firstrotation-90,0));
};
attlistener->onTouchEnded=[&](Touch*touch,Event*event){
Sprite *spRockerF=(Sprite*)this->getChildByTag(1);
// spRockerF->runAction(CCMoveTo::create(0.05, rokerPosition));
spRockerF->setPosition(rokerPosition);
deltax=0;
deltaz=0;
City_layer*gm=(City_layer*)this->getParent()->getChildByTag(1);
Charecter1*spp=(Charecter1*)gm->getChildByTag(9);
spp->stand();
SimpleAudioEngine::getInstance()->stopAllEffects();
};
attlistener->setSwallowTouches(true);
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(attlistener,spRockerF);
// auto item=MenuItemImage::create("CG-1492.png", "CG-1493.png", CC_CALLBACK_1(ui_layer::callback2,this));
// item->setPosition(100,600);
//
//
// auto item2=MenuItemImage::create("CG-1487.png", "CG-1486.png", CC_CALLBACK_1(ui_layer::changeCamera,this));
// item2->setPosition(860,600);
//
auto item=MenuItemImage::create("att1.png", "att2.png", CC_CALLBACK_1(ui_layer::attack,this));
item->setPosition(800,150);
//
auto tol=MenuItemToggle::createWithCallback(CC_CALLBACK_1(ui_layer::is_run,this),
MenuItemImage::create("CG-1494.png", "CG-1494.png"),
MenuItemImage::create("CG-1493.png", "CG-1493.png"),
NULL);
tol->setPosition(50,600);
//
auto menu=Menu::create(item,tol,NULL);
menu->setPosition(0,0);
this->addChild(menu);
auto sp_hp=Sprite::create("CG-1087.png");
auto hp=ProgressTimer::create(sp_hp);
hp->setType(ProgressTimer::Type::BAR);
hp->setPercentage(Charecter1::_hp*2);
hp->setPosition(820,620);
hp->setMidpoint(Vec2(1,0));
hp->setBarChangeRate(Vec2(1,0));
addChild(hp,0,10);
char text[64];
sprintf(text,"%d/50", Charecter1::_hp);
auto hp_str=Label::createWithBMFont("bitmapFontTest.fnt", text);
hp_str->setPosition(820,580);
addChild(hp_str,0,9);
scheduleUpdate();
return true;
}
void ui_layer::update(float dt)
{
auto hp=(ProgressTimer*)this->getChildByTag(10);
hp->setPercentage(Charecter1::_hp*2);
char text[64];
sprintf(text,"%d/50", Charecter1::_hp);
auto hp_text=(Label*)this->getChildByTag(9);
hp_text->setString(text);
}
float ui_layer::getRad(Vec2 pos1){
float px1=pos1.x;
float py1=pos1.y;
float x=px1-rokerPosition.x;
float y=py1-rokerPosition.y;
float xie=sqrt(pow(x,2)+pow(y,2));
float cosAngle=x/xie;
float rad=acos(cosAngle);
if (py1<rokerPosition.y) {
rad=-rad;
}
return rad;
}
Vec2 ui_layer::getAnglePosition(float r,float angle){
return Vec2(r*cos(angle),r*sin(angle));
}
//void ui_layer::changeCamera(Ref* psender){
// GameLayer*gm=(GameLayer*)this->getParent()->getChildByTag(1);
// gm->pCamera_I->setCameraFlag(CameraFlag::USER1);
// gm->pCamera_III->setCameraFlag(CameraFlag::USER2);
// gm->firstperson=true;
// //this->getScene()->setPhysics3DDebugCamera(gm->pCamera_I);
//}
//
//void ui_layer::callback2(Ref* psender){
// GameLayer*gm=(GameLayer*)this->getParent()->getChildByTag(1);
// gm->pCamera_I->setCameraFlag(CameraFlag::USER2);
// gm->pCamera_III->setCameraFlag(CameraFlag::USER1);
// gm->firstperson=false;
// float deltax=200*sin(gm->rotation);//x增量
// float deltaz=200*cos(gm->rotation);//z增量
// gm->pCamera_III->setPosition3D(gm->pla->getChildByTag(2)->getPosition3D()+Vec3(deltax,110,deltaz));
// gm->pCamera_III->lookAt(gm->pla->getChildByTag(2)->getPosition3D());
// // this->getScene()->setPhysics3DDebugCamera(gm->pCamera_III);
//}
void ui_layer::attack(Ref* psender)
{
fight_fit++;
City_layer*gm=(City_layer*)this->getParent()->getChildByTag(1);
Charecter1*spp=(Charecter1*)gm->getChildByTag(9);
spp->attack_1();
}
void ui_layer::is_run(Ref*psender){
run=!run;
}
|
[
"446413497@qq.com"
] |
446413497@qq.com
|
94f4f8fac42cf9db0fe0997f236565f4f16e43b1
|
1b9a32ea5f2492fd3512965f92e0f057b0528d33
|
/rotate_image.cpp
|
b154422e3dc40e0f504b8532233f18513466bd36
|
[] |
no_license
|
shivangigoel1302/leetcode_solutions
|
a459a4279ffcfa889cf1fe0e8eb681e4e79186b6
|
3373f9710bd797bcda5cbd86958e8914ba9e2a15
|
refs/heads/master
| 2023-08-23T04:18:26.678630
| 2021-11-01T14:57:21
| 2021-11-01T14:57:21
| 274,206,300
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,788
|
cpp
|
class Solution {
public:
void rotate(vector<vector<int>>&matrix) {
int n=matrix.size();
if(n%2!=0)
{
for(int i=0;i<n-1;i++)
{
for(int j=i;j<n-i-1;j++)
{
for(int k=0;k<3;k++)
{
if(k==0)
{
swap(matrix[i][j],matrix[n-1-j][i]);
}
else if(k==1)
{
swap(matrix[n-1-j][i],matrix[n-i-1][n-1-j]);
}
else if(k==2)
{
swap(matrix[n-i-1][n-1-j],matrix[j][n-i-1]);
}
}
}
}
}
else
{
for(int i=0;i<n-1;i++)
{
for(int j=i;j<n-1-i;j++)
{
if(j==(n/2)-1&&i==(n/2)-1)
{
break;
}
for(int k=0;k<3;k++)
{
if(k==0)
{
swap(matrix[i][j],matrix[n-1-j][i]);
}
else if(k==1)
{
swap(matrix[n-1-j][i],matrix[n-i-1][n-1-j]);
}
else if(k==2)
{
swap(matrix[n-i-1][n-1-j],matrix[j][n-i-1]);
}
}
}
}
int key=matrix[(n/2)-1][(n/2)-1];
matrix[(n/2)-1][(n/2)-1]=matrix[n/2][(n/2)-1];
matrix[(n/2)][(n/2)-1]=matrix[n/2][n/2];
matrix[n/2][n/2]=matrix[(n/2)-1][(n/2)];
matrix[(n/2)-1][(n/2)]=key;
}
}
};
|
[
"shivangigoel1301@gmail.com"
] |
shivangigoel1301@gmail.com
|
1c515369c243ba9a580ea9712a9ac62a5f9ae4c7
|
78918391a7809832dc486f68b90455c72e95cdda
|
/boost_lib/boost/python/object/value_holder.hpp
|
55d305b69afdd6b9210923155eefeb8ebac5e62a
|
[
"MIT"
] |
permissive
|
kyx0r/FA_Patcher
|
50681e3e8bb04745bba44a71b5fd04e1004c3845
|
3f539686955249004b4483001a9e49e63c4856ff
|
refs/heads/master
| 2022-03-28T10:03:28.419352
| 2020-01-02T09:16:30
| 2020-01-02T09:16:30
| 141,066,396
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,782
|
hpp
|
#if !defined(BOOST_PP_IS_ITERATING)
// Copyright David Abrahams 2001.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
# ifndef VALUE_HOLDER_DWA20011215_HPP
# define VALUE_HOLDER_DWA20011215_HPP
# include <boost/python/object/value_holder_fwd.hpp>
# include <boost/python/instance_holder.hpp>
# include <boost/python/type_id.hpp>
# include <boost/python/wrapper.hpp>
# include <boost/python/object/inheritance_query.hpp>
# include <boost/python/object/forward.hpp>
# include <boost/python/detail/force_instantiate.hpp>
# include <boost/python/detail/preprocessor.hpp>
# include <boost/preprocessor/comma_if.hpp>
# include <boost/preprocessor/enum_params.hpp>
# include <boost/preprocessor/iterate.hpp>
# include <boost/preprocessor/repeat.hpp>
# include <boost/preprocessor/debug/line.hpp>
# include <boost/preprocessor/repetition/enum_params.hpp>
# include <boost/preprocessor/repetition/enum_binary_params.hpp>
# include <boost/utility/addressof.hpp>
namespace boost
{
namespace python
{
namespace objects
{
#define BOOST_PYTHON_UNFORWARD_LOCAL(z, n, _) BOOST_PP_COMMA_IF(n) objects::do_unforward(a##n,0)
template <class Value>
struct value_holder : instance_holder
{
typedef Value held_type;
typedef Value value_type;
// Forward construction to the held object
# define BOOST_PP_ITERATION_PARAMS_1 (4, (0, BOOST_PYTHON_MAX_ARITY, <boost/python/object/value_holder.hpp>, 1))
# include BOOST_PP_ITERATE()
private: // required holder implementation
void* holds(type_info, bool null_ptr_only);
template <class T>
inline void* holds_wrapped(type_info dst_t, wrapper<T>*,T* p)
{
return python::type_id<T>() == dst_t ? p : 0;
}
inline void* holds_wrapped(type_info, ...)
{
return 0;
}
private: // data members
Value m_held;
};
template <class Value, class Held>
struct value_holder_back_reference : instance_holder
{
typedef Held held_type;
typedef Value value_type;
// Forward construction to the held object
# define BOOST_PP_ITERATION_PARAMS_1 (4, (0, BOOST_PYTHON_MAX_ARITY, <boost/python/object/value_holder.hpp>, 2))
# include BOOST_PP_ITERATE()
private: // required holder implementation
void* holds(type_info, bool null_ptr_only);
private: // data members
Held m_held;
};
# undef BOOST_PYTHON_UNFORWARD_LOCAL
template <class Value>
void* value_holder<Value>::holds(type_info dst_t, bool /*null_ptr_only*/)
{
if (void* wrapped = holds_wrapped(dst_t, boost::addressof(m_held), boost::addressof(m_held)))
return wrapped;
type_info src_t = python::type_id<Value>();
return src_t == dst_t ? boost::addressof(m_held)
: find_static_type(boost::addressof(m_held), src_t, dst_t);
}
template <class Value, class Held>
void* value_holder_back_reference<Value,Held>::holds(
type_info dst_t, bool /*null_ptr_only*/)
{
type_info src_t = python::type_id<Value>();
Value* x = &m_held;
if (dst_t == src_t)
return x;
else if (dst_t == python::type_id<Held>())
return &m_held;
else
return find_static_type(x, src_t, dst_t);
}
}
}
} // namespace boost::python::objects
# endif // VALUE_HOLDER_DWA20011215_HPP
// --------------- value_holder ---------------
// For gcc 4.4 compatability, we must include the
// BOOST_PP_ITERATION_DEPTH test inside an #else clause.
#else // BOOST_PP_IS_ITERATING
#if BOOST_PP_ITERATION_DEPTH() == 1 && BOOST_PP_ITERATION_FLAGS() == 1
# if !(BOOST_WORKAROUND(__MWERKS__, > 0x3100) \
&& BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3201)))
# line BOOST_PP_LINE(__LINE__, value_holder.hpp(value_holder))
# endif
# define N BOOST_PP_ITERATION()
# if (N != 0)
template <BOOST_PP_ENUM_PARAMS_Z(1, N, class A)>
# endif
value_holder(
PyObject* self BOOST_PP_COMMA_IF(N) BOOST_PP_ENUM_BINARY_PARAMS_Z(1, N, A, a))
: m_held(
BOOST_PP_REPEAT_1ST(N, BOOST_PYTHON_UNFORWARD_LOCAL, nil)
)
{
python::detail::initialize_wrapper(self, boost::addressof(this->m_held));
}
# undef N
// --------------- value_holder_back_reference ---------------
#elif BOOST_PP_ITERATION_DEPTH() == 1 && BOOST_PP_ITERATION_FLAGS() == 2
# if !(BOOST_WORKAROUND(__MWERKS__, > 0x3100) \
&& BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3201)))
# line BOOST_PP_LINE(__LINE__, value_holder.hpp(value_holder_back_reference))
# endif
# define N BOOST_PP_ITERATION()
# if (N != 0)
template <BOOST_PP_ENUM_PARAMS_Z(1, N, class A)>
# endif
value_holder_back_reference(
PyObject* p BOOST_PP_COMMA_IF(N) BOOST_PP_ENUM_BINARY_PARAMS_Z(1, N, A, a))
: m_held(
p BOOST_PP_COMMA_IF(N)
BOOST_PP_REPEAT_1ST(N, BOOST_PYTHON_UNFORWARD_LOCAL, nil)
)
{
}
# undef N
#endif // BOOST_PP_ITERATION_DEPTH()
#endif
|
[
"k.melekhin@gmail.com"
] |
k.melekhin@gmail.com
|
86f05f74907a15eba34f59f5c4bf67db7838eefd
|
fe276f0bae62c1a762323dda3cd42f5037df3dec
|
/cppLabs/src/Img.h
|
738279cb2fd4b7a2c63c38d03b213b9ec731d5a7
|
[] |
no_license
|
vivere-dally/ppd_c-
|
503cd254f812aa54816c346919456b9858e5f932
|
6380859c37ff5e862415c4333fb658b79a871d5e
|
refs/heads/main
| 2023-01-12T16:06:16.500455
| 2020-11-07T20:20:57
| 2020-11-07T20:20:57
| 307,159,280
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 434
|
h
|
#pragma once
#include <math.h>
template <typename T>
class Img {
protected:
int get_pure_index(int index, int limit) {
int pure_index = abs(index);
if(pure_index >= limit) {
int offset = (1 + pure_index - limit) * 2;
pure_index -= offset;
}
return pure_index;
}
public:
virtual void fill_img(int* numbers) = 0;
virtual void apply_kernel(T kernel, int kernel_rows, int kernel_columns) = 0;
};
|
[
"stefanbuciujr@gmail.com"
] |
stefanbuciujr@gmail.com
|
707f00441347825551cf09b86ce01ab90726b8f2
|
56649046304376279d71bf6fd82562f7efa293ca
|
/PracSim/include/mpsk_symbtowave.h
|
55341b92734f42b3059184fa582badb11e365196
|
[] |
no_license
|
zwm152/WirelessCommSystemSimuC-Model
|
b9b3de73956caa8e872c3d36580ec863962d8ef2
|
7be3562b5a516c73f06c4090b5806ffe7319fe8a
|
refs/heads/master
| 2021-09-23T15:41:08.088030
| 2018-09-25T12:04:04
| 2018-09-25T12:04:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 898
|
h
|
//
// File = mpsk_iq_mod.h
//
#ifndef _MPSK_IQ_MOD_H_
#define _MPSK_IQ_MOD_H_
#include "signal_T.h"
#include "psmodel.h"
class MpskSymbsToQuadWaves : public PracSimModel
{
public:
MpskSymbsToQuadWaves( char* instance_nam,
PracSimModel* outer_model,
Signal<byte_t>* in_symb_seq,
Signal<float>* i_out_sig,
Signal<float>* q_out_sig,
Signal<bit_t>* symb_clock_out );
~MpskSymbsToQuadWaves(void);
void Initialize(void);
int Execute(void);
private:
int In_Block_Size;
int Out_Block_Size;
int Bits_Per_Symb;
int Num_Diff_Symbs;
int Samps_Per_Symb;
double Symb_Duration;
float *I_Compon;
float *Q_Compon;
Signal<byte_t> *In_Symb_Seq;
Signal<float> *I_Out_Sig;
Signal<float> *Q_Out_Sig;
Signal<bit_t> *Symb_Clock_Out;
Signal< std::complex<float> > *Cmpx_Out_Sig;
};
#endif
|
[
"huhaichaotd@139.com"
] |
huhaichaotd@139.com
|
0763d624e210ee68d1bd93f9fb60a4634d9f6977
|
e27580711cbf4beccbfeb3e7abfa33cac2d8c22f
|
/UVAtlas/isochart/meshcommon.inl
|
2da9986b8b41219af4a2506089bcf710d4f71f48
|
[
"MIT"
] |
permissive
|
wentingwei/UVAtlas
|
bb240fce703acb0badd8582ced98c7ce3f9bf98b
|
e46c4141a924e9390327b8e94e6e8c311070e731
|
refs/heads/master
| 2021-01-22T12:02:27.106814
| 2015-10-30T17:42:49
| 2015-10-30T17:42:49
| 45,894,296
| 1
| 0
| null | 2015-11-10T07:09:37
| 2015-11-10T07:09:37
| null |
UTF-8
|
C++
| false
| false
| 15,637
|
inl
|
//-------------------------------------------------------------------------------------
// UVAtlas - meshcommon.inl
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// http://go.microsoft.com/fwlink/?LinkID=512686
//-------------------------------------------------------------------------------------
// [SGSH02] SANDER P., GORTLER S., SNYDER J., HOPPE H.:
// Signal-specialized parameterization
// In Proceedings of Eurographics Workshop on Rendering 2002(2002)
namespace Isochart
{
/////////////////////////////////////////////////////////////
///////////////////////////Tool-Methods//////////////////////
/////////////////////////////////////////////////////////////
inline float CIsochartMesh::CaculateUVDistanceSquare(
DirectX::XMFLOAT2& v0,
DirectX::XMFLOAT2& v1) const
{
return (v0.x-v1.x)*(v0.x-v1.x) + (v0.y-v1.y)*(v0.y-v1.y);
}
// Calculate a face's area in the U-V space.
inline float CIsochartMesh::CalculateUVFaceArea(
ISOCHARTFACE& face) const
{
return CalculateUVFaceArea(
m_pVerts[face.dwVertexID[0]].uv,
m_pVerts[face.dwVertexID[1]].uv,
m_pVerts[face.dwVertexID[2]].uv);
}
// Caculate face area using cross multiplication
inline float CIsochartMesh::CalculateUVFaceArea(
DirectX::XMFLOAT2& v0,
DirectX::XMFLOAT2& v1,
DirectX::XMFLOAT2& v2) const
{
float fA = ((v1.x-v0.x)*(v2.y-v0.y)-(v2.x-v0.x)*(v1.y-v0.y))/2;
if (fA < 0)
{
fA = -fA;
}
return fA;
}
// Caculate parameterized chart's area
inline float CIsochartMesh::CalculateChart2DArea() const
{
float fChart2DArea = 0;
ISOCHARTFACE* pFace = m_pFaces;
for (size_t i=0; i<m_dwFaceNumber; i++)
{
fChart2DArea += CalculateUVFaceArea(*pFace);
pFace++;
}
return fChart2DArea;
}
// Caculate chart's 3D area
inline float CIsochartMesh::CalculateChart3DArea() const
{
float fChart3DArea = 0;
ISOCHARTFACE* pFace = m_pFaces;
for (size_t i=0; i<m_dwFaceNumber; i++)
{
fChart3DArea += m_baseInfo.pfFaceAreaArray[pFace->dwIDInRootMesh];
pFace++;
}
return fChart3DArea;
}
// Check if parameterization cause some edge overlapping.
inline HRESULT CIsochartMesh::IsParameterizationOverlapping(
CIsochartMesh* pMesh,
bool& bIsOverlapping)
{
ISOCHARTEDGE* pEdge1 = nullptr;
ISOCHARTEDGE* pEdge2 = nullptr;
// Collect all boundary edges
std::vector<ISOCHARTEDGE*> boundaryEdgeList;
try
{
for (size_t i=0; i < pMesh->m_edges.size(); i++)
{
pEdge1 = &(pMesh->m_edges[i]);
if (pEdge1->bIsBoundary)
{
boundaryEdgeList.push_back(pEdge1);
}
}
}
catch (std::bad_alloc&)
{
return E_OUTOFMEMORY;
}
assert(!boundaryEdgeList.empty());
for (size_t i=0; i < boundaryEdgeList.size()-1; i++)
{
pEdge1 = boundaryEdgeList[i];
for (size_t j=i+1; j<boundaryEdgeList.size(); j++)
{
pEdge2 = boundaryEdgeList[j];
// if two edges connect together, although they have
// intersection, it's not counted as overlapping
if (pEdge1->dwVertexID[0] == pEdge2->dwVertexID[0]
||pEdge1->dwVertexID[0] == pEdge2->dwVertexID[1]
||pEdge1->dwVertexID[1] == pEdge2->dwVertexID[0]
||pEdge1->dwVertexID[1] == pEdge2->dwVertexID[1])
{
continue;
}
// If two edges doesn't connect together, but have
// intersection, overlapping occurs.
if (IsochartIsSegmentsIntersect(
pMesh->m_pVerts[pEdge1->dwVertexID[0]].uv,
pMesh->m_pVerts[pEdge1->dwVertexID[1]].uv,
pMesh->m_pVerts[pEdge2->dwVertexID[0]].uv,
pMesh->m_pVerts[pEdge2->dwVertexID[1]].uv))
{
bIsOverlapping = true;
return S_OK;
}
}
}
bIsOverlapping = false;
return S_OK;
}
// Calculate the Euclid distance between to vertex on original mesh.
inline float CIsochartMesh::CalculateVextexDistance(
ISOCHARTVERTEX& v0, ISOCHARTVERTEX& v1) const
{
using namespace DirectX;
XMVECTOR pv0 = XMLoadFloat3(m_baseInfo.pVertPosition + v0.dwIDInRootMesh);
XMVECTOR pv1 = XMLoadFloat3(m_baseInfo.pVertPosition + v1.dwIDInRootMesh);
XMVECTOR v2 = pv1 - pv0;
return XMVectorGetX(XMVector3Length(v2));
}
// When performing canonical parameterization to each face, an origin,
// X-axis and Y-axis was specified. Using these information can compute
// the 2-D reflection of any point in 3-D face.
// ( In our algorithm, origin alwasy the first vertex of face)
inline void CIsochartMesh::Vertex3DTo2D(
uint32_t dwFaceIDInRootMesh,
const DirectX::XMFLOAT3* pOrg,
const DirectX::XMFLOAT3* p3D,
DirectX::XMFLOAT2* p2D)
{
using namespace DirectX;
XMFLOAT3* pAxisX
= m_baseInfo.pFaceCanonicalParamAxis
+ 2 * dwFaceIDInRootMesh;
XMFLOAT3* pAxisY = pAxisX + 1;
XMVECTOR tempVector = XMLoadFloat3(p3D) - XMLoadFloat3(pOrg);
p2D->x = XMVectorGetX(XMVector3Dot(tempVector, XMLoadFloat3(pAxisX)));
p2D->y = XMVectorGetX(XMVector3Dot(tempVector, XMLoadFloat3(pAxisY)));
}
// Caculate the signal length of two vertices in one 3D face
// See more detail of this algorithm in [SGSH02]
inline float CIsochartMesh::CalculateSignalLengthOnOneFace(
DirectX::XMFLOAT3* p3D0,
DirectX::XMFLOAT3* p3D1,
uint32_t dwFaceID)
{
using namespace DirectX;
if (INVALID_FACE_ID == dwFaceID)
{
return 0;
}
ISOCHARTFACE* pFace = m_pFaces + dwFaceID;
// 1. Calculate the 2-D reflection of 2 3D vertex
ISOCHARTVERTEX* pVertex =
m_pVerts + pFace->dwVertexID[0];
XMFLOAT3* pOrg =
m_baseInfo.pVertPosition + pVertex->dwIDInRootMesh;
XMFLOAT2 v2d0;
XMFLOAT2 v2d1;
Vertex3DTo2D(
pFace->dwIDInRootMesh,
pOrg, p3D0, &v2d0);
Vertex3DTo2D(
pFace->dwIDInRootMesh,
pOrg, p3D1, &v2d1);
// 2. Using affine transformation to calculate signal length
float fDeltaX = v2d1.x - v2d0.x;
float fDeltaY = v2d1.y - v2d0.y;
const FLOAT3* pIMT = m_baseInfo.pfIMTArray+pFace->dwIDInRootMesh;
float fLength;
fLength
= (*pIMT)[0]*fDeltaX*fDeltaX
+ (*pIMT)[2]*fDeltaY*fDeltaY
+ 2*(*pIMT)[1]*fDeltaX*fDeltaY;
fLength = IsochartSqrtf(fLength);
return fLength;
}
// When computing signal length along internal edge, two adjacent faces
// are involved, individually caculate edge's signal length on the two
// faces and use average.
inline float CIsochartMesh::CalculateEdgeSignalLength(
DirectX::XMFLOAT3* p3D0,
DirectX::XMFLOAT3* p3D1,
uint32_t dwAdjacentFaceID0,
uint32_t dwAdjacentFaceID1)
{
float fLength0;
fLength0 = CalculateSignalLengthOnOneFace(
p3D0, p3D1, dwAdjacentFaceID0);
if (INVALID_FACE_ID == dwAdjacentFaceID1)
{
return fLength0;
}
else
{
float fLength1;
fLength1 = CalculateSignalLengthOnOneFace(
p3D0, p3D1, dwAdjacentFaceID1);
return (fLength0 + fLength1) * 0.5f;
}
}
inline float CIsochartMesh::CalculateEdgeSignalLength(ISOCHARTEDGE& edge)
{
assert (INVALID_FACE_ID != edge.dwFaceID[0]);
assert (
(INVALID_FACE_ID == edge.dwFaceID[1] && edge.bIsBoundary)
||(INVALID_FACE_ID != edge.dwFaceID[1] || edge.bIsBoundary));
float fTestLength = 0;
DirectX::XMFLOAT3* pv0 =
m_baseInfo.pVertPosition + m_pVerts[edge.dwVertexID[0]].dwIDInRootMesh;
DirectX::XMFLOAT3* pv1 =
m_baseInfo.pVertPosition + m_pVerts[edge.dwVertexID[1]].dwIDInRootMesh;
fTestLength = CalculateEdgeSignalLength(
pv0, pv1, edge.dwFaceID[0], edge.dwFaceID[1]);
return fTestLength;
}
// Calculate edge's normal and signal length
inline void CIsochartMesh::CalculateChartEdgeLength()
{
for (size_t i=0; i<m_dwEdgeNumber; i++)
{
ISOCHARTEDGE& edge = m_edges[i];
edge.fLength = CalculateVextexDistance(
m_pVerts[edge.dwVertexID[0]], m_pVerts[edge.dwVertexID[1]]);
if (IsIMTSpecified())
{
edge.fSignalLength = CalculateEdgeSignalLength(edge);
}
else
{
edge.fSignalLength = 0;
}
}
}
inline void Rotate2DPoint(
DirectX::XMFLOAT2& uvOut,
const DirectX::XMFLOAT2& uvIn,
const DirectX::XMFLOAT2& center,
float fSin,
float fCos)
{
float x =
(uvIn.x-center.x)*fCos - (uvIn.y-center.y)*fSin;
float y =
(uvIn.x-center.x)*fSin + (uvIn.y-center.y)*fCos;
uvOut.x = x + center.x;
uvOut.y = y + center.y;
}
// Rotate chart around origin
inline void CIsochartMesh::RotateChart(
const DirectX::XMFLOAT2& center, float fAngle) const
{
DirectX::XMFLOAT2 tempCoordinate;
float fCos = cosf(fAngle);
float fSin = sinf(fAngle);
ISOCHARTVERTEX* pVertex = m_pVerts;
for (size_t i=0; i<m_dwVertNumber; i++)
{
Rotate2DPoint(
pVertex->uv, pVertex->uv, center, fSin, fCos);
pVertex++;
}
}
// Rotate chart boundary, get bounding box
inline void CIsochartMesh::GetRotatedChartBoundingBox(
const DirectX::XMFLOAT2& center,
float fAngle,
DirectX::XMFLOAT2& minBound,
DirectX::XMFLOAT2& maxBound) const
{
minBound.x = minBound.y = FLT_MAX;
maxBound.x = maxBound.y = -FLT_MAX;
DirectX::XMFLOAT2 tempCoordinate;
ISOCHARTVERTEX* pVertex = m_pVerts;
float fCos = cosf(fAngle);
float fSin = sinf(fAngle);
for (size_t i=0; i<m_dwVertNumber; i++)
{
if (!pVertex->bIsBoundary)
{
pVertex++;
continue;
}
Rotate2DPoint(
tempCoordinate,
pVertex->uv,
center,
fSin,
fCos);
minBound.x = std::min(tempCoordinate.x, minBound.x);
minBound.y = std::min(tempCoordinate.y, minBound.y);
maxBound.x = std::max(tempCoordinate.x, maxBound.x);
maxBound.y = std::max(tempCoordinate.y, maxBound.y);
pVertex++;
}
}
// Get the minial bounding box of current chart
inline void CIsochartMesh::CalculateChartMinimalBoundingBox(
size_t dwRotationCount,
DirectX::XMFLOAT2& minBound,
DirectX::XMFLOAT2& maxBound) const
{
using namespace DirectX;
float fMinRectArea = 0;
float fMinAngle = 0;
XMFLOAT2 tempMinBound;
XMFLOAT2 tempMaxBound;
float tempArea;
minBound.x = minBound.y = FLT_MAX;
maxBound.x = maxBound.y = -FLT_MAX;
for (size_t ii=0; ii<m_dwVertNumber; ii++)
{
const XMFLOAT2& uv = m_pVerts[ii].uv;
minBound.x = std::min(uv.x, minBound.x);
minBound.y = std::min(uv.y, minBound.y);
maxBound.x = std::max(uv.x, maxBound.x);
maxBound.y = std::max(uv.y, maxBound.y);
}
XMFLOAT2 center;
XMStoreFloat2(¢er, (XMLoadFloat2(&minBound) + XMLoadFloat2(&maxBound)) / 2);
fMinRectArea = IsochartBoxArea(minBound, maxBound);
fMinAngle = 0;
//To calculate bounding box, only need to rotate with in PI/2 around the chart's center
for (size_t dwRotID = 1; dwRotID <dwRotationCount; dwRotID++)
{
float fAngle = dwRotID* XM_PI /(dwRotationCount*2);
GetRotatedChartBoundingBox(
center, fAngle, tempMinBound, tempMaxBound);
tempArea = IsochartBoxArea(tempMinBound, tempMaxBound);
if (tempArea < fMinRectArea)
{
fMinRectArea = tempArea;
fMinAngle = fAngle;
minBound = tempMinBound;
maxBound = tempMaxBound;
}
}
if (fMinAngle > ISOCHART_ZERO_EPS)
{
RotateChart(center, fMinAngle);
}
}
inline CIsochartMesh* CIsochartMesh::CreateNewChart(
VERTEX_ARRAY& vertList,
std::vector<uint32_t>& faceList,
bool bIsSubChart) const
{
auto pChart = new (std::nothrow) CIsochartMesh(m_baseInfo, m_callbackSchemer, m_IsochartEngine);
if (!pChart)
{
return nullptr;
}
pChart->m_pFather = const_cast<CIsochartMesh* >(this);
pChart->m_bVertImportanceDone = m_bVertImportanceDone;
pChart->m_bIsSubChart = bIsSubChart;
pChart->m_fBoxDiagLen = m_fBoxDiagLen;
pChart->m_dwVertNumber = vertList.size();
pChart->m_dwFaceNumber = faceList.size();
pChart->m_pVerts = new (std::nothrow) ISOCHARTVERTEX[pChart->m_dwVertNumber];
pChart->m_pFaces = new (std::nothrow) ISOCHARTFACE[pChart->m_dwFaceNumber];
if (!pChart->m_pVerts || !pChart->m_pFaces)
{
delete pChart; // vertex and face buffer will be deleted
return nullptr; // in destructor.
}
std::unique_ptr<uint32_t []> pdwVertMap(new (std::nothrow) uint32_t[m_dwVertNumber]);
if (!pdwVertMap)
{
delete pChart;
return nullptr;
}
ISOCHARTVERTEX* pOldVertex = nullptr;
ISOCHARTVERTEX* pNewVertex = pChart->m_pVerts;
for (uint32_t i = 0; i<pChart->m_dwVertNumber; i++)
{
pOldVertex = vertList[i];
pNewVertex->dwID = i;
pNewVertex->dwIDInRootMesh = pOldVertex->dwIDInRootMesh;
pNewVertex->dwIDInFatherMesh = pOldVertex->dwID;
pNewVertex->bIsBoundary = pOldVertex->bIsBoundary;
pNewVertex->nImportanceOrder = pOldVertex->nImportanceOrder;
pdwVertMap[pOldVertex->dwID] = i;
pNewVertex++;
}
ISOCHARTFACE* pNewFace = pChart->m_pFaces;
for (uint32_t i = 0; i<pChart->m_dwFaceNumber; i++)
{
ISOCHARTFACE* pOldFace = m_pFaces + faceList[i];
pNewFace->dwID = i;
pNewFace->dwIDInRootMesh = pOldFace->dwIDInRootMesh;
pNewFace->dwIDInFatherMesh = pOldFace->dwID;
for (size_t j=0; j<3; j++)
{
pNewFace->dwVertexID[j] =
pdwVertMap[pOldFace->dwVertexID[j]];
}
pNewFace++;
}
pChart->m_bNeedToClean = m_bNeedToClean;
return pChart;
}
inline HRESULT CIsochartMesh::MoveTwoValueToHead(
std::vector<uint32_t>& list,
uint32_t dwIdx1,
uint32_t dwIdx2)
{
if (list.size() <3)
{
return S_OK;
}
// if the 2 landmark aready in head
if ((0 == dwIdx1 || 0 == dwIdx2) &&
(1 == dwIdx1 || 1 == dwIdx2))
{
return S_OK;
}
else if (0 == dwIdx1)
{
std::swap(list[1],list[dwIdx2]);
}
else if (0 == dwIdx2)
{
std::swap(list[1], list[dwIdx1]);
}
else if (1 == dwIdx1)
{
std::swap(list[0],list[dwIdx2]);
}
else if (1 == dwIdx2)
{
std::swap(list[0],list[dwIdx1]);
}
else
{
std::swap(list[0], list[dwIdx1]);
std::swap(list[1], list[dwIdx2]);
}
return S_OK;
}
}
|
[
"SND\\walbourn_cp"
] |
SND\walbourn_cp
|
f236ea549a59f6711998919aafb6791caf9675f7
|
70fe255d0a301952a023be5e1c1fefd062d1e804
|
/其它练习/华东师范大学保研机试题练习/2009-3.cpp
|
c2a6cdfccec43f24c67f7c68359ee67bfc41cbdb
|
[
"MIT"
] |
permissive
|
LauZyHou/Algorithm-To-Practice
|
524d4318032467a975cf548d0c824098d63cca59
|
66c047fe68409c73a077eae561cf82b081cf8e45
|
refs/heads/master
| 2021-06-18T01:48:43.378355
| 2021-01-27T14:44:14
| 2021-01-27T14:44:14
| 147,997,740
| 8
| 1
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 1,297
|
cpp
|
#include<iostream>
#include<list>
using namespace std;
//ËØÊý¶Ô,×÷·Ï
list<int> su;
int n,t,cnt;
bool isSu(int n) {
if(n == 1)
return false;
if(n < 4)
return true;
for(int i = 2; i * i <= n; i++) {
if(n % i == 0)
return false;
}
return true;
}
int main() {
scanf("%d", &n);
while(n--) {
scanf("%d",&t);
if(t<3){
printf("0\n");
continue;
}
for(int i = 2; i <= t; i++) {
if(isSu(i))
su.push_back(i);
}
if(su.empty()){
printf("0\n");
continue;
}
list<int>::const_iterator itA=su.cbegin();
list<int>::const_iterator itB=su.cend();
while(itA!=itB){
if(*itA+*itB==t+1){
cnt++;
itA++;
if(itA==itB)
break;
itB--;
cout<<"P";
}else if(*itA+*itB<t+1){
itA++;
cout<<"L";
}else{
itB--;
cout<<"K";
}
}
cnt=cnt<<2;
if(((*itA)<<2)==t+1)
cnt++;
printf("%d--\n",cnt);
cnt=0;
su.clear();
}
return 0;
}
|
[
"java233@foxmail.com"
] |
java233@foxmail.com
|
80df0013f2c9661325e1fe8ee453c43d9c559f5f
|
c9ea4b7d00be3092b91bf157026117bf2c7a77d7
|
/高级数据结构初步/P4392_fast.cpp
|
04ff9569ca6af559cee2c91b9aab1c2b9aa21a8c
|
[] |
no_license
|
Jerry-Terrasse/Programming
|
dc39db2259c028d45c58304e8f29b2116eef4bfd
|
a59a23259d34a14e38a7d4c8c4d6c2b87a91574c
|
refs/heads/master
| 2020-04-12T08:31:48.429416
| 2019-04-20T00:32:55
| 2019-04-20T00:32:55
| 162,387,499
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,529
|
cpp
|
//P4392 [BOI2007]Sound 静音问题
#include<cstdio>
#define MAXN 1000010
#define MAXM 10010
using namespace std;
struct queue
{
int mem[MAXN],*head,*tail;
inline queue();
}q,r;
int a[MAXN],n=0,m=0,c=0;
bool flag=false;
inline void read(int&);
void write(const int&);
int main()
{
register int i=0;
read(n);read(m);read(c);
if(n<m)
{
puts("NONE");
return 0;
}
for(i=0;i<n;++i)
{
read(a[i]);
}
for(i=0;i<m;++i)
{
for(;q.tail-q.head&&a[*(q.tail-1)]>=a[i];--q.tail);
*q.tail=i;++q.tail;
for(;r.tail-r.head&&a[*(r.tail-1)]<=a[i];--r.tail);
*r.tail=i;++r.tail;
}
if(a[*r.head]-a[*q.head]<=c)
{
flag=true;
puts("1");
}
for(;i<n;++i)
{
for(;q.tail-q.head&&a[*(q.tail-1)]>=a[i];--q.tail);
*q.tail=i;++q.tail;
if(*q.head+m==i)
{
++q.head;
}
for(;r.tail-r.head&&a[*(r.tail-1)]<=a[i];--r.tail);
*r.tail=i;++r.tail;
if(*r.head+m==i)
{
++r.head;
}
if(a[*r.head]-a[*q.head]<=c)
{
flag=true;
write(i+2-m);
putchar('\n');
}
}
if(!flag)
{
puts("NONE");
}
return 0;
}
inline queue::queue()
{
head=tail=mem;
return;
}
void write(const int &x)
{
if(x>9)
{
write(x/10);
}
putchar(x%10^48);
return;
}
inline void read(int &x)
{
register char c=getchar();
for(x=0;c<'0'||c>'9';c=getchar());
for(;c>='0'&&c<='9';c=getchar())
{
x=(x<<1)+(x<<3)+(c^48);
}
return;
}
|
[
"3305049949@qq.com"
] |
3305049949@qq.com
|
0bbed5209f713c5e8627c5d430dc89144f597371
|
c044f03d16fc7506a6699a31061ea6a1abd3a68e
|
/src/bonus.cpp
|
6132326236f986f319061c5514608bbbb3e7ac58
|
[] |
no_license
|
mirkoviviano/CppND-Capstone-A-Weird-Snake-Game
|
4c0a3befe81467058f7e09f0c85aef0530e2fe19
|
978d650ab5d11a1b565a8b9f4eb1b40d23fbcf22
|
refs/heads/master
| 2020-07-21T20:32:59.264141
| 2019-10-11T16:56:47
| 2019-10-11T16:56:47
| 206,969,159
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 240
|
cpp
|
#include "bonus.h"
#include <cmath>
#include <iostream>
int Bonus::GetPower(){
Bonus::Power power = Bonus::Power(rand() % 4 + 1);
return power;
}
int Bonus::Duration(){
duration = rand() % 10000 + 1000;
return duration;
}
|
[
"info@mirkoviviano.it"
] |
info@mirkoviviano.it
|
fe3a82bae35accba8886323c3af5b5b92ff4615f
|
0d5be9442b4e78805508a0428dd1f4663cc0d902
|
/PWGGA/PHOSTasks/PHOS_Run2/AliAnalysisTaskPHOSObjectCreator.cxx
|
8fba49992c382b89af1d4a55ca4361e4db38e4b4
|
[] |
permissive
|
brinick/AliPhysics
|
32984d5206212e8f22018fd9e757199f3e092e20
|
49fb1acec903b4d6cb27efdec5fe7909c0985c82
|
refs/heads/master
| 2020-12-02T21:25:45.935213
| 2018-11-07T08:44:41
| 2018-11-07T08:44:41
| 96,315,340
| 0
| 0
|
BSD-3-Clause
| 2018-11-07T09:47:19
| 2017-07-05T12:10:43
|
C++
|
UTF-8
|
C++
| false
| false
| 33,404
|
cxx
|
#include "TF1.h"
#include "TObject.h"
#include "TObjArray.h"
#include "TClonesArray.h"
#include "TString.h"
#include "TMath.h"
#include "THashList.h"
#include "TChain.h"
#include "AliLog.h"
#include "AliAnalysisTaskSE.h"
#include "TParticle.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliStack.h"
#include "AliAODMCParticle.h"
#include "AliVCluster.h"
#include "AliVCaloCells.h"
#include "AliCaloPhoton.h"
#include "AliVEvent.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliPHOSGeometry.h"
#include "AliOADBContainer.h"
#include "AliMagF.h"
#include "TGeoGlobalMagField.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisTaskPHOSObjectCreator.h"
ClassImp(AliAnalysisTaskPHOSObjectCreator)
//________________________________________________________________________
AliAnalysisTaskPHOSObjectCreator::AliAnalysisTaskPHOSObjectCreator(const char *name):
AliAnalysisTaskSE(name),
fOutputContainer(0x0),
fHistoMggvsEProbe(0x0),
fHistoMggvsEPassingProbe(0x0),
fEvent(0x0),
fAODEvent(0x0),
fESDEvent(0x0),
fPHOSObjectArray(NULL),
fPHOSGeo(0x0),
fNonLinCorr(0x0),
fUserNonLinCorr(0x0),
fRunNumber(0),
fUsePHOSTender(kTRUE),
fIsMC(kFALSE),
fBunchSpace(25.),
fMCArrayESD(0x0),
fMCArrayAOD(0x0),
fIsM4Excluded(kTRUE)
{
// Constructor
for(Int_t i=0;i<3;i++){
fVertex[i] = 0;
}
for(Int_t i=0;i<6;i++){
fPHOSBadMap[i] = 0;
}
//Initialize non-linrarity correction
fNonLinCorr = new TF1("nonlin","0.0241 + 1.0504*x + 0.000249*x*x",0.,100.);
fUserNonLinCorr = new TF1("usernonlin","1.",0.,100.);
// Define input and output slots here
// Input slot #0 works with a TChain
DefineInput(0, TChain::Class());
// Output slot #0 id reserved by the base class for AOD
// Output slot #1 writes into a TH1 container
DefineOutput(1, THashList::Class());
}
//________________________________________________________________________
AliAnalysisTaskPHOSObjectCreator::~AliAnalysisTaskPHOSObjectCreator()
{
//destructor
if(fPHOSObjectArray){
delete fPHOSObjectArray;
fPHOSObjectArray = 0x0;
}
if(fNonLinCorr){
delete fNonLinCorr;
fNonLinCorr = 0x0;
}
if(fUserNonLinCorr){
delete fUserNonLinCorr;
fUserNonLinCorr = 0x0;
}
}
//________________________________________________________________________
void AliAnalysisTaskPHOSObjectCreator::UserCreateOutputObjects()
{
// Create histograms
// Called once
fOutputContainer = new THashList();
fOutputContainer->SetOwner(kTRUE);
const Int_t NpTgg = 101;
Double_t pTgg[NpTgg]={};
for(Int_t i=0;i<50;i++) pTgg[i] = 0.1 * i; //every 0.1 GeV/c, up to 5 GeV/c
for(Int_t i=50;i<60;i++) pTgg[i] = 0.5 * (i-50) + 5.0; //every 0.5 GeV/c, up to 10 GeV/c
for(Int_t i=60;i<NpTgg;i++) pTgg[i] = 1.0 * (i-60) + 10.0;//every 1.0 GeV/c, up to 50 GeV/c
fHistoMggvsEProbe = new TH2F("hMgg_STDCut_Probe","Probe #gamma for standard cluster cut",60,0,0.24,NpTgg-1,pTgg);
fHistoMggvsEProbe->Sumw2();
fHistoMggvsEProbe->SetXTitle("M_{#gamma#gamma} (GeV/c^{2})");
fHistoMggvsEProbe->SetYTitle("E_{#gamma} (GeV)");
fHistoMggvsEPassingProbe = new TH2F("hMgg_STDCut_PassingProbe","Passing Probe #gamma for standard cluster cut",60,0,0.24,NpTgg-1,pTgg);
fHistoMggvsEPassingProbe->Sumw2();
fHistoMggvsEPassingProbe->SetXTitle("M_{#gamma#gamma} (GeV/c^{2})");
fHistoMggvsEPassingProbe->SetYTitle("E_{#gamma} (GeV)");
fOutputContainer->Add(fHistoMggvsEProbe);
fOutputContainer->Add(fHistoMggvsEPassingProbe);
Init();//initialize PHOS object array
PostData(1,fOutputContainer);
}
//________________________________________________________________________
void AliAnalysisTaskPHOSObjectCreator::UserExec(Option_t *option)
{
// Main loop
// Called for each event
fEvent = dynamic_cast<AliVEvent*>(InputEvent());
if(!fEvent){
AliError("event is not available.");
return;
}
//cout << "Object Creator usePHOSTender = " << fUsePHOSTender << " , fIsMC = " << fIsMC << endl;
fESDEvent = dynamic_cast<AliESDEvent*>(fEvent);
fAODEvent = dynamic_cast<AliAODEvent*>(fEvent);
if(fIsMC){
fMCArrayESD = 0x0;
fMCArrayAOD = 0x0;
if(fESDEvent){
AliVEventHandler* eventHandler = AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler();
if(eventHandler){
AliMCEventHandler* mcEventHandler = dynamic_cast<AliMCEventHandler*> (eventHandler);
if(mcEventHandler) fMCArrayESD = static_cast<AliMCEventHandler*>(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler())->MCEvent()->Stack();
}
if(!fMCArrayESD) AliError("Could not get MC Stack!");
}
else if(fAODEvent){
fMCArrayAOD = dynamic_cast<TClonesArray*>(fAODEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if(!fMCArrayAOD){
AliError("Could not retrieve MC array!");
return;
}
}
}
if(fRunNumber != fEvent->GetRunNumber()) { // Check run number
fRunNumber = fEvent->GetRunNumber();
SetGeometry();
}
const AliVVertex *vVertex = fEvent->GetPrimaryVertex();
fVertex[0] = vVertex->GetX();
fVertex[1] = vVertex->GetY();
fVertex[2] = vVertex->GetZ();
AliVCaloCells *cells = dynamic_cast<AliVCaloCells*>(fEvent->GetPHOSCells());
Int_t multClust = fEvent->GetNumberOfCaloClusters();
fPHOSObjectArray->Clear();
TLorentzVector p1,p1core;
Double_t energy=0, tof=-999, M20=0, M02=0, R2=999, coreE=0, coreR2=999;
Double_t TrackDx=0, TrackDz=0, TrackPt=0, r=999;
Int_t TrackCharge = 0;
Int_t trackindex=-1;
Int_t relId[4] = {};
Int_t module=-1, cellx=-1, cellz=-1;
Int_t digMult=0;
Float_t position[3] = {};
AliVTrack *vtrack = 0x0;
AliVCluster *cluster = 0x0;
Double_t distance=0;
Int_t inPHOS=0;
for(Int_t iclu=0; iclu<multClust; iclu++){
cluster = (AliVCluster*)fEvent->GetCaloCluster(iclu);
if(cluster->GetType() != AliVCluster::kPHOSNeutral) continue;
if(cluster->E() < 0.1) continue;//energy is set to 0 GeV in PHOS Tender, if its position is one th bad channel.//0.05 GeV is threshold of seed in a cluster by clustering algorithm.
if(cluster->GetM20() > 2.0) continue;
//printf("energy = %e , coreE = %e\n",cluster->E(),cluster->GetCoreEnergy());
distance = cluster->GetDistanceToBadChannel();//in cm.
//cout << "Ncell before = " << cluster->GetNCells() << endl;
Int_t Ncell = cluster->GetNCells();
for(Int_t i=0;i<cluster->GetNCells();i++){
Int_t absId_tmp = cluster->GetCellAbsId(i);
Double_t amp = cells->GetCellAmplitude(absId_tmp);
if(amp < 2e-6) //less than 2 keV
Ncell--;
}
//cluster->SetNCells(Ncell);
cluster->GetPosition(position);
TVector3 global1(position);
fPHOSGeo->GlobalPos2RelId(global1,relId);
module = relId[0];
cellx = relId[2];
cellz = relId[3];
if(fIsM4Excluded && module==4) continue;
if(module < 1 || 4 < module){
AliError(Form("Wrong module number %d",module));
return;
}
if(!fUsePHOSTender && !IsGoodChannel("PHOS",module,cellx,cellz)) continue;
energy = cluster->E();
digMult = cluster->GetNCells();
tof = cluster->GetTOF();
if(fUsePHOSTender){
//When PHOSTender is applied, GetM20(), GetM02() returns M20,M02 of core of cluster respectively.
M20 = cluster->GetM20();//M20 is short axis of elliptic shower shape.
M02 = cluster->GetM02();//M02 is long axis of elliptic shower shape.
R2 = cluster->GetDispersion();//full dispersion
coreE = cluster->GetCoreEnergy();
coreR2 = cluster->Chi2();//core dispersion
r = cluster->GetEmcCpvDistance();
}
else{//no tender
//When PHOSTender is NOT applied, GetM20(), GetM02() returns M20,M02 of full cluster respectively.
M20 = cluster->GetM20();//M20 is short axis of elliptic shower shape.
M02 = cluster->GetM02();//M02 is long axis of elliptic shower shape.
R2 = TestLambda(energy,M20,M02);
coreE = CoreEnergy(cluster,cells);
EvalCoreLambdas(cluster,cells,M02,M20);
coreR2 = TestCoreLambda(energy,M20,M02);
vtrack = 0x0;
if(fESDEvent){//for ESD
trackindex = cluster->GetTrackMatchedIndex();
if(trackindex > 0){
vtrack = (AliVTrack*)(fEvent->GetTrack(trackindex));
}//end of track matching
}//end of track selection in ESD
else if(fAODEvent){//for AOD
if(cluster->GetNTracksMatched() > 0){
vtrack = dynamic_cast<AliVTrack*>(cluster->GetTrackMatched(0));
}//end of track matching
}//end of AOD
if(vtrack){
TrackDx = cluster->GetTrackDx();
TrackDz = cluster->GetTrackDz();
TrackPt = vtrack->Pt();
TrackCharge = vtrack->Charge();
r = TestCPVRun2(TrackDx,TrackDz,TrackPt,TrackCharge);
}//end of track matching
else r = 999;//no matched track
}
cluster->GetMomentum(p1,fVertex);
cluster->GetMomentum(p1core,fVertex);
p1 *= fUserNonLinCorr->Eval(p1.E());
p1core *= coreE/energy * fUserNonLinCorr->Eval(coreE); //use core energy in PbPb.
if(p1.E() < 0.1) continue;//minimum energy cut after NL correciton. Note Ecore <= Efull
new((*fPHOSObjectArray)[inPHOS]) AliCaloPhoton(p1.Px(),p1.Py(),p1.Pz(),p1.E());
AliCaloPhoton * ph = (AliCaloPhoton*)fPHOSObjectArray->At(inPHOS);
ph->SetCluster(cluster);
ph->SetModule(module);
ph->SetNCells(digMult);
ph->SetTime(tof);//unit of second
ph->SetTOFBit(TMath::Abs(tof*1e+9) < fBunchSpace/2.);
ph->SetDistToBadfp(distance/2.2);//in unit of cells with floating point. 2.2 cm is crystal size
ph->SetEMCx((Double_t)position[0]);
ph->SetEMCy((Double_t)position[1]);
ph->SetEMCz((Double_t)position[2]);
ph->SetWeight(1.);
if(fIsMC){
Bool_t sure = kTRUE;
Int_t label = FindPrimary(ph,sure);
ph->SetPrimary(label);
//ph->SetPrimary(cluster->GetLabel());
}
ph->SetLambdas(M20,M02);
ph->SetNsigmaCPV(r);
ph->SetNsigmaFullDisp(TMath::Sqrt(R2));
ph->SetNsigmaCoreDisp(TMath::Sqrt(coreR2));
ph->SetMomV2(&p1core);//core energy
//printf("energy = %e , coreE = %e\n",ph->Energy(),ph->GetMomV2()->Energy());
inPHOS++;
}
EstimateSTDCutEfficiency(fPHOSObjectArray);
const Int_t Nph = fPHOSObjectArray->GetEntries();
for(Int_t iph=0;iph<Nph;iph++){
AliCaloPhoton *ph = (AliCaloPhoton*)fPHOSObjectArray->At(iph);
AliVCluster *cluster = (AliVCluster*)ph->GetCluster();
if(!PassSTDCut(cluster)){
//AliInfo("cluster is rejected by the standard cluster cut.");
fPHOSObjectArray->Remove(ph);
}
}
fPHOSObjectArray->Compress();
AliVEvent* input = InputEvent();
TObject* outO = input->FindListObject("PHOSClusterArray");
if(!outO){
fPHOSObjectArray->SetName("PHOSClusterArray");
input->AddObject(fPHOSObjectArray);
}
}
//________________________________________________________________________
void AliAnalysisTaskPHOSObjectCreator::Terminate(Option_t *option)
{
//Called once at the end of the query
//fUserNonLinCorr->Draw();
}
//________________________________________________________________________
void AliAnalysisTaskPHOSObjectCreator::Init()
{
//Called once at the end of the query
//if(fPHOSObjectArray != NULL){
if(fPHOSObjectArray){
//delete fPHOSObjectArray;
fPHOSObjectArray = NULL;
//fPHOSObjectArray->Clear();
}
fPHOSObjectArray = new TClonesArray("AliCaloPhoton",200);
fPHOSObjectArray->Delete();
}
//________________________________________________________________________
void AliAnalysisTaskPHOSObjectCreator::InitBadMap()
{
AliOADBContainer badmapContainer(Form("phosBadMap"));
badmapContainer.InitFromFile("$ALICE_PHYSICS/OADB/PHOS/PHOSBadMaps.root","phosBadMap");
TObjArray *maps = (TObjArray*)badmapContainer.GetObject(fRunNumber,"phosBadMap");
if(!maps){
AliError(Form("Can not read Bad map for run %d. \n You may choose to use your map with ForceUsingBadMap().",fRunNumber)) ;
}
else{
AliInfo(Form("Setting PHOS bad map with name %s.",maps->GetName())) ;
for(Int_t mod=0; mod<6;mod++){
if(fPHOSBadMap[mod]) delete fPHOSBadMap[mod];
TH2I * h = (TH2I*)maps->At(mod);
if(h) fPHOSBadMap[mod]=new TH2I(*h);
}
}
}
//________________________________________________________________________
void AliAnalysisTaskPHOSObjectCreator::SetGeometry()
{
// Initialize the PHOS geometry
if(fUsePHOSTender){
if(fRunNumber < 209122)//Run1
fPHOSGeo = AliPHOSGeometry::GetInstance("IHEP") ;
else//Run2
fPHOSGeo = AliPHOSGeometry::GetInstance("Run2") ;
}
else{//PHOSTender is not applied.
AliOADBContainer geomContainer("phosGeo");
if(fRunNumber < 209122)//Run1
fPHOSGeo = AliPHOSGeometry::GetInstance("IHEP") ;
else//Run2
fPHOSGeo = AliPHOSGeometry::GetInstance("Run2") ;
if(fIsMC){ //use excatly the same geometry as in simulation, stored in esd
if(fESDEvent){
for(Int_t mod=0; mod<6; mod++) {
const TGeoHMatrix * m = fESDEvent->GetPHOSMatrix(mod);
if(m){
fPHOSGeo->SetMisalMatrix(m,mod) ;
printf(".........Adding Matrix(%d), geo=%p\n",mod,fPHOSGeo);
m->Print();
}
}
}
else if(fAODEvent){ //To be fixed
geomContainer.InitFromFile("$ALICE_PHYSICS/OADB/PHOS/PHOSMCGeometry.root","PHOSMCRotationMatrixes");
TObjArray *matrixes = (TObjArray*)geomContainer.GetObject(fRunNumber,"PHOSRotationMatrixes");
for(Int_t mod=0; mod<6; mod++){
if(!matrixes->At(mod)) continue;
fPHOSGeo->SetMisalMatrix(((TGeoHMatrix*)matrixes->At(mod)),mod);
printf(".........Adding Matrix(%d), geo=%p\n",mod,fPHOSGeo);
((TGeoHMatrix*)matrixes->At(mod))->Print();
}
}
}//end of MC
else{ //Use best approaximation to real geometry
geomContainer.InitFromFile("$ALICE_PHYSICS/OADB/PHOS/PHOSGeometry.root","PHOSRotationMatrixes");
TObjArray *matrixes = (TObjArray*)geomContainer.GetObject(fRunNumber,"PHOSRotationMatrixes");
for(Int_t mod=0; mod<6; mod++){
if(!matrixes->At(mod)) continue;
fPHOSGeo->SetMisalMatrix(((TGeoHMatrix*)matrixes->At(mod)),mod);
printf(".........Adding Matrix(%d), geo=%p\n",mod,fPHOSGeo);
((TGeoHMatrix*)matrixes->At(mod))->Print();
}
}//end of real data
}
}
//________________________________________________________________________
Bool_t AliAnalysisTaskPHOSObjectCreator::IsGoodChannel(const char * det, Int_t mod, Int_t ix, Int_t iz)
{
//Check if this channel belogs to the good ones
if(strcmp(det,"PHOS")==0){
if(mod>5 || mod<1){
AliError(Form("No bad map for PHOS module %d ",mod)) ;
return kTRUE ;
}
if(!fPHOSBadMap[mod]){
AliError(Form("No Bad map for PHOS module %d",mod)) ;
return kTRUE ;
}
if(fPHOSBadMap[mod]->GetBinContent(ix,iz)>0)
return kFALSE ;
else
return kTRUE ;
}
else{
AliError(Form("Can not find bad channels for detector %s ",det)) ;
}
return kTRUE ;
}
//________________________________________________________________________
Double_t AliAnalysisTaskPHOSObjectCreator::TestCPVRun2(Double_t dx, Double_t dz, Double_t pt, Int_t charge)
{
//Parameterization of LHC15o period
//_true if neutral_
Double_t meanX=0.;
Double_t meanZ=0.;
Double_t sx = TMath::Min(5.2, 1.160 + 0.52 * TMath::Exp(-0.042 * pt*pt) + 5.1/TMath::Power(pt+0.62,3));
Double_t sz = TMath::Min(3.3, 1.10 + 0.39 * TMath::Exp(-0.027 * pt*pt) + 0.70 /TMath::Power(pt+0.223,3));
Double_t mf1 = fEvent->GetMagneticField(); //Positive for ++ and negative for --
if(mf1<0.){ //field --
meanZ = 0.077;
if(charge>0)
meanX = TMath::Min(5.8, 0.2 + 0.7 * TMath::Exp(-0.019 * pt*pt) + 34./TMath::Power(pt+1.39,3));
else
meanX = -TMath::Min(5.8, 0.1 + 0.7 * TMath::Exp(-0.014 * pt*pt) + 30./TMath::Power(pt+1.36,3));
}
else{ //Field ++
meanZ= 0.077;
if(charge>0)
meanX = -TMath::Min(5.8, 0.3 + 0.7 * TMath::Exp(-0.012 * pt*pt) + 35./TMath::Power(pt+1.43,3));
else
meanX = TMath::Min(5.8, 0.2 + 0.6 * TMath::Exp(-0.014 * pt*pt) + 28./TMath::Power(pt+1.27,3));
}
Double_t rz=(dz-meanZ)/sz ;
Double_t rx=(dx-meanX)/sx ;
return TMath::Sqrt(rx*rx+rz*rz) ;
}
//________________________________________________________________________
Double_t AliAnalysisTaskPHOSObjectCreator::TestLambda(Double_t e,Double_t l1,Double_t l2)
{
Double_t l2Mean = 1.53126+9.50835e+06/(1.+1.08728e+07*e+1.73420e+06*e*e) ;
Double_t l1Mean = 1.12365+0.123770*TMath::Exp(-e*0.246551)+5.30000e-03*e ;
Double_t l2Sigma = 6.48260e-02+7.60261e+10/(1.+1.53012e+11*e+5.01265e+05*e*e)+9.000e-03*e;
Double_t l1Sigma = 4.44719e-04+6.99839e-01/(1.+1.22497e+00*e+6.78604e-07*e*e)+9.000e-03*e;
Double_t c=-0.35-0.550*TMath::Exp(-0.390730*e) ;
Double_t R2=0.5*(l1-l1Mean)*(l1-l1Mean)/l1Sigma/l1Sigma +
0.5*(l2-l2Mean)*(l2-l2Mean)/l2Sigma/l2Sigma +
0.5*c*(l1-l1Mean)*(l2-l2Mean)/l1Sigma/l2Sigma ;
return R2;
}
//________________________________________________________________________
Double_t AliAnalysisTaskPHOSObjectCreator::TestCoreLambda(Double_t e, Double_t l1, Double_t l2)
{
//Evaluates if lambdas correspond to photon cluster
//Tuned using pp date
//For core radius R=4.5
Double_t l1Mean = 1.150200 + 0.097886/(1.+1.486645*e+0.000038*e*e) ;
Double_t l2Mean = 1.574706 + 0.997966*exp(-0.895075*e)-0.010666*e ;
Double_t l1Sigma = 0.100255 + 0.337177*exp(-0.517684*e)+0.001170*e ;
Double_t l2Sigma = 0.232580 + 0.573401*exp(-0.735903*e)-0.002325*e ;
Double_t c = -0.110983 -0.017353/(1.-1.836995*e+0.934517*e*e) ;
Double_t R2=0.5*(l1-l1Mean)*(l1-l1Mean)/l1Sigma/l1Sigma +
0.5*(l2-l2Mean)*(l2-l2Mean)/l2Sigma/l2Sigma +
0.5*c*(l1-l1Mean)*(l2-l2Mean)/l1Sigma/l2Sigma ;
return R2 ;
}
//________________________________________________________________________
void AliAnalysisTaskPHOSObjectCreator::EvalCoreLambdas(AliVCluster *clu, AliVCaloCells *cells,Double_t &m02, Double_t &m20)
{
//calculate dispecrsion of the cluster in the circle with radius distanceCut around the maximum
const Double_t rCut=4.5;
const Double32_t *elist = clu->GetCellsAmplitudeFraction();
//Calculates the center of gravity in the local PHOS-module coordinates
Float_t wtot = 0;
const Int_t mulDigit=clu->GetNCells() ;
Double_t xc[mulDigit] ;
Double_t zc[mulDigit] ;
Double_t wi[mulDigit] ;
Double_t x = 0 ;
Double_t z = 0 ;
const Double_t logWeight=4.5 ;
for(Int_t iDigit=0; iDigit<mulDigit; iDigit++) {
Int_t relid[4] ;
Float_t xi=0. ;
Float_t zi=0. ;
Int_t absId = clu->GetCellAbsId(iDigit) ;
fPHOSGeo->AbsToRelNumbering(absId, relid) ;
fPHOSGeo->RelPosInModule(relid, xi, zi);
xc[iDigit]=xi ;
zc[iDigit]=zi ;
Double_t ei = elist[iDigit]*cells->GetCellAmplitude(absId) ;
wi[iDigit]=0. ;
if (clu->E()>0 && ei>0) {
wi[iDigit] = TMath::Max( 0., logWeight + TMath::Log( ei / clu->E() ) ) ;
Double_t w=wi[iDigit];
x += xc[iDigit] * w ;
z += zc[iDigit] * w ;
wtot += w ;
}
}
if (wtot>0) {
x /= wtot ;
z /= wtot ;
}
wtot = 0. ;
Double_t dxx = 0.;
Double_t dzz = 0.;
Double_t dxz = 0.;
Double_t xCut = 0.;
Double_t zCut = 0.;
for(Int_t iDigit=0; iDigit<mulDigit; iDigit++) {
Double_t w=wi[iDigit];
if(w>0.) {
Double_t xi= xc[iDigit] ;
Double_t zi= zc[iDigit] ;
if((xi-x)*(xi-x)+(zi-z)*(zi-z) < rCut*rCut){
xCut += w * xi ;
zCut += w * zi ;
dxx += w * xi * xi ;
dzz += w * zi * zi ;
dxz += w * xi * zi ;
wtot += w ;
}
}
}
if(wtot>0) {
xCut/= wtot ;
zCut/= wtot ;
dxx /= wtot ;
dzz /= wtot ;
dxz /= wtot ;
dxx -= xCut * xCut ;
dzz -= zCut * zCut ;
dxz -= xCut * zCut ;
m02 = 0.5 * (dxx + dzz) + TMath::Sqrt( 0.25 * (dxx - dzz) * (dxx - dzz) + dxz * dxz ) ;
m20 = 0.5 * (dxx + dzz) - TMath::Sqrt( 0.25 * (dxx - dzz) * (dxx - dzz) + dxz * dxz ) ;
}
else {
m20=m02=0.;
}
}
//________________________________________________________________________
Double_t AliAnalysisTaskPHOSObjectCreator::CoreEnergy(AliVCluster *clu, AliVCaloCells *cells)
{
//calculate energy of the cluster in the circle with radius distanceCut around the maximum
//Can not use already calculated coordinates?
//They have incidence correction...
const Double_t distanceCut =3.5;//default value
const Double_t logWeight=4.5;
const Double32_t * elist = clu->GetCellsAmplitudeFraction() ;
// Calculates the center of gravity in the local PHOS-module coordinates
Float_t wtot = 0;
const Int_t mulDigit=clu->GetNCells() ;
Double_t xc[mulDigit] ;
Double_t zc[mulDigit] ;
Double_t ei[mulDigit] ;
Double_t x = 0 ;
Double_t z = 0 ;
for(Int_t iDigit=0; iDigit<mulDigit; iDigit++) {
Int_t relid[4] ;
Float_t xi ;
Float_t zi ;
fPHOSGeo->AbsToRelNumbering(clu->GetCellAbsId(iDigit), relid) ;
fPHOSGeo->RelPosInModule(relid, xi, zi);
xc[iDigit]=xi ;
zc[iDigit]=zi ;
ei[iDigit]=elist[iDigit]*cells->GetCellAmplitude(clu->GetCellsAbsId()[iDigit]);
if( fDebug >= 3 )
printf("%f ",ei[iDigit]);
if (clu->E()>0 && ei[iDigit]>0) {
Float_t w = TMath::Max( 0., logWeight + TMath::Log( ei[iDigit] / clu->E() ) ) ;
x += xc[iDigit] * w ;
z += zc[iDigit] * w ;
wtot += w ;
}
}
if (wtot>0) {
x /= wtot ;
z /= wtot ;
}
Double_t coreE=0. ;
for(Int_t iDigit=0; iDigit < mulDigit; iDigit++) {
Double_t distance = TMath::Sqrt((xc[iDigit]-x)*(xc[iDigit]-x)+(zc[iDigit]-z)*(zc[iDigit]-z)) ;
if(distance < distanceCut)
coreE += ei[iDigit] ;
}
//Apply non-linearity correction
return fNonLinCorr->Eval(coreE);
}
//________________________________________________________________________
Double_t AliAnalysisTaskPHOSObjectCreator::CoreEnergy(AliVCluster *clu)
{
//calculate energy of the cluster in the circle with radius distanceCut around the maximum
//Can not use already calculated coordinates?
//They have incidence correction...
const Double_t distanceCut =3.5 ;
const Double_t logWeight=4.5 ;
Double32_t * elist = clu->GetCellsAmplitudeFraction() ;
// Calculates the center of gravity in the local PHOS-module coordinates
Float_t wtot = 0;
Double_t xc[100]={0} ;
Double_t zc[100]={0} ;
Double_t x = 0 ;
Double_t z = 0 ;
Int_t mulDigit=TMath::Min(100,clu->GetNCells()) ;
for(Int_t iDigit=0; iDigit<mulDigit; iDigit++) {
Int_t relid[4] ;
Float_t xi ;
Float_t zi ;
fPHOSGeo->AbsToRelNumbering(clu->GetCellAbsId(iDigit), relid) ;
fPHOSGeo->RelPosInModule(relid, xi, zi);
xc[iDigit]=xi ;
zc[iDigit]=zi ;
if (clu->E()>0 && elist[iDigit]>0) {
Float_t w = TMath::Max( 0., logWeight + TMath::Log( elist[iDigit] / clu->E() ) ) ;
x += xc[iDigit] * w ;
z += zc[iDigit] * w ;
wtot += w ;
}
}
if (wtot>0) {
x /= wtot ;
z /= wtot ;
}
Double_t coreE=0. ;
for(Int_t iDigit=0; iDigit < mulDigit; iDigit++) {
Double_t distance = TMath::Sqrt((xc[iDigit]-x)*(xc[iDigit]-x)+(zc[iDigit]-z)*(zc[iDigit]-z)) ;
if(distance < distanceCut)
coreE += elist[iDigit] ;
}
//Apply non-linearity correction
return coreE ;
}
//________________________________________________________________________
void AliAnalysisTaskPHOSObjectCreator::EvalLambdas(AliVCluster * clu, Double_t &m02, Double_t &m20)
{
//calculate dispecrsion of the cluster in the circle with radius distanceCut around the maximum
const Double_t rCut=4.5 ;
Double32_t * elist = clu->GetCellsAmplitudeFraction() ;
// Calculates the center of gravity in the local PHOS-module coordinates
Float_t wtot = 0;
Double_t xc[100]={0} ;
Double_t zc[100]={0} ;
Double_t x = 0 ;
Double_t z = 0 ;
Int_t mulDigit=TMath::Min(100,clu->GetNCells()) ;
const Double_t logWeight=4.5 ;
for(Int_t iDigit=0; iDigit<mulDigit; iDigit++) {
Int_t relid[4] ;
Float_t xi ;
Float_t zi ;
fPHOSGeo->AbsToRelNumbering(clu->GetCellAbsId(iDigit), relid) ;
fPHOSGeo->RelPosInModule(relid, xi, zi);
xc[iDigit]=xi ;
zc[iDigit]=zi ;
if (clu->E()>0 && elist[iDigit]>0) {
Float_t w = TMath::Max( 0., logWeight + TMath::Log( elist[iDigit] / clu->E() ) ) ;
x += xc[iDigit] * w ;
z += zc[iDigit] * w ;
wtot += w ;
}
}
if (wtot>0) {
x /= wtot ;
z /= wtot ;
}
wtot = 0. ;
Double_t dxx = 0.;
Double_t dzz = 0.;
Double_t dxz = 0.;
Double_t xCut = 0. ;
Double_t zCut = 0. ;
for(Int_t iDigit=0; iDigit<mulDigit; iDigit++) {
if (clu->E()>0 && elist[iDigit]>0.) {
Double_t w = TMath::Max( 0., logWeight + TMath::Log( elist[iDigit] / clu->E() ) ) ;
Double_t xi= xc[iDigit] ;
Double_t zi= zc[iDigit] ;
if((xi-x)*(xi-x)+(zi-z)*(zi-z) < rCut*rCut){
xCut += w * xi ;
zCut += w * zi ;
dxx += w * xi * xi ;
dzz += w * zi * zi ;
dxz += w * xi * zi ;
wtot += w ;
}
}
}
if (wtot>0) {
xCut/= wtot ;
zCut/= wtot ;
dxx /= wtot ;
dzz /= wtot ;
dxz /= wtot ;
dxx -= xCut * xCut ;
dzz -= zCut * zCut ;
dxz -= xCut * zCut ;
m02 = 0.5 * (dxx + dzz) + TMath::Sqrt( 0.25 * (dxx - dzz) * (dxx - dzz) + dxz * dxz ) ;
m20 = 0.5 * (dxx + dzz) - TMath::Sqrt( 0.25 * (dxx - dzz) * (dxx - dzz) + dxz * dxz ) ;
}
else {
m20=m02=0.;
}
}
//________________________________________________________________________
Int_t AliAnalysisTaskPHOSObjectCreator::FindTrackMatching(Int_t mod,TVector3 *locpos, Double_t &dx, Double_t &dz, Double_t &pt,Int_t &charge)
{
//Find track with closest extrapolation to cluster
AliESDEvent *esd = fESDEvent;
AliAODEvent *aod = fAODEvent;
if(!esd && !aod){
AliError("Neither AOD nor ESD was found") ;
return -1;
}
Double_t magF =0.;
if(esd)
magF = esd->GetMagneticField();
if(aod)
magF = aod->GetMagneticField();
Double_t magSign = 1.0;
if(magF<0)magSign = -1.0;
if (!TGeoGlobalMagField::Instance()->GetField()) {
AliError("Margnetic filed was not initialized, use default") ;
AliMagF* field = new AliMagF("Maps","Maps", magSign, magSign, AliMagF::k5kG);
TGeoGlobalMagField::Instance()->SetField(field);
}
// *** Start the matching
Int_t nt = 0;
if(esd)
nt = esd->GetNumberOfTracks();
else
nt = aod->GetNumberOfTracks();
//Calculate actual distance to PHOS module
TVector3 globaPos ;
fPHOSGeo->Local2Global(mod, 0.,0., globaPos) ;
const Double_t rPHOS = globaPos.Pt() ; //Distance to center of PHOS module
const Double_t kYmax = 72.+10. ; //Size of the module (with some reserve) in phi direction
const Double_t kZmax = 64.+10. ; //Size of the module (with some reserve) in z direction
const Double_t kAlpha0=330./180.*TMath::Pi() ; //First PHOS module angular direction
const Double_t kAlpha= 20./180.*TMath::Pi() ; //PHOS module angular size
Double_t minDistance = 1.e6;
Double_t gposTrack[3] ;
Double_t bz = ((AliMagF*)TGeoGlobalMagField::Instance()->GetField())->SolenoidField();
bz = TMath::Sign(0.5*kAlmost0Field,bz) + bz;
Double_t b[3];
Int_t itr=-1 ;
AliESDtrack *esdTrack=0x0 ;
AliAODTrack *aodTrack=0x0 ;
Double_t xyz[3] = {0}, pxpypz[3] = {0}, cv[21] = {0};
for (Int_t i=0; i<nt; i++) {
if(esd)
esdTrack=esd->GetTrack(i);
else
aodTrack=(AliAODTrack*)aod->GetTrack(i);
// Skip the tracks having "wrong" status (has to be checked/tuned)
if(esd){
ULong_t status = esdTrack->GetStatus();
if((status & AliESDtrack::kTPCout) == 0) continue;
}
else{
}
//Continue extrapolation from TPC outer surface
AliExternalTrackParam outerParam;
if(esdTrack){
outerParam = *(esdTrack->GetOuterParam());
}
if(aodTrack){
aodTrack->GetPxPyPz(pxpypz);
aodTrack->GetXYZ(xyz);
aodTrack->GetCovarianceXYZPxPyPz(cv);
outerParam.Set(xyz,pxpypz,cv,aodTrack->Charge());
}
Double_t z;
if(!outerParam.GetZAt(rPHOS,bz,z))
continue ;
if (TMath::Abs(z) > kZmax)
continue; // Some tracks miss the PHOS in Z
//Direction to the current PHOS module
Double_t phiMod=kAlpha0-kAlpha*mod ;
if(!outerParam.RotateParamOnly(phiMod)) continue ; //RS use faster rotation if errors are not needed
Double_t y; // Some tracks do not reach the PHOS
if (!outerParam.GetYAt(rPHOS,bz,y)) continue; // because of the bending
if(TMath::Abs(y) < kYmax){
outerParam.GetBxByBz(b) ;
outerParam.PropagateToBxByBz(rPHOS,b); // Propagate to the matching module
//outerParam.CorrectForMaterial(...); // Correct for the TOF material, if needed
outerParam.GetXYZ(gposTrack) ;
TVector3 globalPositionTr(gposTrack) ;
TVector3 localPositionTr ;
fPHOSGeo->Global2Local(localPositionTr,globalPositionTr,mod) ;
Double_t ddx = locpos->X()-localPositionTr.X();
Double_t ddz = locpos->Z()-localPositionTr.Z();
Double_t d2 = ddx*ddx + ddz*ddz;
if(d2 < minDistance) {
dx = ddx ;
dz = ddz ;
minDistance=d2 ;
itr=i ;
if(esdTrack){
pt=esdTrack->Pt() ;
charge=esdTrack->Charge() ;
}
else{
pt=aodTrack->Pt() ;
charge=aodTrack->Charge() ;
}
}
}
}//Scanned all tracks
return itr ;
}
//________________________________________________________________________
void AliAnalysisTaskPHOSObjectCreator::DistanceToBadChannel(Int_t mod, TVector3 * locPos, Double_t &minDist)
{
//Check if distance to bad channel was reduced
Int_t range = minDist/2.2 +1 ; //Distance at which bad channels should be serached
Int_t relid[4]={0,0,0,0} ;
fPHOSGeo->RelPosToRelId(mod, locPos->X(), locPos->Z(), relid) ;
Int_t xmin=TMath::Max(1,relid[2]-range) ;
Int_t xmax=TMath::Min(64,relid[2]+range) ;
Int_t zmin=TMath::Max(1,relid[3]-range) ;
Int_t zmax=TMath::Min(56,relid[3]+range) ;
Float_t x=0.,z=0.;
for(Int_t ix=xmin;ix<=xmax;ix++){
for(Int_t iz=zmin;iz<=zmax;iz++){
if(fPHOSBadMap[mod] && fPHOSBadMap[mod]->GetBinContent(ix,iz)>0){ //Bad channel
Int_t relidBC[4]={mod,0,ix,iz} ;
fPHOSGeo->RelPosInModule(relidBC,x,z);
Double_t dist = TMath::Sqrt((x-locPos->X())*(x-locPos->X()) + (z-locPos->Z())*(z-locPos->Z()));
if(dist<minDist) minDist = dist;
}
}
}
}
//________________________________________________________________________
Int_t AliAnalysisTaskPHOSObjectCreator::FindPrimary(AliCaloPhoton *ph, Bool_t&sure)
{
//Finds primary and estimates if it unique one?
//First check can it be photon/electron
AliVCluster *clu = (AliVCluster*)ph->GetCluster();
const Double_t emFraction=0.9; //part of energy of cluster to be assigned to EM particle
Int_t n = clu->GetNLabels();
if(fESDEvent){
return clu->GetLabel();
}
else if(fAODEvent){
for(Int_t i=0; i<n; i++){
Int_t label = clu->GetLabelAt(i);
AliAODMCParticle *p = (AliAODMCParticle*)fMCArrayAOD->At(label);
Int_t pdg = p->PdgCode() ;
if(pdg==22 || pdg==11 || pdg == -11){
if(p->E()>emFraction*clu->E()){
sure=kTRUE ;
return label;
}
}
}
Double_t *Ekin = new Double_t[n];
for(Int_t i=0; i<n; i++){
Int_t label = clu->GetLabelAt(i);
AliAODMCParticle* p = (AliAODMCParticle*)fMCArrayAOD->At(label);
Ekin[i]=p->P() ; // estimate of kinetic energy
if(p->PdgCode()==-2212 || p->PdgCode()==-2112){
Ekin[i]+=1.8 ; //due to annihilation
}
}
Int_t iMax=0;
Double_t eMax=0.,eSubMax=0. ;
for(Int_t i=0; i<n; i++){
if(Ekin[i]>eMax){
eSubMax=eMax;
eMax=Ekin[i];
iMax=i;
}
}
if(eSubMax>0.8*eMax)//not obvious primary
sure=kFALSE;
else
sure=kTRUE;
delete[] Ekin;
return clu->GetLabelAt(iMax);
}
else{
return clu->GetLabel();
}
}
//________________________________________________________________________
Bool_t AliAnalysisTaskPHOSObjectCreator::PassSTDCut(AliVCluster *cluster)
{
if(cluster->E() > 1.0 && cluster->GetM02() < 0.1) return kFALSE;
else return kTRUE;
}
//________________________________________________________________________
void AliAnalysisTaskPHOSObjectCreator::EstimateSTDCutEfficiency(TClonesArray *array)
{
const Int_t multClust = array->GetEntriesFast();
TLorentzVector p12;
Double_t m12=0;
Double_t energy=0;
for(Int_t i1=0;i1<multClust;i1++){
AliCaloPhoton *ph1 = (AliCaloPhoton*)array->At(i1);
if(ph1->GetNsigmaCoreDisp() > 3.0) continue;
if(ph1->Energy() < 0.5) continue;
for(Int_t i2=0;i2<multClust;i2++){
AliCaloPhoton *ph2 = (AliCaloPhoton*)array->At(i2);
AliVCluster *cluster = (AliVCluster*)ph2->GetCluster();
if(i2==i1) continue;//reject same cluster combination
p12 = *ph1 + *ph2;
m12 = p12.M();
energy = ph2->Energy();
fHistoMggvsEProbe->Fill(m12,energy);
if(PassSTDCut(cluster)) fHistoMggvsEPassingProbe->Fill(m12,energy);
}//end of ph2
}//end of ph1
}
|
[
"daiki.sekihata@cern.ch"
] |
daiki.sekihata@cern.ch
|
d6600819ba7c80e418b08d70a15f648c7d90c525
|
7de07a6709e001bf361ff97068f2ad4d2a119da8
|
/CubeSolverENG4/CubeSolverENG4/CubeSolver.cpp
|
af0ebd755f26981f9eb59226419e1bfa084df43d
|
[] |
no_license
|
VB6Hobbyst7/PolycubeSolver
|
66959aefb28d1079c65e07a5bfca9325ddc89089
|
e12d76071285572e97440e6ab058d2606b988a67
|
refs/heads/master
| 2021-12-14T19:11:02.130941
| 2017-05-22T08:29:10
| 2017-05-22T08:29:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,203
|
cpp
|
/*
* File: CubeSolver.cpp *
*
* Created on April 8, 2016, 2:13 PM
*/
using namespace std;
#include "definitions.h"
#include "dlxSolver.h"
#include "cubeConfig.h"
#include "puzzlePiece.h"
long NUMGAMEPIECES;
typedef std::vector<long> puzzlePieceIdent;
#define ONE_SOLUTION 1
#define ALL_SOLUTIONS 1000000
int main(int argc, char** argv) {
long cubeDimSize;
long numOfSolutions;
long pieceSize;
long pieceIdent;
long** puzzlePiecesXYZ;
puzzlePieceIdent* solution;
cubeConfig* puzzleCube = new cubeConfig();
if(argc == 2 && argv[1][0]=='1')
numOfSolutions = ONE_SOLUTION;
else if (argc == 2 && argv[1][0]=='a')
numOfSolutions = ALL_SOLUTIONS;
else
numOfSolutions = ONE_SOLUTION;
std::ifstream fin(argv[2]);
if (!fin.is_open()){
cerr<<"Could not open file"<<endl;
exit(1);
}
fin >> cubeDimSize;
cout << cubeDimSize <<endl;
fin >> NUMGAMEPIECES;
cout << NUMGAMEPIECES<<endl;
puzzlePiecesXYZ = new long*[NUMGAMEPIECES];
/*Read in all game pieces*/
for(long piece = 0; piece < NUMGAMEPIECES;piece++){
fin >> pieceIdent;
fin >> pieceSize;
/*Read in unit cubes for single puzzle piece*/
for (long row = 0; row < pieceSize; row++) {
puzzlePiecesXYZ[row] = new long[3];
fin>>(puzzlePiecesXYZ[row])[X];
fin>>(puzzlePiecesXYZ[row])[Y];
fin>>(puzzlePiecesXYZ[row])[Z];
}
puzzleCube->addPuzzlePiece(pieceIdent,pieceSize,puzzlePiecesXYZ);
}
puzzlePiecePtr* winningPuzzlePieces = new puzzlePiecePtr[NUMGAMEPIECES];
PieceConfigSets* puzzlePieces = &(puzzleCube->getAllBitSets());
dlxSolver solver(numOfSolutions,puzzlePieces);
if (solver.findSolutions()) {
long i = 0;
solution = solver.getSolution(1);
for (long ident : (*solution)) {
winningPuzzlePieces[i] = puzzleCube->getPuzzlePieceNum(ident);
winningPuzzlePieces[i]->printPuzzlePiece();
i++;
}
}
delete(puzzleCube);
return 0;
}
|
[
"artur.prusinowski@gmail.com"
] |
artur.prusinowski@gmail.com
|
43dc1f3c4f670bc92051625d930e9c9568d08b3e
|
b8dbc3c7a55c0bdb5f8e077f0b2d8c1a032c9eb9
|
/tst-endian.cc
|
84c8282b845ac5e218eeb408995aca5829f16d6f
|
[] |
no_license
|
thuermann/cc.endian
|
8f9bfc2a1879927a60a37a2a051fd924dc22c4ae
|
4fc9d4191cfb6f2a0d4090004a84cb8d1e4c6067
|
refs/heads/master
| 2020-03-15T12:22:07.213569
| 2017-11-30T10:19:54
| 2017-11-30T10:19:54
| 132,141,777
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 760
|
cc
|
//
// $Id: tst-endian.cc,v 1.4 2017/11/30 10:19:54 urs Exp $
//
#include "endian.hh"
be<short> n, m, k = 0x1234;
be<int> a, b, c = 0x42;
be<long> x, y, z = 0x0815;
short s1, s2;
int i1, i2;
long l1, l2;
int main()
{
k = 42;
c = 666;
z = 4711;
n = s1;
s2 = m;
a = i1;
i2 = b;
x = l1;
l2 = y;
}
void bar (void)
{
n *= 2;
m *= 3;
k /= 4;
a += b;
c -= a;
// The following is equivalent to b += 10.
b += 4;
b += 6;
// The following two stmts are a NOP and could be
// completely eliminated.
x++;
--x;
// The following is equivalent to y += 2.
y++;
++y;
// The following is equivalent to l1 = l2 = z.
l1 = z++;
l2 = --z;
}
int foo()
{
int s = 0;
for (be<int> i = 0; i < 10; i++)
s += i;
return s;
}
|
[
"urs@isnogud.escape.de"
] |
urs@isnogud.escape.de
|
6c66e7fbae190b5c1ed1bffcba0c0d38f5125cef
|
47d89cd67ce335c6125a70174938b755cd2958ef
|
/chapter15/webServer-v2.cpp
|
2403adef2ec36e4040d8bb217624bfc1959964a0
|
[] |
no_license
|
sleep-jyx/webServer
|
f351ade24526c6d20e262d682e80de50d2b980cd
|
295a233bf2c0768d2995d5978cc4b776cc42d234
|
refs/heads/main
| 2023-07-03T04:08:24.535153
| 2021-07-29T13:41:39
| 2021-07-29T13:41:39
| 390,714,596
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,737
|
cpp
|
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <cassert>
#include <sys/epoll.h>
#include "locker.h"
#include "threadpool.h"
#include "http_conn.h"
#define MAX_FD 65536
#define MAX_EVENT_NUMBER 10000
extern int addfd(int epollfd, int fd, bool one_shot);
extern int removefd(int epollfd, int fd);
void addsig(int sig, void(handler)(int), bool restart = true)
{
struct sigaction sa;
memset(&sa, '\0', sizeof(sa));
sa.sa_handler = handler;
if (restart)
{
sa.sa_flags |= SA_RESTART;
}
sigfillset(&sa.sa_mask);
assert(sigaction(sig, &sa, NULL) != -1);
}
void show_error(int connfd, const char *info)
{
printf("%s", info);
send(connfd, info, strlen(info), 0);
close(connfd);
}
int main(int argc, char *argv[])
{
if (argc <= 2)
{
printf("usage: %s ip_address port_number\n", basename(argv[0]));
return 1;
}
const char *ip = argv[1];
int port = atoi(argv[2]);
addsig(SIGPIPE, SIG_IGN);
threadpool<http_conn> *pool = NULL;
try
{
pool = new threadpool<http_conn>;
printf("--debug--:创建线程池成功\n");
}
catch (...)
{
return 1;
}
http_conn *users = new http_conn[MAX_FD];
assert(users);
int user_count = 0;
int listenfd = socket(PF_INET, SOCK_STREAM, 0);
assert(listenfd >= 0);
struct linger tmp = {1, 0};
setsockopt(listenfd, SOL_SOCKET, SO_LINGER, &tmp, sizeof(tmp));
int ret = 0;
struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_family = AF_INET;
inet_pton(AF_INET, ip, &address.sin_addr);
address.sin_port = htons(port);
ret = bind(listenfd, (struct sockaddr *)&address, sizeof(address));
assert(ret >= 0);
ret = listen(listenfd, 5);
assert(ret >= 0);
epoll_event events[MAX_EVENT_NUMBER];
int epollfd = epoll_create(5);
assert(epollfd != -1);
addfd(epollfd, listenfd, false);
http_conn::m_epollfd = epollfd;
while (true)
{
int number = epoll_wait(epollfd, events, MAX_EVENT_NUMBER, -1);
if ((number < 0) && (errno != EINTR))
{
printf("epoll failure\n");
break;
}
for (int i = 0; i < number; i++)
{
int sockfd = events[i].data.fd;
//轮询服务器
if (sockfd == listenfd)
{
printf("--debug--:主线程轮询到服务器\n");
struct sockaddr_in client_address;
socklen_t client_addrlength = sizeof(client_address);
int connfd = accept(listenfd, (struct sockaddr *)&client_address, &client_addrlength);
if (connfd < 0)
{
printf("errno is: %d\n", errno);
continue;
}
if (http_conn::m_user_count >= MAX_FD)
{
show_error(connfd, "Internal server busy");
continue;
}
//主线程创建一个HTTP服务器对象,让其处理客户请求
users[connfd].init(connfd, client_address);
}
//客户连接退出
else if (events[i].events & (EPOLLRDHUP | EPOLLHUP | EPOLLERR))
{
printf("--debug--:有客户连接退出\n");
users[sockfd].close_conn();
}
//客户连接有请求到来,需要主线程去读
else if (events[i].events & EPOLLIN)
{
printf("--debug--:客户连接有请求到来,需要主线程去读\n");
if (users[sockfd].read())
{ //http服务器对象成功读取了客户的请求数据,将该请求数据插入到请求队列上
printf("--debug--:http服务器对象成功读取了客户的请求数据,将该请求数据插入到请求队列上\n");
pool->append(users + sockfd);
}
else
{
users[sockfd].close_conn();
}
}
//客户连接请求数据,
else if (events[i].events & EPOLLOUT)
{
printf("--debug--:客户连接请求数据\n");
if (!users[sockfd].write())
{
users[sockfd].close_conn();
}
}
else
{
}
}
}
close(epollfd);
close(listenfd);
delete[] users;
delete pool;
return 0;
}
|
[
"1608713140@qq.com"
] |
1608713140@qq.com
|
56e243fc97ece22fed718d9f43f4f026d37fb888
|
448ee86f1acde912aebb4a03065cb4dad396c729
|
/bakaengine/game/scene/gameobject.h
|
06d0621a32fb11bd3594aa8710a96d71c7d93bdd
|
[] |
no_license
|
eplightning/bakaengine
|
7f9ac9f24ba688f004b65e1b8c4ca5885bdb545a
|
1c58d19fd302dba259979daec42c6ad7e3130988
|
refs/heads/master
| 2016-08-11T07:45:46.418760
| 2015-10-02T14:43:12
| 2015-10-02T14:43:12
| 43,558,706
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,142
|
h
|
#ifndef GAME_SCENE_GAMEOBJECT_H
#define GAME_SCENE_GAMEOBJECT_H
#include "bakaglobal.h"
#include <glm/vec3.hpp>
#include <glm/mat4x4.hpp>
#include "game/scene/component.h"
namespace Baka
{
class Scene;
class GameObject {
public:
explicit GameObject(Scene *scene);
virtual ~GameObject();
virtual const char* GetName();
virtual const char* GetID();
virtual VisibleComponent* GetVisibleComponent();
virtual PhysicalComponent* GetPhysicalComponent();
virtual LightComponent* GetLightComponent();
virtual bool IsActor() const;
virtual void Update(double dt);
bool IsDying(bool die = false);
protected:
Scene *scene_;
bool dying_;
};
class GameActor : public GameObject {
public:
explicit GameActor(Scene *scene);
const char* GetName() override;
const char* GetID() override;
glm::vec3& GetPosition();
glm::vec3& GetRotation();
float& GetScale();
const Mat4& GetModelMatrix() const;
bool IsActor() const override;
void UpdateModelMatrix();
protected:
virtual Mat4 CalculateModelMatrix() const;
Vec3 position_;
Vec3 rotation_;
float scale_;
Mat4 model_matrix_;
};
}
#endif
|
[
"eplightning@outlook.com"
] |
eplightning@outlook.com
|
150be5d375f7f99308fa8ab2b19b326da4569f1d
|
11228887a9e68aba52c68a9c3c116461c1122c74
|
/EngineMechanics/MathManipulations.h
|
372b9abe9f20c63a5e1ca7032cdaf0c299615b52
|
[] |
no_license
|
mgoulet/phase4
|
ddc348d7e3dc58f6e5778f6649973fa24e882a6d
|
15de636b55c273d36884cebcd27708f044204dca
|
refs/heads/master
| 2016-09-06T00:20:31.478035
| 2011-12-21T21:13:14
| 2011-12-21T21:13:14
| 3,029,498
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,123
|
h
|
////////////////////////////////////////////////
// Martin Goulet
// Project:
// MathManipulations.h
////////////////////////////////////////////////
/*
NOTE: This namespace does NOT contain the manipulations found
in the PrimitiveManipulations from the previous version
of the project.
*/
#ifndef MATHMANIPULATIONS_H
#define MATHMANIPULATIONS_H
#include <iostream>
#include <deque>
#include <cmath>
#include "MathEntities.h"
using namespace std;
namespace MathManipulations
{
//explicit vectorial operator overloaders
bool AddVEC (VEC& vtarget_ref, const VEC& v_ref);
bool AddVEC (VEC& vtarget_ref, const VEC& v1_ref, const VEC& v2_ref);
bool SubVEC (VEC& vtarget_ref, const VEC& v1_ref);
bool SubVEC (VEC& vtarget_ref, const VEC& v1_ref, const VEC& v2_ref);
bool MulVEC (VEC& vtarget_ref, float f);
//trivial structure manipulations
float SizVEC (const VEC& v_ref);
bool InvVEC (VEC& v_ref);
bool NorVEC (VEC& v_ref);
bool CroVEC (VEC& vtarget_ref, const VEC& v1_ref, const VEC& v2_ref);
float DotVEC (const VEC& v1_ref, const VEC& v2_ref);
float RtsCHK (float fCentreBit, float fErrorBit, float fResultToClassify);
float FndDeg (const VEC& v1_ref, const VEC& v2_ref);
//compound structure manipulations
bool PrlCHK (const PLN& pln_ref, const TRI& tri_ref);
bool IntLINPLN (VEC& v_ref, const LIN& lin_ref, const PLN& pln_ref);
bool IntSEGPLN (VEC& v_ref, const LIN& lin_ref, const PLN& pln_ref);
bool IntRAYPLN (VEC& v_ref, const LIN& lin_ref, const PLN& pln_ref);
//3X3 matrix manipulations
float DetMtx3X3 (const M3X3& m3x3_ref);
bool RotMtx3X3 (VEC& vtarget_ref, const VEC& vxis_ref, float fAngle);
bool MulMtx3X3 (M3X3& m3x3_ref, float f);
bool MulMtx3X3 (M3X3& m3x3target_ref, const M3X3& m3x3_ref);
bool TrsMtx3X3 (M3X3& m3x3_ref);
bool InvMtx3X3 (M3X3& m3x3_ref);
//4X4 matrix manipulations
bool CpyMtx4X4 (M4X4& m4x4_ref, const M3X3& m3x3_ref);
bool MulMtx4X4 (M4X4& m4x4_ref, float f);
bool MulMtx4X4 (M4X4& m4x4target_ref, const M4X4& m4x4_ref);
bool MulMtx4X4 (VEC& vtarget_ref, const M4X4& m4x4_ref, const VEC& v_ref);
};
#endif MATHMANIPULATIONS_H
|
[
"martin.goulet@gmail.com"
] |
martin.goulet@gmail.com
|
3c118f1953ba44c1b079ec3e012753e1b0a7eafa
|
9e0b3515b9489811570035f40b2693fe2247076c
|
/TdxPlugin/winds/TDXGfcx.cpp
|
60ef3440ad8c9ed1664872c0703145022ed4b357
|
[] |
no_license
|
locustwei/WorkBack
|
8118d3f0dc61a0d5958d0878e26e6ea650f5a765
|
bd4ef7838142caddd24c77ea469ac68ed1f87498
|
refs/heads/master
| 2020-03-26T14:49:25.049620
| 2018-08-17T03:50:00
| 2018-08-17T03:50:00
| 145,006,896
| 4
| 5
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,209
|
cpp
|
/************************************************************************
股份查询窗口
************************************************************************/
#include "TDXGfcx.h"
#include <string.h>
#include <stdlib.h>
#include <commctrl.h>
#pragma warning( disable : 4244)
CTDXZjgf::CTDXZjgf(HWND hWnd):CWndHook(hWnd)
{
m_l628 = GetDlgItem(hWnd, 0x0628);
m_lst61F = GetDlgItem(hWnd, 0x061F);
}
CTDXZjgf::~CTDXZjgf(void)
{
}
BOOL CTDXZjgf::GetStatisticsValue(float& ye, float& ky, float& sz, float& yk)
{
if(m_l628==NULL)
return FALSE;
TCHAR szText[200] = {0};
GetWindowText(m_l628, szText, 200);
TCHAR szValue[20] = {0};
LPCTSTR tmp = wcsstr(szText, L"余额:");
if(!tmp)
return FALSE;
tmp += 3;
for (int i=0; tmp[i] != ' ' && tmp[i] != 0; i++){
szText[i] = tmp[i];
}
ye = _wtof(szValue);
ZeroMemory(szValue, sizeof(szValue));
tmp = wcsstr(szText, L"可用:");
if(!tmp)
return FALSE;
tmp += 3;
for (int i=0; tmp[i] != ' ' && tmp[i] != 0; i++){
szText[i] = tmp[i];
}
ky = _wtof(szValue);
ZeroMemory(szValue, sizeof(szValue));
tmp = wcsstr(szText, L"参考市值:");
if(!tmp)
return FALSE;
tmp += 5;
for (int i=0; tmp[i] != ' ' && tmp[i] != 0; i++){
szText[i] = tmp[i];
}
sz = _wtof(szValue);
ZeroMemory(szValue, sizeof(szValue));
tmp = wcsstr(szText, L"盈亏:");
if(!tmp)
return FALSE;
tmp += 3;
for (int i=0; tmp[i] != ' ' && tmp[i] != 0; i++){
szText[i] = tmp[i];
}
yk = _wtof(szValue);
return TRUE;
}
int CTDXZjgf::GetGf(PTDX_STOCK_GF pGf)
{
if(!m_lst61F)
return FALSE;
int nCount = ListView_GetItemCount(m_lst61F);
for(int i=0; i<nCount; i++){
ListView_GetItemText(m_lst61F, i, 0, pGf[i].code, 6); //
ListView_GetItemText(m_lst61F, i, 1, pGf[i].name, 4);
TCHAR szText[20] = {0};
ListView_GetItemText(m_lst61F, i, 2, szText, 20);
pGf[i].sl = _wtoi(szText);
ListView_GetItemText(m_lst61F, i, 3, szText, 20);
pGf[i].kmsl = _wtoi(szText);
ListView_GetItemText(m_lst61F, i, 4, szText, 20);
pGf[i].jmsl = _wtoi(szText);
ListView_GetItemText(m_lst61F, i, 5, szText, 20);
pGf[i].ckcbj = _wtof(szText);
ListView_GetItemText(m_lst61F, i, 6, szText, 20);
pGf[i].mrjj = _wtof(szText);
ListView_GetItemText(m_lst61F, i, 7, szText, 20);
pGf[i].dqj = _wtof(szText);
ListView_GetItemText(m_lst61F, i, 8, szText, 20);
pGf[i].zxsz = _wtof(szText);
ListView_GetItemText(m_lst61F, i, 9, szText, 20);
pGf[i].ccyk = _wtof(szText);
ListView_GetItemText(m_lst61F, i, 10, szText, 20);
pGf[i].ykbl = _wtoi(szText);
ListView_GetItemText(m_lst61F, i, 11, szText, 20);
pGf[i].djsl = _wtoi(szText);
}
return nCount;
}
int CTDXZjgf::GetZjgf(_Out_ PTDX_STOCK_ZJGF* result)
{
int nSize = 0;
PTDX_STOCK_ZJGF tmp = NULL;
int nCount = ListView_GetItemCount(m_lst61F);
nSize = sizeof(TDX_STOCK_ZJGF) + nCount*sizeof(TDX_STOCK_GF);
tmp = (PTDX_STOCK_ZJGF)malloc(nSize);
ZeroMemory(tmp, nSize);
if(!GetStatisticsValue(tmp->ye, tmp->ky, tmp->sz, tmp->yk)){
free(tmp);
return 0;
}
tmp->count = GetGf(tmp->gf);
*result = tmp;
return nSize;
}
|
[
"locustwei@7198d612-9af8-4b9f-b382-878749309fc7"
] |
locustwei@7198d612-9af8-4b9f-b382-878749309fc7
|
cb7f24c9c803b776aef4e8adcd95c8acc69d6c90
|
7425b73c5c4301b73efee73a2a97c478e3d9c94f
|
/src/sleipnir/src/serverclient.cpp
|
1ebbc5032f750db6a5d7706a89ecb2f3f8de8a80
|
[
"CC-BY-3.0"
] |
permissive
|
mehdiAT/diseasequest-docker
|
318202ced87e5e5ed1bd609fe268ebc530c65e96
|
31943d2fafa8516b866fa13ff3d0d79989aef361
|
refs/heads/master
| 2020-05-15T01:21:21.530861
| 2018-04-16T22:42:34
| 2018-04-16T22:42:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,445
|
cpp
|
/*****************************************************************************
* This file is provided under the Creative Commons Attribution 3.0 license.
*
* You are free to share, copy, distribute, transmit, or adapt this work
* PROVIDED THAT you attribute the work to the authors listed below.
* For more information, please see the following web page:
* http://creativecommons.org/licenses/by/3.0/
*
* This file is a component of the Sleipnir library for functional genomics,
* authored by:
* Curtis Huttenhower (chuttenh@princeton.edu)
* Mark Schroeder
* Maria D. Chikina
* Olga G. Troyanskaya (ogt@princeton.edu, primary contact)
*
* If you use this library, the included executable tools, or any related
* code in your work, please cite the following publication:
* Curtis Huttenhower, Mark Schroeder, Maria D. Chikina, and
* Olga G. Troyanskaya.
* "The Sleipnir library for computational functional genomics"
*****************************************************************************/
#include "stdafx.h"
#include "serverclient.h"
#include "server.h"
namespace Sleipnir {
void* CServerClientImpl::StartRoutine( void* pArg ) {
CServerClientImpl* pClient;
pClient = (CServerClientImpl*)pArg;
pClient->StartRoutine( );
delete pClient;
return NULL; }
void CServerClientImpl::StartRoutine( ) {
do
ReadMessage( );
while( m_vecbMessage.size( ) && m_pClient->ProcessMessage( m_vecbMessage ) );
g_CatSleipnir( ).info( "Client 0x%08x disconnected", m_pClient ); }
CServerClientImpl::CServerClientImpl( SOCKET iSocket, IServerClient* pClient ) : m_iSocket(iSocket),
m_pClient(pClient) { }
CServerClientImpl::~CServerClientImpl( ) {
closesocket( m_iSocket );
m_pClient->Destroy( ); }
void CServerClientImpl::ReadMessage( ) {
unsigned char acBuffer[ c_iBuffer ];
size_t iRead, iTotal, iPrev;
m_vecbMessage.clear( );
if( !( iRead = recv( m_iSocket, (char*)acBuffer, c_iBuffer, 0 ) ) || ( iRead == -1 ) ||
( iRead < sizeof(uint32_t) ) )
return;
iTotal = *(uint32_t*)acBuffer;
m_vecbMessage.resize( max( iTotal, iPrev = iRead - sizeof(uint32_t) ) );
copy( acBuffer + sizeof(uint32_t), acBuffer + iRead, m_vecbMessage.begin( ) );
while( ( iPrev < iTotal ) && ( iRead = recv( m_iSocket, (char*)acBuffer, c_iBuffer, 0 ) ) ) {
if( ( iPrev + iRead ) >= m_vecbMessage.size( ) )
m_vecbMessage.resize( iPrev + iRead );
copy( acBuffer, acBuffer + iRead, m_vecbMessage.begin( ) + iPrev );
iPrev += iRead; } }
}
|
[
"vicyao@gmail.com"
] |
vicyao@gmail.com
|
eff5b860a4d2dfeec90fdec4fff3752d97cdfa9b
|
66169a2be2a38aa8b5090308d43b42c63549ca94
|
/Nesis/Common/Geometry/Point2D.h
|
e96e89c5d0336457b646b564adc4367da1b4f0e6
|
[] |
no_license
|
jpoirier/x-gauges
|
6a5a3b05673aeff8632908cdfc2975a0a07f75ee
|
8261b19a9678ad27db44eb8c354f5e66bd061693
|
refs/heads/master
| 2016-09-06T11:13:27.022707
| 2011-12-19T06:54:23
| 2011-12-19T06:54:23
| 1,551,637
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,286
|
h
|
#ifndef __POINT2D_H
#define __POINT2D_H
/***************************************************************************
* *
* Copyright (C) 2006 by Kanardia d.o.o. [see www.kanardia.eu] *
* Writen by: *
* Ales Krajnc [ales.krajnc@kanardia.eu] *
* *
* Status: Open Source *
* *
* License: GPL - GNU General Public License *
* See 'COPYING.html' for more details about the license. *
* *
***************************************************************************/
/*! \file Point2D.h
\brief Declaration file for the Point2D class.
\author Ales Krajnc
\date 1.1.2006 - ported from VisualStudio code.
*/
#include <iostream>
#include <QPoint>
#include "CommonDefs.h"
#include "Tolerance.h"
// ----------------------------------------------------------------------------
//! The geometry namespace combines geometry related classes.
namespace geometry {
// ----------------------------------------------------------------------------
//! This class implements a point in 2D space. Point is based on qreal precision.
/*! It is assumed that this point lies in the X-Y plain and
positive angles are measured counterclockwise. This defines righthand
Euclidian space where Z axis seems to be missing. But it is not. Z axis
is defined by positive \b counterclockwise rotation of positive angles
(righthand rule).
The class provides operator conversions to QPoint class.
The class is member of the #geometry namespace. Related classes are
Line2D ...
*/
class Point2D
{
public:
//! Default constructor.
Point2D(qreal x=0.0, qreal y=0.0)
{ m_dX=x; m_dY=y; }
//! Construct from QPoint.
Point2D(QPoint p)
{ m_dX=p.x(); m_dY=p.y(); }
//! Construct from QPointF.
Point2D(QPointF p)
{ m_dX=p.x(); m_dY=p.y(); }
//! Copy constructor.
Point2D(const Point2D& C)
{ Copy(C); }
//! Create a copy of given point.
void Copy(const Point2D& C)
{ m_dX = C.m_dX; m_dY = C.m_dY; }
//! The assignment operator.
const Point2D& operator=(const Point2D& p)
{ Copy(p); return *this; }
//! Sets the x coordinate.
void SetX(qreal dX)
{ m_dX = dX; }
//! Sets the y coordinate.
void SetY(qreal dY)
{ m_dY = dY; }
//! Returns the x coordinate.
qreal GetX() const
{ return m_dX; }
//! Returns the y coordinate.
qreal GetY() const
{ return m_dY; }
//! Offsets the current point by a given distance.
void Move(const Point2D& p)
{ m_dX+=p.m_dX; m_dY+=p.m_dY; }
//! Rotates the point around the origin for given angle.
void Rotate(qreal dAlpha);
//! Rotates the point around given point (move, rotate, move).
void Rotate(const Point2D& p, qreal dAlpha);
//! Calculates the distance between this and given point.
qreal GetDistance(const Point2D& p) const;
//! Calculates the angle between this point and given point p.
qreal GetAngle(const Point2D& p) const;
//! The difference between this and given point p returned as a new point.
Point2D operator-(const Point2D& p) const;
//! The sum of this and given point p returned as a new point.
Point2D operator+(const Point2D& p) const;
//! Negate the point.
Point2D operator-() const
{ return Point2D(-m_dX,-m_dY); }
//! Operator that converts this point to QPoint object.
operator QPoint() const
{ return QPoint((int)(m_dX+0.5),(int)(m_dY+0.5)); }
//! Operator that converts this point to QPointF object.
operator QPointF() const
{ return QPointF(m_dX, m_dY); }
//! Adds the given coordinates to the existing coordinates. Same as #Move.
void operator+=(const Point2D& p)
{ m_dX+=p.m_dX; m_dY+=p.m_dY; }
//! Subtracts the given coordinates from the existing coordinates.
void operator-=(const Point2D& p)
{ m_dX-=p.m_dX; m_dY-=p.m_dY; }
//! Compares for equality of two points using default relative tolerance.
bool operator==(const Point2D& p) const
{ return tolerance_rel::Equal(m_dX,p.m_dX)
&& tolerance_rel::Equal(m_dY,p.m_dY);}
//! Negation of the operator ==.
bool operator!=(const Point2D& p) const
{ return !operator==(p); }
//! Returns true if the first point has smaller coordinates than given point p.
bool operator<(const Point2D& p) const
{ return m_dX<p.m_dX && m_dY<p.m_dY; }
//! Compares for equality of two points using specified tolerance.
bool IsEqual(const Point2D& p, qreal dTolerance) const
{ return tolerance_rel::Equal(m_dX,p.m_dX, dTolerance)
&& tolerance_rel::Equal(m_dY,p.m_dY, dTolerance);}
//! Serializes the point to the data binary stream.
void Serialize(QDataStream& ds);
protected:
//! X coordinate.
qreal m_dX;
//! Y coordinate.
qreal m_dY;
};
//! Outputs the Point2D object to the out stream.
inline std::ostream& operator<<(std::ostream& out, const Point2D& p)
{
out << "(" << p.GetX() << "," << p.GetY() << ")";
return out;
}
//! Writes the Point2D object to the data stream object.
inline QDataStream& operator<<(QDataStream& ds, const Point2D& p)
{
const_cast<Point2D&>(p).Serialize(ds);
return ds;
}
//! Reads the Point2D object from the data stream object.
inline QDataStream& operator>>(QDataStream& ds, Point2D& p)
{
p.Serialize(ds);
return ds;
}
// --------------------------------------------------------
//! Special binary_function that sorts points.
class Point2DSortXLess : std::binary_function<Point2D, Point2D, bool>
{
public:
Point2DSortXLess() {}
result_type operator() (first_argument_type a, second_argument_type b)
{
return (a.GetX() < b.GetX()) ? true :
(a.GetX() == b.GetX()) ? a.GetY() <b.GetY() :
false;
}
};
}
// ----------------------------------------------------------------------------
#endif // __POINT2D_H
|
[
"devnull@localhost"
] |
devnull@localhost
|
36a723901a34ed927885bb473f277b346f288acc
|
380d95bcf755f0c227130454e02b1e8698b274a2
|
/cf637/a.cpp
|
aea0d32f27f6757a31f7826d999adbda23196538
|
[] |
no_license
|
geekpradd/CP-Topicwise
|
dd590ce94d0feb6b7a7037dd54e54a4b40041e77
|
5a257676171d0c4db71125ad3e872b338202fe16
|
refs/heads/master
| 2021-05-20T09:29:35.898564
| 2020-12-25T18:54:30
| 2020-12-25T18:54:30
| 252,225,116
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 846
|
cpp
|
#include <bits/stdc++.h>
#define int long long
#define ii pair<int, int>
#define pb push_back
#define mp make_pair
#define MOD 1000000007
#define E9 1000000000
using namespace std;
int power(int base, int exp){
if (exp==0)
return 1;
int res = power(base, exp/2);
res = (res*res)%MOD;
if (exp % 2)
return (res*base)%MOD;
return res;
}
int inverse(int n){
return power(n, MOD-2);
}
void solve(){
int n, a, b, c, d;
cin >> n >> a >> b >> c >> d;
bool pos = 0;
for (int i=c-d; i<=c+d; ++i){
if (i >= n*(a-b) && i<=n*(a+b)){
pos = 1;
break;
}
}
if (pos){
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
signed main(){
cin.tie(NULL); ios_base::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
int t; cin >> t;
for (int w=1; w<=t; ++w){
solve();
}
return 0;
}
|
[
"geekpradd@gmail.com"
] |
geekpradd@gmail.com
|
5b2c197c870e3fd962097338d6dd3d28cc715f42
|
91db922ced8fb4899e4fc5ad20179f07d738a99f
|
/ABC/043/C.cpp
|
3ce26c08b2e99d104fecc5bc72a266b92aeabdd2
|
[] |
no_license
|
hntk03/atcoder
|
d1bb795b9b9db2a689353eedcf6b9211d923b21b
|
cd024e1b6911765ef9239a72c2e25147922fa460
|
refs/heads/master
| 2022-10-08T05:35:24.339333
| 2022-10-02T03:12:55
| 2022-10-02T03:12:55
| 162,792,776
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 495
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> VI;
typedef vector<string> VS;
//container util
#define SORT(c) sort((c).begin(),(c).end())
//repetition
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
int main(void){
int N; cin >> N;
vector<int> a(N);
REP(i,N) cin >> a[i];
int ans = 1 << 30;
FOR(i,-100,101){
int sum = 0;
REP(j,N) sum += abs((int)pow(i-a[j],2));
ans = min(ans, sum);
}
cout << ans << endl;
return 0;
}
|
[
"hntk03@gmail.com"
] |
hntk03@gmail.com
|
db2b308ac3de5b31aa1a7e60bacb5f1475e861ef
|
e44283331c214e69f049d3d23b6350dbf2abbf32
|
/C++/starting c++/main.cpp
|
0f28ebff65ba46e79819c5cfdbe3df933b0b0900
|
[] |
no_license
|
Abiduddin/Competitive-Programming-Codes
|
cd2a8730998859d751e1891b4bc9bd3a790b8416
|
59b51b08c6f34c1bed941c8b86490ee9a250e5a9
|
refs/heads/master
| 2020-09-09T22:54:09.708942
| 2019-11-14T02:31:06
| 2019-11-14T02:31:06
| 221,588,892
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 170
|
cpp
|
#include <iostream>
int main()
{
int a,b,m;
std::cout<<"Enter two number"<<std::endl;
std::cin>>a>>b;
m=a+b;
std::cout<<"The sum "<<m<<std::endl;
}
|
[
"abidakash456@gmail.com"
] |
abidakash456@gmail.com
|
cc9a527b82712b86c0c112c04397fe5e5ef8f996
|
cec12808651cae020f66b95e17f73edd0c1b32fb
|
/src/Engine/Entity.cpp
|
dc583db3a3d5a8b3ee5ef7047e922bf294c47bb0
|
[] |
no_license
|
Bluest/BUJam2020
|
990cad38ff1f72f872abd4f316783d897e1a4fcc
|
bb0b161dd970cdbdd2e5fed3ab2bf54d6809f4fe
|
refs/heads/master
| 2021-03-02T03:19:05.486659
| 2020-03-13T13:48:50
| 2020-03-13T13:48:50
| 245,834,251
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 495
|
cpp
|
#include "Component.h"
#include "Entity.h"
void Entity::start()
{
for (auto it = components.begin(); it != components.end(); ++it)
{
(*it)->onStart();
}
}
void Entity::update()
{
for (auto it = components.begin(); it != components.end(); ++it)
{
(*it)->onUpdate();
}
}
void Entity::draw(SDL_Renderer* _renderer)
{
for (auto it = components.begin(); it != components.end(); ++it)
{
(*it)->onDraw(_renderer);
}
}
std::shared_ptr<Core> Entity::getCore()
{
return core.lock();
}
|
[
"oscarlh24@hotmail.com"
] |
oscarlh24@hotmail.com
|
d15f12b01322a7dc3974a28fd5a5a5d6580ff500
|
8f17795ece2ec5ee4261daede757ae6089cdf927
|
/src/test/base32_tests.cpp
|
93b02c9ed57c4b124f2d155e79cd943728ce0a20
|
[
"MIT"
] |
permissive
|
tatsuhirosato/momentum-beta
|
67da26495c74311826d14e8b0c2d5e79cb1a883c
|
faafc58e52d2404e9087b017b9345f797a2bae6f
|
refs/heads/master
| 2016-09-05T16:02:38.976468
| 2014-01-27T22:00:47
| 2014-01-27T22:00:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 648
|
cpp
|
#include <boost/test/unit_test.hpp>
#include "util.h"
BOOST_AUTO_TEST_SUITE(base32_tests)
BOOST_AUTO_TEST_CASE(base32_testvectors)
{
static const std::string vstrIn[] = {"","f","fo","PMM","PMMb","PMMba","PMMbar"};
static const std::string vstrOut[] = {"","my======","mzxq====","mzxw6===","mzxw6yq=","mzxw6ytb","mzxw6ytboi======"};
for (unsigned int i=0; i<sizeof(vstrIn)/sizeof(vstrIn[0]); i++)
{
std::string strEnc = EncodeBase32(vstrIn[i]);
BOOST_CHECK(strEnc == vstrOut[i]);
std::string strDec = DecodeBase32(vstrOut[i]);
BOOST_CHECK(strDec == vstrIn[i]);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
[
"luca@Host-001.homenet.telecomitalia.it"
] |
luca@Host-001.homenet.telecomitalia.it
|
fd5846979a9027e46b395dd03a86e1e7097620a9
|
77861deda8b3046bdda221d3cb80b77e84b14523
|
/conv_to_oct/speedup.cpp
|
2098ec3cc5b816324681ef7c94348590cae9abf9
|
[
"BSD-2-Clause"
] |
permissive
|
WojciechMula/toys
|
b73f09212ca19f1e76bbf2afaa5ad2efcea95175
|
6110b59de45dc1ce44388b21c6437eff49a7655c
|
refs/heads/master
| 2023-08-18T12:54:25.919406
| 2023-08-05T09:20:14
| 2023-08-05T09:20:14
| 14,905,115
| 302
| 44
|
BSD-2-Clause
| 2020-04-17T17:10:42
| 2013-12-03T20:35:37
|
C++
|
UTF-8
|
C++
| false
| false
| 3,505
|
cpp
|
/*
Convert to octal representation - measure speedup over naive version
Author : Wojciech Muła
Date : 2014-09-28
License : BSD
*/
#include <string>
#include <vector>
#include <sys/time.h>
#include <cstdio>
#include "conv.h"
class measure_item_t {
uint32_t t1;
uint32_t t2;
public:
const std::string name;
public:
measure_item_t(const std::string& name)
: name(name)
{}
public:
double get_time() const {
return (t2 - t1)/1000000.0;
}
double get_speedup(const measure_item_t& other) const {
return other.get_time()/get_time();
}
void start() {
t1 = get_current_time();
}
void stop() {
t2 = get_current_time();
}
private:
uint32_t get_current_time(void) {
static struct timeval T;
gettimeofday(&T, NULL);
return (T.tv_sec * 1000000) + T.tv_usec;
}
};
typedef std::vector<measure_item_t> results_t;
// ------------------------------------------------------------------------
void print_results(const results_t& results) {
auto bar = [](int n, char c) {
while (n-- > 0) {
putchar(c);
}
putchar('\n');
};
const int terminal_width = 79;
const int convert = 10;
const int time = 10;
const int speedup = 10;
printf("| %*s | %*s | %*s |\n",
-convert, "convert",
time, "time [s]",
speedup, "speedup");
bar(terminal_width, '-');
const auto& ref = results[0];
double max_speedup = 0;
for (const auto& m: results) {
max_speedup = std::max(max_speedup, m.get_speedup(ref));
}
for (const auto& m: results) {
const int n = printf("| %*s | %*.4f | %*.2f | ",
convert, m.name.c_str(),
time, m.get_time(),
speedup, m.get_speedup(ref)
);
const double f = m.get_speedup(ref)/max_speedup;
const int k = f * (terminal_width - n);
bar(k, '#');
}
}
void csv_results(FILE* f, const results_t& results) {
fprintf(f, "\"convert\",\"time [s]\",\"speedup\"\n");
const auto& ref = results[0];
for (const auto& m: results) {
fprintf(f, "\"%s\",%.4f,%0.2f\n",
m.name.c_str(),
m.get_time(),
m.get_speedup(ref)
);
}
}
// ------------------------------------------------------------------------
template <typename F>
measure_item_t measure(F convert, int iterations, const std::string& name) {
std::printf("measure %s... ", name.c_str());
std::fflush(stdout);
measure_item_t m(name);
m.start();
uint16_t word = 0;
while (iterations-- > 0) {
convert(word & 0x0fff);
word += 33;
}
m.stop();
std::printf("ok\n");
return m;
}
results_t measure() {
const int n = 100000000;
results_t res;
prepare_single_lookup();
res.push_back(measure(to_oct_naive, n, "naive"));
res.push_back(measure(to_oct_mul, n, "mul"));
res.push_back(measure(to_oct_sse2, n, "SSE2"));
#ifdef HAVE_PDEP_INSTRUCTION
res.push_back(measure(to_oct_pdep, n, "pdep"));
#endif
res.push_back(measure(to_oct_single_lookup, n, "1 LUT"));
res.push_back(measure(to_oct_two_lookups, n, "2 LUTs"));
return res;
}
// ------------------------------------------------------------------------
int main() {
const auto res = measure();
std::puts("");
print_results(res);
FILE* f = fopen("results.csv", "wb");
if (f) {
csv_results(f, res);
fclose(f);
}
}
|
[
"wojciech_mula@poczta.onet.pl"
] |
wojciech_mula@poczta.onet.pl
|
bea586836e8548a42b213f87184de73316bf03e8
|
0c2fb0e9ad4ae4094633a1fc56d1aface65a5f76
|
/src/fgmm/update.cpp
|
6cf39e11e3276fe1eca13f9e7b2b5f8f2d9664be
|
[] |
no_license
|
zhxinhust/motion_planner
|
6203958eb8b8196735edddc4f3f18f34523a7971
|
6e8006b1586c9d6457f18c032c6b9f6a8d683f7b
|
refs/heads/master
| 2021-05-14T18:42:22.789608
| 2018-01-22T01:35:21
| 2018-01-22T01:35:21
| 116,083,320
| 8
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,001
|
cpp
|
/*********************************************************************
FGMM: a fast(er) and light Gaussian mixture model implementation.
Copyright (C) 2010 Florent D'Halluin
Contact: florent.dhalluin@epfl.ch
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License,
version 3 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*********************************************************************/
#include "fgmm.h"
#include "gaussian.h"
void fgmm_update(struct gmm * gmm,const float * data_point)
{
int state_i=0;
float * pxi;
float nf = 0;
float eta = .05;
float weighted_lr;
pxi = (float *) malloc( sizeof(float) * gmm->nstates);
for(;state_i<gmm->nstates;state_i++)
{
pxi[state_i] = gaussian_pdf(&gmm->gauss[state_i], data_point);
nf += pxi[state_i];
}
for(state_i=0;state_i<gmm->nstates;state_i++)
{
weighted_lr = eta * pxi[state_i]/nf;
gaussian_update(&gmm->gauss[state_i],data_point,weighted_lr);
invert_covar(&gmm->gauss[state_i]);
}
free(pxi);
}
/* winner take all approach */
void fgmm_update_wta(struct gmm * gmm,const float * data_point)
{
int state_i=0;
int the_state = 0;
float eta = .05;
float max_p = 0.;
float w = 0.;
for(;state_i<gmm->nstates;state_i++)
{
w = gaussian_pdf(&gmm->gauss[state_i], data_point);
if(w>max_p)
{
max_p = w;
the_state = state_i;
}
}
gaussian_update(&gmm->gauss[the_state],data_point,eta);
invert_covar(&gmm->gauss[the_state]);
}
|
[
"zhaoxin@hust.edu.cn"
] |
zhaoxin@hust.edu.cn
|
a662aa30916fd2fb254a75e6f8ea668139db7933
|
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
|
/c++/ClickHouse/2015/8/StorageSystemMerges.cpp
|
17a6e21449fb973a385a11e580367db87c54cf1d
|
[] |
no_license
|
rosoareslv/SED99
|
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
|
a062c118f12b93172e31e8ca115ce3f871b64461
|
refs/heads/main
| 2023-02-22T21:59:02.703005
| 2021-01-28T19:40:51
| 2021-01-28T19:40:51
| 306,497,459
| 1
| 1
| null | 2020-11-24T20:56:18
| 2020-10-23T01:18:07
| null |
UTF-8
|
C++
| false
| false
| 3,704
|
cpp
|
#include <DB/Storages/StorageSystemMerges.h>
#include <DB/DataTypes/DataTypeString.h>
#include <DB/DataTypes/DataTypesNumberFixed.h>
#include <DB/Columns/ColumnString.h>
#include <DB/DataStreams/OneBlockInputStream.h>
#include <DB/Interpreters/Context.h>
#include <DB/Storages/MergeTree/MergeList.h>
namespace DB
{
StorageSystemMerges::StorageSystemMerges(const std::string & name)
: name{name}
, columns{
{ "database", new DataTypeString },
{ "table", new DataTypeString },
{ "elapsed", new DataTypeFloat64 },
{ "progress", new DataTypeFloat64 },
{ "num_parts", new DataTypeUInt64 },
{ "result_part_name", new DataTypeString },
{ "total_size_bytes_compressed", new DataTypeUInt64 },
{ "total_size_marks", new DataTypeUInt64 },
{ "bytes_read_uncompressed", new DataTypeUInt64 },
{ "rows_read", new DataTypeUInt64 },
{ "bytes_written_uncompressed", new DataTypeUInt64 },
{ "rows_written", new DataTypeUInt64 }
}
{
}
StoragePtr StorageSystemMerges::create(const std::string & name)
{
return (new StorageSystemMerges{name})->thisPtr();
}
BlockInputStreams StorageSystemMerges::read(
const Names & column_names,
ASTPtr query,
const Context & context,
const Settings & settings,
QueryProcessingStage::Enum & processed_stage,
const size_t max_block_size,
const unsigned)
{
check(column_names);
processed_stage = QueryProcessingStage::FetchColumns;
ColumnWithTypeAndName col_database{new ColumnString, new DataTypeString, "database"};
ColumnWithTypeAndName col_table{new ColumnString, new DataTypeString, "table"};
ColumnWithTypeAndName col_elapsed{new ColumnFloat64, new DataTypeFloat64, "elapsed"};
ColumnWithTypeAndName col_progress{new ColumnFloat64, new DataTypeFloat64, "progress"};
ColumnWithTypeAndName col_num_parts{new ColumnUInt64, new DataTypeUInt64, "num_parts"};
ColumnWithTypeAndName col_result_part_name{new ColumnString, new DataTypeString, "result_part_name"};
ColumnWithTypeAndName col_total_size_bytes_compressed{new ColumnUInt64, new DataTypeUInt64, "total_size_bytes_compressed"};
ColumnWithTypeAndName col_total_size_marks{new ColumnUInt64, new DataTypeUInt64, "total_size_marks"};
ColumnWithTypeAndName col_bytes_read_uncompressed{new ColumnUInt64, new DataTypeUInt64, "bytes_read_uncompressed"};
ColumnWithTypeAndName col_rows_read{new ColumnUInt64, new DataTypeUInt64, "rows_read"};
ColumnWithTypeAndName col_bytes_written_uncompressed{new ColumnUInt64, new DataTypeUInt64, "bytes_written_uncompressed"};
ColumnWithTypeAndName col_rows_written{new ColumnUInt64, new DataTypeUInt64, "rows_written"};
for (const auto & merge : context.getMergeList().get())
{
col_database.column->insert(merge.database);
col_table.column->insert(merge.table);
col_elapsed.column->insert(merge.watch.elapsedSeconds());
col_progress.column->insert(merge.progress);
col_num_parts.column->insert(merge.num_parts);
col_result_part_name.column->insert(merge.result_part_name);
col_total_size_bytes_compressed.column->insert(merge.total_size_bytes_compressed);
col_total_size_marks.column->insert(merge.total_size_marks);
col_bytes_read_uncompressed.column->insert(merge.bytes_read_uncompressed);
col_rows_read.column->insert(merge.rows_read);
col_bytes_written_uncompressed.column->insert(merge.bytes_written_uncompressed);
col_rows_written.column->insert(merge.rows_written);
}
Block block{
col_database,
col_table,
col_elapsed,
col_progress,
col_num_parts,
col_result_part_name,
col_total_size_bytes_compressed,
col_total_size_marks,
col_bytes_read_uncompressed,
col_rows_read,
col_bytes_written_uncompressed,
col_rows_written
};
return BlockInputStreams{1, new OneBlockInputStream{block}};
}
}
|
[
"rodrigosoaresilva@gmail.com"
] |
rodrigosoaresilva@gmail.com
|
75fc128126b2727ade19940fc63af8589163bf40
|
f8de51e1f3bbb061e905320131c5ae16889896cc
|
/chessEngine/src/OldMove.cpp
|
92d7e1dba732da8edc4789c5834e448027c9c8d5
|
[] |
no_license
|
guyKN/Chess2
|
dad62064428cdcd63dae9f076bda8921f14967a6
|
327725c7fe770215dc72ce8de1e4084179643bc4
|
refs/heads/main
| 2023-08-22T12:57:11.022884
| 2021-09-19T17:53:36
| 2021-09-19T17:53:36
| 326,276,822
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,051
|
cpp
|
//
// Created by guykn on 12/9/2020.
//
#include "OldMove.h"
#include <iostream>
#include <string>
#include <Bitboards.h>
namespace Chess {
OldMove OldMove::invalidMove(SQ_INVALID, SQ_INVALID, PIECE_INVALID, PIECE_INVALID);
std::ostream& OldMove::longNotation(std::ostream &outputStream) const {
if (!isOk()) {
outputStream << "ILLEGAL";
} else {
if (castlingType != CASTLE_NONE) {
outputStream << (isKingSide(castlingType) ? "o-o " : "o-o-o");
} else if (pieceTypeOf(srcPiece) != PIECE_TYPE_PAWN) {
outputStream << toChar(pieceTypeOf(srcPiece))
<< toString(srcSquare)
<< ((dstPiece == PIECE_NONE) ? '-' : 'x')
<< toString(dstSquare);
} else {
outputStream << Chess::toString(srcSquare)
<< ((dstPiece == PIECE_NONE) ? '-' : 'x')
<< toString(dstSquare)
<< ' ';
}
}
return outputStream;
}
bool OldMove::isOk() const {
return square_ok(srcSquare) &&
square_ok(dstSquare) &&
srcSquare != dstSquare &&
srcPiece != PIECE_NONE && pieceOk(srcPiece) &&
pieceOk(dstPiece) &&
(dstPiece == PIECE_NONE || ~playerOf(dstPiece) == playerOf(srcPiece)) &&
(pieceOk(promotionPiece)) &&
playerOf(promotionPiece) == playerOf(srcPiece) &&
(promotionPiece == srcPiece || isValidPromotion(pieceTypeOf(promotionPiece)));
}
bool OldMove::operator==(const OldMove &other) const {
return this->srcPiece == other.srcPiece &&
this->dstPiece == other.dstPiece &&
this->srcSquare == other.srcSquare &&
this->dstSquare == other.dstSquare &&
this->promotionPiece == other.promotionPiece &&
this->castlingType == other.castlingType;
}
bool OldMove::matchesMoveInput(MoveInputData moveInputData) const {
return moveInputData.src == srcSquare &&
moveInputData.dst == dstSquare;
}
OldMove::OldMove(const CastlingData &castlingData) :
srcSquare(castlingData.kingSrc),
dstSquare(castlingData.kingDst),
srcPiece(makePiece(PIECE_TYPE_KING, playerOf(castlingData.castlingType))),
dstPiece(PIECE_NONE),
promotionPiece(srcPiece),
pawnForward2Square(SQ_INVALID),
castlingType(castlingData.castlingType),
isEnPassant(false){}
const OldMove OldMove::castleMoves[NUM_CASTLE_TYPES] = {
OldMove(CastlingData::fromCastlingType(CASTLE_WHITE_KING_SIDE)),
OldMove(CastlingData::fromCastlingType(CASTLE_WHITE_QUEEN_SIDE)),
OldMove(CastlingData::fromCastlingType(CASTLE_BLACK_KING_SIDE)),
OldMove(CastlingData::fromCastlingType(CASTLE_BLACK_QUEEN_SIDE))
};
}
|
[
"guyknaan@gmail.com"
] |
guyknaan@gmail.com
|
4869846f55b13d0929085a30c6365e74d51e5782
|
002b4d417e72855adb94c91955ba5c2b2f3fecc0
|
/00654_1_MBT.cpp
|
aff94ae02d6be3f4380897eb7be2f8943cc7b927
|
[] |
no_license
|
Zerorlis/leetcode
|
9ffd3f439b5b43845439e6af5f35dc03fe0eb643
|
2de1680b2504f2c17d8c8aa0eac15b9177a1406e
|
refs/heads/master
| 2021-08-06T06:13:05.426331
| 2020-05-19T12:59:28
| 2020-05-19T12:59:28
| 177,396,417
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 687
|
cpp
|
#include <algorithm>
#include <vector>
#include "tree.h"
using namespace std;
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return constructSonBinaryTree(nums.begin(), nums.end());
}
TreeNode* constructSonBinaryTree(const vector<int>::iterator& left,
const vector<int>::iterator& right) {
if (left == right) return NULL;
// find root
auto root_p = max_element(left, right);
auto root = new TreeNode(*root_p);
root->left = constructSonBinaryTree(left, root_p);
root->right = constructSonBinaryTree(++root_p, right);
return root;
}
};
|
[
"zerorlis@163.com"
] |
zerorlis@163.com
|
eccb886f4081c6806faeda4991d8ff92830bce3b
|
c16872de1c97f749987df5526f73285cc51f0044
|
/OuSns/pugixml.hpp
|
922743fdf473b1695390cf41b7011f5fc708e067
|
[] |
no_license
|
baobo5625/ousnsClient
|
65f685366a2d47ec79abc87d2eeceef0f58fbdf0
|
f998f1a314e43d51a7b460546811b41f788acc46
|
refs/heads/master
| 2021-01-20T21:23:21.209220
| 2014-12-15T07:46:40
| 2014-12-15T07:46:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 41,211
|
hpp
|
/**
* pugixml parser - version 1.0
* --------------------------------------------------------
* Copyright (C) 2006-2010, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
* Report bugs and download new versions at http://pugixml.org/
*
* This library is distributed under the MIT License. See notice at the end
* of this file.
*
* This work is based on the pugxml parser, which is:
* Copyright (C) 2003, by Kristen Wegner (kristen@tima.net)
*/
#include"stdafx.h"
//#ifndef HEADER_PUGIXML_HPP
//#define HEADER_PUGIXML_HPP
#include "pugiconfig.hpp"
#ifndef PUGIXML_NO_STL
namespace std
{
struct bidirectional_iterator_tag;
#ifdef __SUNPRO_CC
// Sun C++ compiler has a bug which forces template argument names in forward declarations to be the same as in actual definitions
template <class _T> class allocator;
template <class _charT> struct char_traits;
template <class _charT, class _Traits> class basic_istream;
template <class _charT, class _Traits> class basic_ostream;
template <class _charT, class _Traits, class _Allocator> class basic_string;
#else
// Borland C++ compiler has a bug which forces template argument names in forward declarations to be the same as in actual definitions
template <class _Ty> class allocator;
template <class _Ty> struct char_traits;
template <class _Elem, class _Traits> class basic_istream;
template <class _Elem, class _Traits> class basic_ostream;
template <class _Elem, class _Traits, class _Ax> class basic_string;
#endif
// Digital Mars compiler has a bug which requires a forward declaration for explicit instantiation (otherwise type selection is messed up later, producing link errors)
// Also note that we have to declare char_traits as a class here, since it's defined that way
#ifdef __DMC__
template <> class char_traits<char>;
#endif
}
#endif
// Macro for deprecated features
#ifndef PUGIXML_DEPRECATED
# if defined(__GNUC__)
# define PUGIXML_DEPRECATED __attribute__((deprecated))
# elif defined(_MSC_VER) && _MSC_VER >= 1300
# define PUGIXML_DEPRECATED __declspec(deprecated)
# else
# define PUGIXML_DEPRECATED
# endif
#endif
// Include exception header for XPath
#if !defined(PUGIXML_NO_XPATH) && !defined(PUGIXML_NO_EXCEPTIONS)
# include <exception>
#endif
// If no API is defined, assume default
#ifndef PUGIXML_API
# define PUGIXML_API
#endif
// If no API for classes is defined, assume default
#ifndef PUGIXML_CLASS
# define PUGIXML_CLASS PUGIXML_API
#endif
// If no API for functions is defined, assume default
#ifndef PUGIXML_FUNCTION
# define PUGIXML_FUNCTION PUGIXML_API
#endif
#include <stddef.h>
// Character interface macros
#ifdef PUGIXML_WCHAR_MODE
# define PUGIXML_TEXT(t) L ## t
# define PUGIXML_CHAR wchar_t
#else
# define PUGIXML_TEXT(t) t
# define PUGIXML_CHAR char
#endif
namespace pugi
{
// Character type used for all internal storage and operations; depends on PUGIXML_WCHAR_MODE
typedef PUGIXML_CHAR char_t;
#ifndef PUGIXML_NO_STL
// String type used for operations that work with STL string; depends on PUGIXML_WCHAR_MODE
typedef std::basic_string<PUGIXML_CHAR, std::char_traits<PUGIXML_CHAR>, std::allocator<PUGIXML_CHAR> > string_t;
#endif
}
// The PugiXML namespace
namespace pugi
{
// Tree node types
enum xml_node_type
{
node_null, // Empty (null) node handle
node_document, // A document tree's absolute root
node_element, // Element tag, i.e. '<node/>'
node_pcdata, // Plain character data, i.e. 'text'
node_cdata, // Character data, i.e. '<![CDATA[text]]>'
node_comment, // Comment tag, i.e. '<!-- text -->'
node_pi, // Processing instruction, i.e. '<?name?>'
node_declaration, // Document declaration, i.e. '<?xml version="1.0"?>'
node_doctype // Document type declaration, i.e. '<!DOCTYPE doc>'
};
// Parsing options
// Minimal parsing mode (equivalent to turning all other flags off).
// Only elements and PCDATA sections are added to the DOM tree, no text conversions are performed.
const unsigned int parse_minimal = 0x0000;
// This flag determines if processing instructions (node_pi) are added to the DOM tree. This flag is off by default.
const unsigned int parse_pi = 0x0001;
// This flag determines if comments (node_comment) are added to the DOM tree. This flag is off by default.
const unsigned int parse_comments = 0x0002;
// This flag determines if CDATA sections (node_cdata) are added to the DOM tree. This flag is on by default.
const unsigned int parse_cdata = 0x0004;
// This flag determines if plain character data (node_pcdata) that consist only of whitespace are added to the DOM tree.
// This flag is off by default; turning it on usually results in slower parsing and more memory consumption.
const unsigned int parse_ws_pcdata = 0x0008;
// This flag determines if character and entity references are expanded during parsing. This flag is on by default.
const unsigned int parse_escapes = 0x0010;
// This flag determines if EOL characters are normalized (converted to #xA) during parsing. This flag is on by default.
const unsigned int parse_eol = 0x0020;
// This flag determines if attribute values are normalized using CDATA normalization rules during parsing. This flag is on by default.
const unsigned int parse_wconv_attribute = 0x0040;
// This flag determines if attribute values are normalized using NMTOKENS normalization rules during parsing. This flag is off by default.
const unsigned int parse_wnorm_attribute = 0x0080;
// This flag determines if document declaration (node_declaration) is added to the DOM tree. This flag is off by default.
const unsigned int parse_declaration = 0x0100;
// This flag determines if document type declaration (node_doctype) is added to the DOM tree. This flag is off by default.
const unsigned int parse_doctype = 0x0200;
// The default parsing mode.
// Elements, PCDATA and CDATA sections are added to the DOM tree, character/reference entities are expanded,
// End-of-Line characters are normalized, attribute values are normalized using CDATA normalization rules.
const unsigned int parse_default = parse_cdata | parse_escapes | parse_wconv_attribute | parse_eol;
// The full parsing mode.
// Nodes of all types are added to the DOM tree, character/reference entities are expanded,
// End-of-Line characters are normalized, attribute values are normalized using CDATA normalization rules.
const unsigned int parse_full = parse_default | parse_pi | parse_comments | parse_declaration | parse_doctype;
// These flags determine the encoding of input data for XML document
enum xml_encoding
{
encoding_auto, // Auto-detect input encoding using BOM or < / <? detection; use UTF8 if BOM is not found
encoding_utf8, // UTF8 encoding
encoding_utf16_le, // Little-endian UTF16
encoding_utf16_be, // Big-endian UTF16
encoding_utf16, // UTF16 with native endianness
encoding_utf32_le, // Little-endian UTF32
encoding_utf32_be, // Big-endian UTF32
encoding_utf32, // UTF32 with native endianness
encoding_wchar // The same encoding wchar_t has (either UTF16 or UTF32)
};
// Formatting flags
// Indent the nodes that are written to output stream with as many indentation strings as deep the node is in DOM tree. This flag is on by default.
const unsigned int format_indent = 0x01;
// Write encoding-specific BOM to the output stream. This flag is off by default.
const unsigned int format_write_bom = 0x02;
// Use raw output mode (no indentation and no line breaks are written). This flag is off by default.
const unsigned int format_raw = 0x04;
// Omit default XML declaration even if there is no declaration in the document. This flag is off by default.
const unsigned int format_no_declaration = 0x08;
// The default set of formatting flags.
// Nodes are indented depending on their depth in DOM tree, a default declaration is output if document has none.
const unsigned int format_default = format_indent;
// Forward declarations
struct xml_attribute_struct;
struct xml_node_struct;
class xml_node_iterator;
class xml_attribute_iterator;
class xml_tree_walker;
class xml_node;
#ifndef PUGIXML_NO_XPATH
class xpath_node;
class xpath_node_set;
class xpath_query;
class xpath_variable_set;
#endif
// Writer interface for node printing (see xml_node::print)
class PUGIXML_CLASS xml_writer
{
public:
virtual ~xml_writer() {}
// Write memory chunk into stream/file/whatever
virtual void write(const void* data, size_t size) = 0;
};
// xml_writer implementation for FILE*
class PUGIXML_CLASS xml_writer_file: public xml_writer
{
public:
// Construct writer from a FILE* object; void* is used to avoid header dependencies on stdio
xml_writer_file(void* file);
virtual void write(const void* data, size_t size);
private:
void* file;
};
struct xml_string_writer: pugi::xml_writer
{
std::string result;
virtual void write(const void* data, size_t size)
{
result += std::string(static_cast<const char*>(data), size);
}
};
#ifndef PUGIXML_NO_STL
// xml_writer implementation for streams
class PUGIXML_CLASS xml_writer_stream: public xml_writer
{
public:
// Construct writer from an output stream object
xml_writer_stream(std::basic_ostream<char, std::char_traits<char> >& stream);
xml_writer_stream(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream);
virtual void write(const void* data, size_t size);
private:
std::basic_ostream<char, std::char_traits<char> >* narrow_stream;
std::basic_ostream<wchar_t, std::char_traits<wchar_t> >* wide_stream;
};
#endif
// A light-weight handle for manipulating attributes in DOM tree
class PUGIXML_CLASS xml_attribute
{
friend class xml_attribute_iterator;
friend class xml_node;
private:
xml_attribute_struct* _attr;
typedef xml_attribute_struct* xml_attribute::*unspecified_bool_type;
public:
// Default constructor. Constructs an empty attribute.
xml_attribute();
// Constructs attribute from internal pointer
explicit xml_attribute(xml_attribute_struct* attr);
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
// Comparison operators (compares wrapped attribute pointers)
bool operator==(const xml_attribute& r) const;
bool operator!=(const xml_attribute& r) const;
bool operator<(const xml_attribute& r) const;
bool operator>(const xml_attribute& r) const;
bool operator<=(const xml_attribute& r) const;
bool operator>=(const xml_attribute& r) const;
// Check if attribute is empty
bool empty() const;
// Get attribute name/value, or "" if attribute is empty
const char_t* name() const;
const char_t* value() const;
// Get attribute value as a number, or 0 if conversion did not succeed or attribute is empty
int as_int() const;
unsigned int as_uint() const;
double as_double() const;
float as_float() const;
// Get attribute value as bool (returns true if first character is in '1tTyY' set), or false if attribute is empty
bool as_bool() const;
// Set attribute name/value (returns false if attribute is empty or there is not enough memory)
bool set_name(const char_t* rhs);
bool set_value(const char_t* rhs);
// Set attribute value with type conversion (numbers are converted to strings, boolean is converted to "true"/"false")
bool set_value(int rhs);
bool set_value(unsigned int rhs);
bool set_value(double rhs);
bool set_value(bool rhs);
// Set attribute value (equivalent to set_value without error checking)
xml_attribute& operator=(const char_t* rhs);
xml_attribute& operator=(int rhs);
xml_attribute& operator=(unsigned int rhs);
xml_attribute& operator=(double rhs);
xml_attribute& operator=(bool rhs);
// Get next/previous attribute in the attribute list of the parent node
xml_attribute next_attribute() const;
xml_attribute previous_attribute() const;
// Get hash value (unique for handles to the same object)
size_t hash_value() const;
// Get internal pointer
xml_attribute_struct* internal_object() const;
};
#ifdef __BORLANDC__
// Borland C++ workaround
bool PUGIXML_FUNCTION operator&&(const xml_attribute& lhs, bool rhs);
bool PUGIXML_FUNCTION operator||(const xml_attribute& lhs, bool rhs);
#endif
// A light-weight handle for manipulating nodes in DOM tree
class PUGIXML_CLASS xml_node
{
friend class xml_attribute_iterator;
friend class xml_node_iterator;
protected:
xml_node_struct* _root;
typedef xml_node_struct* xml_node::*unspecified_bool_type;
public:
// Default constructor. Constructs an empty node.
xml_node();
// Constructs node from internal pointer
explicit xml_node(xml_node_struct* p);
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
// Comparison operators (compares wrapped node pointers)
bool operator==(const xml_node& r) const;
bool operator!=(const xml_node& r) const;
bool operator<(const xml_node& r) const;
bool operator>(const xml_node& r) const;
bool operator<=(const xml_node& r) const;
bool operator>=(const xml_node& r) const;
// Check if node is empty.
bool empty() const;
// Get node type
xml_node_type type() const;
// Get node name/value, or "" if node is empty or it has no name/value
const char_t* name() const;
const char_t* value() const;
// Get attribute list
xml_attribute first_attribute() const;
xml_attribute last_attribute() const;
// Get children list
xml_node first_child() const;
xml_node last_child() const;
// Get next/previous sibling in the children list of the parent node
xml_node next_sibling() const;
xml_node previous_sibling() const;
// Get parent node
xml_node parent() const;
// Get root of DOM tree this node belongs to
xml_node root() const;
// Get child, attribute or next/previous sibling with the specified name
xml_node child(const char_t* name) const;
xml_attribute attribute(const char_t* name) const;
xml_node next_sibling(const char_t* name) const;
xml_node previous_sibling(const char_t* name) const;
// Get child value of current node; that is, value of the first child node of type PCDATA/CDATA
const char_t* child_value() const;
// Get child value of child with specified name. Equivalent to child(name).child_value().
const char_t* child_value(const char_t* name) const;
// Set node name/value (returns false if node is empty, there is not enough memory, or node can not have name/value)
bool set_name(const char_t* rhs);
bool set_value(const char_t* rhs);
// Add attribute with specified name. Returns added attribute, or empty attribute on errors.
xml_attribute append_attribute(const char_t* name);
xml_attribute prepend_attribute(const char_t* name);
xml_attribute insert_attribute_after(const char_t* name, const xml_attribute& attr);
xml_attribute insert_attribute_before(const char_t* name, const xml_attribute& attr);
// Add a copy of the specified attribute. Returns added attribute, or empty attribute on errors.
xml_attribute append_copy(const xml_attribute& proto);
xml_attribute prepend_copy(const xml_attribute& proto);
xml_attribute insert_copy_after(const xml_attribute& proto, const xml_attribute& attr);
xml_attribute insert_copy_before(const xml_attribute& proto, const xml_attribute& attr);
// Add child node with specified type. Returns added node, or empty node on errors.
xml_node append_child(xml_node_type type = node_element);
xml_node prepend_child(xml_node_type type = node_element);
xml_node insert_child_after(xml_node_type type, const xml_node& node);
xml_node insert_child_before(xml_node_type type, const xml_node& node);
// Add child element with specified name. Returns added node, or empty node on errors.
xml_node append_child(const char_t* name);
xml_node prepend_child(const char_t* name);
xml_node insert_child_after(const char_t* name, const xml_node& node);
xml_node insert_child_before(const char_t* name, const xml_node& node);
// Add a copy of the specified node as a child. Returns added node, or empty node on errors.
xml_node append_copy(const xml_node& proto);
xml_node prepend_copy(const xml_node& proto);
xml_node insert_copy_after(const xml_node& proto, const xml_node& node);
xml_node insert_copy_before(const xml_node& proto, const xml_node& node);
// Remove specified attribute
bool remove_attribute(const xml_attribute& a);
bool remove_attribute(const char_t* name);
// Remove specified child
bool remove_child(const xml_node& n);
bool remove_child(const char_t* name);
// Find attribute using predicate. Returns first attribute for which predicate returned true.
template <typename Predicate> xml_attribute find_attribute(Predicate pred) const
{
if (!_root) return xml_attribute();
for (xml_attribute attrib = first_attribute(); attrib; attrib = attrib.next_attribute())
if (pred(attrib))
return attrib;
return xml_attribute();
}
// Find child node using predicate. Returns first child for which predicate returned true.
template <typename Predicate> xml_node find_child(Predicate pred) const
{
if (!_root) return xml_node();
for (xml_node node = first_child(); node; node = node.next_sibling())
if (pred(node))
return node;
return xml_node();
}
// Find node from subtree using predicate. Returns first node from subtree (depth-first), for which predicate returned true.
template <typename Predicate> xml_node find_node(Predicate pred) const
{
if (!_root) return xml_node();
xml_node cur = first_child();
while (cur._root && cur._root != _root)
{
if (pred(cur)) return cur;
if (cur.first_child()) cur = cur.first_child();
else if (cur.next_sibling()) cur = cur.next_sibling();
else
{
while (!cur.next_sibling() && cur._root != _root) cur = cur.parent();
if (cur._root != _root) cur = cur.next_sibling();
}
}
return xml_node();
}
// Find child node by attribute name/value
xml_node find_child_by_attribute(const char_t* name, const char_t* attr_name, const char_t* attr_value) const;
xml_node find_child_by_attribute(const char_t* attr_name, const char_t* attr_value) const;
#ifndef PUGIXML_NO_STL
// Get the absolute node path from root as a text string.
string_t path(char_t delimiter = '/') const;
#endif
// Search for a node by path consisting of node names and . or .. elements.
xml_node first_element_by_path(const char_t* path, char_t delimiter = '/') const;
// Recursively traverse subtree with xml_tree_walker
bool traverse(xml_tree_walker& walker);
#ifndef PUGIXML_NO_XPATH
// Select single node by evaluating XPath query. Returns first node from the resulting node set.
xpath_node select_single_node(const char_t* query, xpath_variable_set* variables = 0) const;
xpath_node select_single_node(const xpath_query& query) const;
// Select node set by evaluating XPath query
xpath_node_set select_nodes(const char_t* query, xpath_variable_set* variables = 0) const;
xpath_node_set select_nodes(const xpath_query& query) const;
#endif
// Print subtree using a writer object
void print(xml_writer& writer, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto, unsigned int depth = 0) const;
#ifndef PUGIXML_NO_STL
// Print subtree to stream
void print(std::basic_ostream<char, std::char_traits<char> >& os, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto, unsigned int depth = 0) const;
void print(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& os, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, unsigned int depth = 0) const;
#endif
// Child nodes iterators
typedef xml_node_iterator iterator;
iterator begin() const;
iterator end() const;
// Attribute iterators
typedef xml_attribute_iterator attribute_iterator;
attribute_iterator attributes_begin() const;
attribute_iterator attributes_end() const;
// Get node offset in parsed file/string (in char_t units) for debugging purposes
ptrdiff_t offset_debug() const;
// Get hash value (unique for handles to the same object)
size_t hash_value() const;
// Get internal pointer
xml_node_struct* internal_object() const;
};
#ifdef __BORLANDC__
// Borland C++ workaround
bool PUGIXML_FUNCTION operator&&(const xml_node& lhs, bool rhs);
bool PUGIXML_FUNCTION operator||(const xml_node& lhs, bool rhs);
#endif
// Child node iterator (a bidirectional iterator over a collection of xml_node)
class PUGIXML_CLASS xml_node_iterator
{
friend class xml_node;
private:
xml_node _wrap;
xml_node _parent;
xml_node_iterator(xml_node_struct* ref, xml_node_struct* parent);
public:
// Iterator traits
typedef ptrdiff_t difference_type;
typedef xml_node value_type;
typedef xml_node* pointer;
typedef xml_node& reference;
#ifndef PUGIXML_NO_STL
typedef std::bidirectional_iterator_tag iterator_category;
#endif
// Default constructor
xml_node_iterator();
// Construct an iterator which points to the specified node
xml_node_iterator(const xml_node& node);
// Iterator operators
bool operator==(const xml_node_iterator& rhs) const;
bool operator!=(const xml_node_iterator& rhs) const;
xml_node& operator*();
xml_node* operator->();
const xml_node_iterator& operator++();
xml_node_iterator operator++(int);
const xml_node_iterator& operator--();
xml_node_iterator operator--(int);
};
// Attribute iterator (a bidirectional iterator over a collection of xml_attribute)
class PUGIXML_CLASS xml_attribute_iterator
{
friend class xml_node;
private:
xml_attribute _wrap;
xml_node _parent;
xml_attribute_iterator(xml_attribute_struct* ref, xml_node_struct* parent);
public:
// Iterator traits
typedef ptrdiff_t difference_type;
typedef xml_attribute value_type;
typedef xml_attribute* pointer;
typedef xml_attribute& reference;
#ifndef PUGIXML_NO_STL
typedef std::bidirectional_iterator_tag iterator_category;
#endif
// Default constructor
xml_attribute_iterator();
// Construct an iterator which points to the specified attribute
xml_attribute_iterator(const xml_attribute& attr, const xml_node& parent);
// Iterator operators
bool operator==(const xml_attribute_iterator& rhs) const;
bool operator!=(const xml_attribute_iterator& rhs) const;
xml_attribute& operator*();
xml_attribute* operator->();
const xml_attribute_iterator& operator++();
xml_attribute_iterator operator++(int);
const xml_attribute_iterator& operator--();
xml_attribute_iterator operator--(int);
};
// Abstract tree walker class (see xml_node::traverse)
class PUGIXML_CLASS xml_tree_walker
{
friend class xml_node;
private:
int _depth;
protected:
// Get current traversal depth
int depth() const;
public:
xml_tree_walker();
virtual ~xml_tree_walker();
// Callback that is called when traversal begins
virtual bool begin(xml_node& node);
// Callback that is called for each node traversed
virtual bool for_each(xml_node& node) = 0;
// Callback that is called when traversal ends
virtual bool end(xml_node& node);
};
// Parsing status, returned as part of xml_parse_result object
enum xml_parse_status
{
status_ok = 0, // No error
status_file_not_found, // File was not found during load_file()
status_io_error, // Error reading from file/stream
status_out_of_memory, // Could not allocate memory
status_internal_error, // Internal error occurred
status_unrecognized_tag, // Parser could not determine tag type
status_bad_pi, // Parsing error occurred while parsing document declaration/processing instruction
status_bad_comment, // Parsing error occurred while parsing comment
status_bad_cdata, // Parsing error occurred while parsing CDATA section
status_bad_doctype, // Parsing error occurred while parsing document type declaration
status_bad_pcdata, // Parsing error occurred while parsing PCDATA section
status_bad_start_element, // Parsing error occurred while parsing start element tag
status_bad_attribute, // Parsing error occurred while parsing element attribute
status_bad_end_element, // Parsing error occurred while parsing end element tag
status_end_element_mismatch // There was a mismatch of start-end tags (closing tag had incorrect name, some tag was not closed or there was an excessive closing tag)
};
// Parsing result
struct PUGIXML_CLASS xml_parse_result
{
// Parsing status (see xml_parse_status)
xml_parse_status status;
// Last parsed offset (in char_t units from start of input data)
ptrdiff_t offset;
// Source document encoding
xml_encoding encoding;
// Default constructor, initializes object to failed state
xml_parse_result();
// Cast to bool operator
operator bool() const;
// Get error description
const char* description() const;
};
// Document class (DOM tree root)
class PUGIXML_CLASS xml_document: public xml_node
{
private:
char_t* _buffer;
char _memory[192];
// Non-copyable semantics
xml_document(const xml_document&);
const xml_document& operator=(const xml_document&);
void create();
void destroy();
xml_parse_result load_buffer_impl(void* contents, size_t size, unsigned int options, xml_encoding encoding, bool is_mutable, bool own);
public:
// Default constructor, makes empty document
xml_document();
// Destructor, invalidates all node/attribute handles to this document
~xml_document();
// Removes all nodes, leaving the empty document
void reset();
// Removes all nodes, then copies the entire contents of the specified document
void reset(const xml_document& proto);
#ifndef PUGIXML_NO_STL
// Load document from stream.
xml_parse_result load(std::basic_istream<char, std::char_traits<char> >& stream, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
xml_parse_result load(std::basic_istream<wchar_t, std::char_traits<wchar_t> >& stream, unsigned int options = parse_default);
#endif
// Load document from zero-terminated string. No encoding conversions are applied.
xml_parse_result load(const char_t* contents, unsigned int options = parse_default);
// Load document from file
xml_parse_result load_file(const char* path, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
xml_parse_result load_file(const wchar_t* path, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Load document from buffer. Copies/converts the buffer, so it may be deleted or changed after the function returns.
xml_parse_result load_buffer(const void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Load document from buffer, using the buffer for in-place parsing (the buffer is modified and used for storage of document data).
// You should ensure that buffer data will persist throughout the document's lifetime, and free the buffer memory manually once document is destroyed.
xml_parse_result load_buffer_inplace(void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Load document from buffer, using the buffer for in-place parsing (the buffer is modified and used for storage of document data).
// You should allocate the buffer with pugixml allocation function; document will free the buffer when it is no longer needed (you can't use it anymore).
xml_parse_result load_buffer_inplace_own(void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Save XML document to writer (semantics is slightly different from xml_node::print, see documentation for details).
void save(xml_writer& writer, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
#ifndef PUGIXML_NO_STL
// Save XML document to stream (semantics is slightly different from xml_node::print, see documentation for details).
void save(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
void save(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default) const;
#endif
// Save XML to file
bool save_file(const char* path, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
bool save_file(const wchar_t* path, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
// Get document element
xml_node document_element() const;
};
#ifndef PUGIXML_NO_XPATH
// XPath query return type
enum xpath_value_type
{
xpath_type_none, // Unknown type (query failed to compile)
xpath_type_node_set, // Node set (xpath_node_set)
xpath_type_number, // Number
xpath_type_string, // String
xpath_type_boolean // Boolean
};
// XPath parsing result
struct PUGIXML_CLASS xpath_parse_result
{
// Error message (0 if no error)
const char* error;
// Last parsed offset (in char_t units from string start)
ptrdiff_t offset;
// Default constructor, initializes object to failed state
xpath_parse_result();
// Cast to bool operator
operator bool() const;
// Get error description
const char* description() const;
};
// A single XPath variable
class PUGIXML_CLASS xpath_variable
{
friend class xpath_variable_set;
protected:
xpath_value_type _type;
xpath_variable* _next;
xpath_variable();
// Non-copyable semantics
xpath_variable(const xpath_variable&);
xpath_variable& operator=(const xpath_variable&);
public:
// Get variable name
const char_t* name() const;
// Get variable type
xpath_value_type type() const;
// Get variable value; no type conversion is performed, default value (false, NaN, empty string, empty node set) is returned on type mismatch error
bool get_boolean() const;
double get_number() const;
const char_t* get_string() const;
const xpath_node_set& get_node_set() const;
// Set variable value; no type conversion is performed, false is returned on type mismatch error
bool set(bool value);
bool set(double value);
bool set(const char_t* value);
bool set(const xpath_node_set& value);
};
// A set of XPath variables
class PUGIXML_CLASS xpath_variable_set
{
private:
xpath_variable* _data[64];
// Non-copyable semantics
xpath_variable_set(const xpath_variable_set&);
xpath_variable_set& operator=(const xpath_variable_set&);
xpath_variable* find(const char_t* name) const;
public:
// Default constructor/destructor
xpath_variable_set();
~xpath_variable_set();
// Add a new variable or get the existing one, if the types match
xpath_variable* add(const char_t* name, xpath_value_type type);
// Set value of an existing variable; no type conversion is performed, false is returned if there is no such variable or if types mismatch
bool set(const char_t* name, bool value);
bool set(const char_t* name, double value);
bool set(const char_t* name, const char_t* value);
bool set(const char_t* name, const xpath_node_set& value);
// Get existing variable by name
xpath_variable* get(const char_t* name);
const xpath_variable* get(const char_t* name) const;
};
// A compiled XPath query object
class PUGIXML_CLASS xpath_query
{
private:
void* _impl;
xpath_parse_result _result;
typedef void* xpath_query::*unspecified_bool_type;
// Non-copyable semantics
xpath_query(const xpath_query&);
xpath_query& operator=(const xpath_query&);
public:
// Construct a compiled object from XPath expression.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on compilation errors.
explicit xpath_query(const char_t* query, xpath_variable_set* variables = 0);
// Destructor
~xpath_query();
// Get query expression return type
xpath_value_type return_type() const;
// Evaluate expression as boolean value in the specified context; performs type conversion if necessary.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
bool evaluate_boolean(const xpath_node& n) const;
// Evaluate expression as double value in the specified context; performs type conversion if necessary.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
double evaluate_number(const xpath_node& n) const;
#ifndef PUGIXML_NO_STL
// Evaluate expression as string value in the specified context; performs type conversion if necessary.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
string_t evaluate_string(const xpath_node& n) const;
#endif
// Evaluate expression as string value in the specified context; performs type conversion if necessary.
// At most capacity characters are written to the destination buffer, full result size is returned (includes terminating zero).
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
// If PUGIXML_NO_EXCEPTIONS is defined, returns empty set instead.
size_t evaluate_string(char_t* buffer, size_t capacity, const xpath_node& n) const;
// Evaluate expression as node set in the specified context.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on type mismatch and std::bad_alloc on out of memory errors.
// If PUGIXML_NO_EXCEPTIONS is defined, returns empty node set instead.
xpath_node_set evaluate_node_set(const xpath_node& n) const;
// Get parsing result (used to get compilation errors in PUGIXML_NO_EXCEPTIONS mode)
const xpath_parse_result& result() const;
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
};
#ifndef PUGIXML_NO_EXCEPTIONS
// XPath exception class
class PUGIXML_CLASS xpath_exception: public std::exception
{
private:
xpath_parse_result _result;
public:
// Construct exception from parse result
explicit xpath_exception(const xpath_parse_result& result);
// Get error message
virtual const char* what() const throw();
// Get parse result
const xpath_parse_result& result() const;
};
#endif
// XPath node class (either xml_node or xml_attribute)
class PUGIXML_CLASS xpath_node
{
private:
xml_node _node;
xml_attribute _attribute;
typedef xml_node xpath_node::*unspecified_bool_type;
public:
// Default constructor; constructs empty XPath node
xpath_node();
// Construct XPath node from XML node/attribute
xpath_node(const xml_node& node);
xpath_node(const xml_attribute& attribute, const xml_node& parent);
// Get node/attribute, if any
xml_node node() const;
xml_attribute attribute() const;
// Get parent of contained node/attribute
xml_node parent() const;
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
// Comparison operators
bool operator==(const xpath_node& n) const;
bool operator!=(const xpath_node& n) const;
};
#ifdef __BORLANDC__
// Borland C++ workaround
bool PUGIXML_FUNCTION operator&&(const xpath_node& lhs, bool rhs);
bool PUGIXML_FUNCTION operator||(const xpath_node& lhs, bool rhs);
#endif
// A fixed-size collection of XPath nodes
class PUGIXML_CLASS xpath_node_set
{
public:
// Collection type
enum type_t
{
type_unsorted, // Not ordered
type_sorted, // Sorted by document order (ascending)
type_sorted_reverse // Sorted by document order (descending)
};
// Constant iterator type
typedef const xpath_node* const_iterator;
// Default constructor. Constructs empty set.
xpath_node_set();
// Constructs a set from iterator range; data is not checked for duplicates and is not sorted according to provided type, so be careful
xpath_node_set(const_iterator begin, const_iterator end, type_t type = type_unsorted);
// Destructor
~xpath_node_set();
// Copy constructor/assignment operator
xpath_node_set(const xpath_node_set& ns);
xpath_node_set& operator=(const xpath_node_set& ns);
// Get collection type
type_t type() const;
// Get collection size
size_t size() const;
// Indexing operator
const xpath_node& operator[](size_t index) const;
// Collection iterators
const_iterator begin() const;
const_iterator end() const;
// Sort the collection in ascending/descending order by document order
void sort(bool reverse = false);
// Get first node in the collection by document order
xpath_node first() const;
// Check if collection is empty
bool empty() const;
private:
type_t _type;
xpath_node _storage;
xpath_node* _begin;
xpath_node* _end;
void _assign(const_iterator begin, const_iterator end);
};
#endif
#ifndef PUGIXML_NO_STL
// Convert wide string to UTF8
std::basic_string<char, std::char_traits<char>, std::allocator<char> > PUGIXML_FUNCTION as_utf8(const wchar_t* str);
std::basic_string<char, std::char_traits<char>, std::allocator<char> > PUGIXML_FUNCTION as_utf8(const std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >& str);
// Convert UTF8 to wide string
std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > PUGIXML_FUNCTION as_wide(const char* str);
std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > PUGIXML_FUNCTION as_wide(const std::basic_string<char, std::char_traits<char>, std::allocator<char> >& str);
#endif
// Memory allocation function interface; returns pointer to allocated memory or NULL on failure
typedef void* (*allocation_function)(size_t size);
// Memory deallocation function interface
typedef void (*deallocation_function)(void* ptr);
// Override default memory management functions. All subsequent allocations/deallocations will be performed via supplied functions.
void PUGIXML_FUNCTION set_memory_management_functions(allocation_function allocate, deallocation_function deallocate);
// Get current memory management functions
allocation_function PUGIXML_FUNCTION get_memory_allocation_function();
deallocation_function PUGIXML_FUNCTION get_memory_deallocation_function();
}
#if !defined(PUGIXML_NO_STL) && (defined(_MSC_VER) || defined(__ICC))
namespace std
{
// Workarounds for (non-standard) iterator category detection for older versions (MSVC7/IC8 and earlier)
std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_node_iterator&);
std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_attribute_iterator&);
}
#endif
#if !defined(PUGIXML_NO_STL) && defined(__SUNPRO_CC)
namespace std
{
// Workarounds for (non-standard) iterator category detection
std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_node_iterator&);
std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_attribute_iterator&);
}
#endif
//#endif
/**
* Copyright (c) 2006-2010 Arseny Kapoulkine
*
* 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.
*/
|
[
"baobo5625@gmail.com"
] |
baobo5625@gmail.com
|
edeed468aae36e15118c9de6b47193a46e9719b7
|
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
|
/atcoder/abc251-300/abc264/g.cpp
|
6e54f3be78fc0169b25d90032b11d347ddfcbfd5
|
[] |
no_license
|
kmjp/procon
|
27270f605f3ae5d80fbdb28708318a6557273a57
|
8083028ece4be1460150aa3f0e69bdb57e510b53
|
refs/heads/master
| 2023-09-04T11:01:09.452170
| 2023-09-03T15:25:21
| 2023-09-03T15:25:21
| 30,825,508
| 23
| 2
| null | 2023-08-18T14:02:07
| 2015-02-15T11:25:23
|
C++
|
SHIFT_JIS
|
C++
| false
| false
| 1,870
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define FORR2(x,y,arr) for(auto& [x,y]:arr)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
template<class T> bool chmax(T &a, const T &b) { if(a<b){a=b;return 1;}return 0;}
template<class T> bool chmin(T &a, const T &b) { if(a>b){a=b;return 1;}return 0;}
//-------------------------------------------------------
int N;
ll P1[26];
ll P2[26][26];
ll P3[26][26][26];
ll dp[26][26];
void solve() {
int i,j,k,l,r,x,y; string s;
cin>>N;
FOR(i,N) {
cin>>s>>x;
FORR(c,s) c-='a';
if(s.size()==1) {
P1[s[0]]=x;
}
if(s.size()==2) {
P2[s[0]][s[1]]=x;
}
if(s.size()==3) {
P3[s[0]][s[1]][s[2]]=x;
}
}
ll ma=-1LL<<60;
//1文字
FOR(i,26) ma=max(ma,P1[i]);
//2文字
priority_queue<pair<ll,int>> Q;
FOR(y,26) FOR(x,26) {
ma=max(ma,P2[y][x]+P1[y]+P1[x]);
dp[y][x]=P2[y][x]+P1[y]+P1[x];
Q.push({-dp[y][x],y*26+x});
}
//2文字
FOR(i,26) ma=max(ma,P1[i]);
int loop=1000000;
while(Q.size()) {
loop--;
if(loop==0) {
cout<<"Infinity"<<endl;
return;
}
ll co=-Q.top().first;
int c1=Q.top().second/26;
int c2=Q.top().second%26;
Q.pop();
if(dp[c1][c2]!=co) continue;
ma=max(ma,co);
FOR(i,26) {
ll sc=co+P3[c1][c2][i]+P2[c2][i]+P1[i];
if(sc>dp[c2][i]) {
dp[c2][i]=sc;
Q.push({-sc,c2*26+i});
}
}
}
cout<<ma<<endl;
}
int main(int argc,char** argv){
string s;int i;
if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
cout.tie(0); solve(); return 0;
}
|
[
"kmjp@users.noreply.github.com"
] |
kmjp@users.noreply.github.com
|
9b4ff69f43e74dc301f2ae026f3616da805e3dca
|
25c7df49d390698b49c13c40533bfd870f547d0b
|
/game/.svn/text-base/player_workshop.h.svn-base
|
b640f4d30d0755a4f0d564601ea91ddef25b5222
|
[] |
no_license
|
xubingyue/galaxy
|
603701759b38446ffd9c1c069beb66197c0bca51
|
3ec14b2d531b2a15e0c52aac748b44a5c74033b0
|
refs/heads/master
| 2020-05-22T23:27:20.857629
| 2015-07-11T01:53:49
| 2015-07-11T01:53:49
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,493
|
#pragma once
#include "block.h"
#include <vector>
#include <boost/unordered_map.hpp>
using namespace std;
namespace gg
{
const static string player_workshop_db_name = "gl.player_workshop";
const static string player_workshop_counter_field = "ctr";/*生产计数器*/
const static string player_workshop_qianzhi_counter_field = "qctr";//强制生产次数 (计数器)
const static string player_workshop_last_timestamp = "lt";/*最后一次生产时间戳*/
const static string player_workshop_level_field = "lv";
const static string player_workshop_exp_field = "exp";
const static string player_workshop_total_free_count_field = "fc";
const static string player_workshop_last_auto_sale_timestamp_field = "last";//最后一次自动卖出时间
const static string player_goods_data_field = "d";
const static string player_goods_id_filed = "id";
const static string player_goods_count_field = "ct";//单个物品数量
//--- 只作为 协议返回字段
const static string player_qianzhi_cost_gold = "qzcg";//当前强制生产所需要金币
struct playerGoods
{
playerGoods(){
id = 0;
count = 0;
}
playerGoods(const int goods_type){
memset(this, 0x0, sizeof(playerGoods));
this->id = goods_type;
count = 0;
}
bool operator == (const playerGoods& goods){
return this->id == goods.id && this->count == goods.count;
}
int id;
int count;
};
class TTManager;
class playerWorkShop : public Block
{
friend class TTManager;
public:
playerWorkShop(playerData& own);
virtual bool get();
virtual bool save();
virtual void update();
virtual void autoUpdate();
int getPresentationCount();//获取免费生产次数
void addPresentation(int count);//添加免费生产次数, 函数已 insert save set 与 addPackage
int getGoodsCount();
int getQianzhiCounter();//获取强制生产计数器
void updateYield(bool is_qianzhi);
int getTotalFreeCounter(){ return total_free_counter; }
void addTotalFreeCounter();
int exp;
int level;
void addGoods(const int goods_type);//添加物品
typedef boost::unordered_map< int, playerGoods > goodsMap;
goodsMap goods_map;
void package(Json::Value& pack);
unsigned last_auto_sale_timestamp; //最后一次自动卖出物品时间
unsigned last_timestamp;//最后一次生产时间
private:
int counter;
int qianzhi_counter;
int total_free_counter;
};
}
|
[
"kelvinlyan@localhost.localdomain"
] |
kelvinlyan@localhost.localdomain
|
|
f18a0d72859ea90385deba8371a5b93a5cdd6df5
|
56bd4faa9c00a871139c6e419fff02c8d5207cef
|
/src/muz/spacer/spacer_legacy_mev.cpp
|
0ab33c69326335f2762d0da654fb65f3209bda6c
|
[
"MIT"
] |
permissive
|
SRI-CSL/z3
|
e950f5d32477166bfefe2ab77644b31827d9a354
|
a5ce83b6ad12f44661d24e9ad91f926bfbadfba6
|
refs/heads/master
| 2020-04-12T17:17:50.276968
| 2018-12-20T23:08:33
| 2018-12-20T23:08:33
| 162,640,242
| 1
| 2
|
NOASSERTION
| 2018-12-20T23:02:31
| 2018-12-20T23:02:31
| null |
UTF-8
|
C++
| false
| false
| 24,468
|
cpp
|
/**
Copyright (c) 2017 Arie Gurfinkel
Deprecated implementation of model evaluator. To be removed.
*/
#include <sstream>
#include "arith_simplifier_plugin.h"
#include "array_decl_plugin.h"
#include "ast_pp.h"
#include "basic_simplifier_plugin.h"
#include "bv_simplifier_plugin.h"
#include "bool_rewriter.h"
#include "dl_util.h"
#include "for_each_expr.h"
#include "smt_params.h"
#include "model.h"
#include "ref_vector.h"
#include "rewriter.h"
#include "rewriter_def.h"
#include "util.h"
#include "spacer_manager.h"
#include "spacer_legacy_mev.h"
#include "spacer_util.h"
#include "arith_decl_plugin.h"
#include "expr_replacer.h"
#include "model_smt2_pp.h"
#include "scoped_proof.h"
#include "qe_lite.h"
#include "spacer_qe_project.h"
#include "model_pp.h"
#include "expr_safe_replace.h"
#include "datatype_decl_plugin.h"
#include "bv_decl_plugin.h"
namespace old {
/////////////////////////
// model_evaluator
//
void model_evaluator::assign_value(expr* e, expr* val)
{
rational r;
if (m.is_true(val)) {
set_true(e);
} else if (m.is_false(val)) {
set_false(e);
} else if (m_arith.is_numeral(val, r)) {
set_number(e, r);
} else if (m.is_value(val)) {
set_value(e, val);
} else {
IF_VERBOSE(3, verbose_stream() << "Not evaluated " << mk_pp(e, m) << "\n";);
TRACE("old_spacer", tout << "Variable is not tracked: " << mk_pp(e, m) << "\n";);
set_x(e);
}
}
void model_evaluator::setup_model(const model_ref& model)
{
m_numbers.reset();
m_values.reset();
m_model = model.get();
rational r;
unsigned sz = model->get_num_constants();
for (unsigned i = 0; i < sz; i++) {
func_decl * d = model->get_constant(i);
expr* val = model->get_const_interp(d);
expr* e = m.mk_const(d);
m_refs.push_back(e);
assign_value(e, val);
}
}
void model_evaluator::reset()
{
m1.reset();
m2.reset();
m_values.reset();
m_visited.reset();
m_numbers.reset();
m_refs.reset();
m_model = 0;
}
void model_evaluator::minimize_literals(ptr_vector<expr> const& formulas,
const model_ref& mdl, expr_ref_vector& result)
{
TRACE("old_spacer",
tout << "formulas:\n";
for (unsigned i = 0; i < formulas.size(); ++i) tout << mk_pp(formulas[i], m) << "\n";
);
expr_ref tmp(m);
ptr_vector<expr> tocollect;
setup_model(mdl);
collect(formulas, tocollect);
for (unsigned i = 0; i < tocollect.size(); ++i) {
expr* e = tocollect[i];
expr* e1, *e2;
SASSERT(m.is_bool(e));
SASSERT(is_true(e) || is_false(e));
if (is_true(e)) {
result.push_back(e);
}
// hack to break disequalities for arithmetic variables.
else if (m.is_eq(e, e1, e2) && m_arith.is_int_real(e1)) {
if (get_number(e1) < get_number(e2)) {
result.push_back(m_arith.mk_lt(e1, e2));
} else {
result.push_back(m_arith.mk_lt(e2, e1));
}
} else {
result.push_back(m.mk_not(e));
}
}
reset();
TRACE("old_spacer",
tout << "minimized model:\n";
for (unsigned i = 0; i < result.size(); ++i) tout << mk_pp(result[i].get(), m) << "\n";
);
}
void model_evaluator::process_formula(app* e, ptr_vector<expr>& todo, ptr_vector<expr>& tocollect)
{
SASSERT(m.is_bool(e));
SASSERT(is_true(e) || is_false(e));
unsigned v = is_true(e);
unsigned sz = e->get_num_args();
expr* const* args = e->get_args();
if (e->get_family_id() == m.get_basic_family_id()) {
switch (e->get_decl_kind()) {
case OP_TRUE:
break;
case OP_FALSE:
break;
case OP_EQ:
case OP_IFF:
if (args[0] == args[1]) {
SASSERT(v);
// no-op
} else if (m.is_bool(args[0])) {
todo.append(sz, args);
} else {
tocollect.push_back(e);
}
break;
case OP_DISTINCT:
tocollect.push_back(e);
break;
case OP_ITE:
if (args[1] == args[2]) {
tocollect.push_back(args[1]);
} else if (is_true(args[1]) && is_true(args[2])) {
todo.append(2, args + 1);
} else if (is_false(args[1]) && is_false(args[2])) {
todo.append(2, args + 1);
} else if (is_true(args[0])) {
todo.append(2, args);
} else {
SASSERT(is_false(args[0]));
todo.push_back(args[0]);
todo.push_back(args[2]);
}
break;
case OP_AND:
if (v) {
todo.append(sz, args);
} else {
unsigned i = 0;
for (; !is_false(args[i]) && i < sz; ++i);
if (i == sz) {
fatal_error(1);
}
VERIFY(i < sz);
todo.push_back(args[i]);
}
break;
case OP_OR:
if (v) {
unsigned i = 0;
for (; !is_true(args[i]) && i < sz; ++i);
if (i == sz) {
fatal_error(1);
}
VERIFY(i < sz);
todo.push_back(args[i]);
} else {
todo.append(sz, args);
}
break;
case OP_XOR:
case OP_NOT:
todo.append(sz, args);
break;
case OP_IMPLIES:
if (v) {
if (is_true(args[1])) {
todo.push_back(args[1]);
} else if (is_false(args[0])) {
todo.push_back(args[0]);
} else {
IF_VERBOSE(0, verbose_stream() << "Term not handled " << mk_pp(e, m) << "\n";);
UNREACHABLE();
}
} else {
todo.append(sz, args);
}
break;
default:
IF_VERBOSE(0, verbose_stream() << "Term not handled " << mk_pp(e, m) << "\n";);
UNREACHABLE();
}
} else {
tocollect.push_back(e);
}
}
void model_evaluator::collect(ptr_vector<expr> const& formulas, ptr_vector<expr>& tocollect)
{
ptr_vector<expr> todo;
todo.append(formulas);
m_visited.reset();
VERIFY(check_model(formulas));
while (!todo.empty()) {
app* e = to_app(todo.back());
todo.pop_back();
if (!m_visited.is_marked(e)) {
process_formula(e, todo, tocollect);
m_visited.mark(e, true);
}
}
m_visited.reset();
}
void model_evaluator::eval_arith(app* e)
{
rational r, r2;
#define ARG1 e->get_arg(0)
#define ARG2 e->get_arg(1)
unsigned arity = e->get_num_args();
for (unsigned i = 0; i < arity; ++i) {
expr* arg = e->get_arg(i);
if (is_x(arg)) {
set_x(e);
return;
}
SASSERT(!is_unknown(arg));
}
switch (e->get_decl_kind()) {
case OP_NUM:
VERIFY(m_arith.is_numeral(e, r));
set_number(e, r);
break;
case OP_IRRATIONAL_ALGEBRAIC_NUM:
set_x(e);
break;
case OP_LE:
set_bool(e, get_number(ARG1) <= get_number(ARG2));
break;
case OP_GE:
set_bool(e, get_number(ARG1) >= get_number(ARG2));
break;
case OP_LT:
set_bool(e, get_number(ARG1) < get_number(ARG2));
break;
case OP_GT:
set_bool(e, get_number(ARG1) > get_number(ARG2));
break;
case OP_ADD:
r = rational::zero();
for (unsigned i = 0; i < arity; ++i) {
r += get_number(e->get_arg(i));
}
set_number(e, r);
break;
case OP_SUB:
r = get_number(e->get_arg(0));
for (unsigned i = 1; i < arity; ++i) {
r -= get_number(e->get_arg(i));
}
set_number(e, r);
break;
case OP_UMINUS:
SASSERT(arity == 1);
set_number(e, -get_number(e->get_arg(0)));
break;
case OP_MUL:
r = rational::one();
for (unsigned i = 0; i < arity; ++i) {
r *= get_number(e->get_arg(i));
}
set_number(e, r);
break;
case OP_DIV:
SASSERT(arity == 2);
r = get_number(ARG2);
if (r.is_zero()) {
set_x(e);
} else {
set_number(e, get_number(ARG1) / r);
}
break;
case OP_IDIV:
SASSERT(arity == 2);
r = get_number(ARG2);
if (r.is_zero()) {
set_x(e);
} else {
set_number(e, div(get_number(ARG1), r));
}
break;
case OP_REM:
// rem(v1,v2) = if v2 >= 0 then mod(v1,v2) else -mod(v1,v2)
SASSERT(arity == 2);
r = get_number(ARG2);
if (r.is_zero()) {
set_x(e);
} else {
r2 = mod(get_number(ARG1), r);
if (r.is_neg()) { r2.neg(); }
set_number(e, r2);
}
break;
case OP_MOD:
SASSERT(arity == 2);
r = get_number(ARG2);
if (r.is_zero()) {
set_x(e);
} else {
set_number(e, mod(get_number(ARG1), r));
}
break;
case OP_TO_REAL:
SASSERT(arity == 1);
set_number(e, get_number(ARG1));
break;
case OP_TO_INT:
SASSERT(arity == 1);
set_number(e, floor(get_number(ARG1)));
break;
case OP_IS_INT:
SASSERT(arity == 1);
set_bool(e, get_number(ARG1).is_int());
break;
case OP_POWER:
set_x(e);
break;
default:
IF_VERBOSE(0, verbose_stream() << "Term not handled " << mk_pp(e, m) << "\n";);
UNREACHABLE();
break;
}
}
void model_evaluator::inherit_value(expr* e, expr* v)
{
expr* w;
SASSERT(!is_unknown(v));
SASSERT(m.get_sort(e) == m.get_sort(v));
if (is_x(v)) {
set_x(e);
} else if (m.is_bool(e)) {
SASSERT(m.is_bool(v));
if (is_true(v)) { set_true(e); }
else if (is_false(v)) { set_false(e); }
else {
TRACE("old_spacer", tout << "not inherited:\n" << mk_pp(e, m) << "\n" << mk_pp(v, m) << "\n";);
set_x(e);
}
} else if (m_arith.is_int_real(e)) {
set_number(e, get_number(v));
} else if (m.is_value(v)) {
set_value(e, v);
} else if (m_values.find(v, w)) {
set_value(e, w);
} else {
TRACE("old_spacer", tout << "not inherited:\n" << mk_pp(e, m) << "\n" << mk_pp(v, m) << "\n";);
set_x(e);
}
}
void model_evaluator::eval_exprs(expr_ref_vector& es)
{
model_ref mr(m_model);
for (unsigned j = 0; j < es.size(); ++j) {
if (m_array.is_as_array(es[j].get())) {
es[j] = eval(mr, es[j].get());
}
}
}
bool model_evaluator::extract_array_func_interp(expr* a, vector<expr_ref_vector>& stores, expr_ref& else_case)
{
SASSERT(m_array.is_array(a));
TRACE("old_spacer", tout << mk_pp(a, m) << "\n";);
while (m_array.is_store(a)) {
expr_ref_vector store(m);
store.append(to_app(a)->get_num_args() - 1, to_app(a)->get_args() + 1);
eval_exprs(store);
stores.push_back(store);
a = to_app(a)->get_arg(0);
}
if (m_array.is_const(a)) {
else_case = to_app(a)->get_arg(0);
return true;
}
while (m_array.is_as_array(a)) {
func_decl* f = m_array.get_as_array_func_decl(to_app(a));
func_interp* g = m_model->get_func_interp(f);
unsigned sz = g->num_entries();
unsigned arity = f->get_arity();
for (unsigned i = 0; i < sz; ++i) {
expr_ref_vector store(m);
func_entry const* fe = g->get_entry(i);
store.append(arity, fe->get_args());
store.push_back(fe->get_result());
for (unsigned j = 0; j < store.size(); ++j) {
if (!is_ground(store[j].get())) {
TRACE("old_spacer", tout << "could not extract array interpretation: " << mk_pp(a, m) << "\n" << mk_pp(store[j].get(), m) << "\n";);
return false;
}
}
eval_exprs(store);
stores.push_back(store);
}
else_case = g->get_else();
if (!else_case) {
TRACE("old_spacer", tout << "no else case " << mk_pp(a, m) << "\n";);
return false;
}
if (!is_ground(else_case)) {
TRACE("old_spacer", tout << "non-ground else case " << mk_pp(a, m) << "\n" << mk_pp(else_case, m) << "\n";);
return false;
}
if (m_array.is_as_array(else_case)) {
model_ref mr(m_model);
else_case = eval(mr, else_case);
}
TRACE("old_spacer", tout << "else case: " << mk_pp(else_case, m) << "\n";);
return true;
}
TRACE("old_spacer", tout << "no translation: " << mk_pp(a, m) << "\n";);
return false;
}
/**
best effort evaluator of extensional array equality.
*/
void model_evaluator::eval_array_eq(app* e, expr* arg1, expr* arg2)
{
TRACE("old_spacer", tout << "array equality: " << mk_pp(e, m) << "\n";);
expr_ref v1(m), v2(m);
m_model->eval(arg1, v1);
m_model->eval(arg2, v2);
if (v1 == v2) {
set_true(e);
return;
}
sort* s = m.get_sort(arg1);
sort* r = get_array_range(s);
// give up evaluating finite domain/range arrays
if (!r->is_infinite() && !r->is_very_big() && !s->is_infinite() && !s->is_very_big()) {
TRACE("old_spacer", tout << "equality is unknown: " << mk_pp(e, m) << "\n";);
set_x(e);
return;
}
vector<expr_ref_vector> store;
expr_ref else1(m), else2(m);
if (!extract_array_func_interp(v1, store, else1) ||
!extract_array_func_interp(v2, store, else2)) {
TRACE("old_spacer", tout << "equality is unknown: " << mk_pp(e, m) << "\n";);
set_x(e);
return;
}
if (else1 != else2) {
if (m.is_value(else1) && m.is_value(else2)) {
TRACE("old_spacer", tout
<< "defaults are different: " << mk_pp(e, m) << " "
<< mk_pp(else1, m) << " " << mk_pp(else2, m) << "\n";);
set_false(e);
} else if (m_array.is_array(else1)) {
eval_array_eq(e, else1, else2);
} else {
TRACE("old_spacer", tout << "equality is unknown: " << mk_pp(e, m) << "\n";);
set_x(e);
}
return;
}
expr_ref s1(m), s2(m), w1(m), w2(m);
expr_ref_vector args1(m), args2(m);
args1.push_back(v1);
args2.push_back(v2);
for (unsigned i = 0; i < store.size(); ++i) {
args1.resize(1);
args2.resize(1);
args1.append(store[i].size() - 1, store[i].c_ptr());
args2.append(store[i].size() - 1, store[i].c_ptr());
s1 = m_array.mk_select(args1.size(), args1.c_ptr());
s2 = m_array.mk_select(args2.size(), args2.c_ptr());
m_model->eval(s1, w1);
m_model->eval(s2, w2);
if (w1 == w2) {
continue;
}
if (m.is_value(w1) && m.is_value(w2)) {
TRACE("old_spacer", tout << "Equality evaluation: " << mk_pp(e, m) << "\n";
tout << mk_pp(s1, m) << " |-> " << mk_pp(w1, m) << "\n";
tout << mk_pp(s2, m) << " |-> " << mk_pp(w2, m) << "\n";);
set_false(e);
} else if (m_array.is_array(w1)) {
eval_array_eq(e, w1, w2);
if (is_true(e)) {
continue;
}
} else {
TRACE("old_spacer", tout << "equality is unknown: " << mk_pp(e, m) << "\n";);
set_x(e);
}
return;
}
set_true(e);
}
void model_evaluator::eval_eq(app* e, expr* arg1, expr* arg2)
{
if (arg1 == arg2) {
set_true(e);
} else if (m_array.is_array(arg1)) {
eval_array_eq(e, arg1, arg2);
} else if (is_x(arg1) || is_x(arg2)) {
set_x(e);
} else if (m.is_bool(arg1)) {
bool val = is_true(arg1) == is_true(arg2);
SASSERT(val == (is_false(arg1) == is_false(arg2)));
if (val) {
set_true(e);
} else {
set_false(e);
}
} else if (m_arith.is_int_real(arg1)) {
set_bool(e, get_number(arg1) == get_number(arg2));
} else {
expr* e1 = get_value(arg1);
expr* e2 = get_value(arg2);
if (m.is_value(e1) && m.is_value(e2)) {
set_bool(e, e1 == e2);
} else if (e1 == e2) {
set_bool(e, true);
} else {
TRACE("old_spacer", tout << "not value equal:\n" << mk_pp(e1, m) << "\n" << mk_pp(e2, m) << "\n";);
set_x(e);
}
}
}
void model_evaluator::eval_basic(app* e)
{
expr* arg1, *arg2;
expr *argCond, *argThen, *argElse, *arg;
bool has_x = false;
unsigned arity = e->get_num_args();
switch (e->get_decl_kind()) {
case OP_AND:
for (unsigned j = 0; j < arity; ++j) {
expr * arg = e->get_arg(j);
if (is_false(arg)) {
set_false(e);
return;
} else if (is_x(arg)) {
has_x = true;
} else {
SASSERT(is_true(arg));
}
}
if (has_x) {
set_x(e);
} else {
set_true(e);
}
break;
case OP_OR:
for (unsigned j = 0; j < arity; ++j) {
expr * arg = e->get_arg(j);
if (is_true(arg)) {
set_true(e);
return;
} else if (is_x(arg)) {
has_x = true;
} else {
SASSERT(is_false(arg));
}
}
if (has_x) {
set_x(e);
} else {
set_false(e);
}
break;
case OP_NOT:
VERIFY(m.is_not(e, arg));
if (is_true(arg)) {
set_false(e);
} else if (is_false(arg)) {
set_true(e);
} else {
SASSERT(is_x(arg));
set_x(e);
}
break;
case OP_IMPLIES:
VERIFY(m.is_implies(e, arg1, arg2));
if (is_false(arg1) || is_true(arg2)) {
set_true(e);
} else if (arg1 == arg2) {
set_true(e);
} else if (is_true(arg1) && is_false(arg2)) {
set_false(e);
} else {
SASSERT(is_x(arg1) || is_x(arg2));
set_x(e);
}
break;
case OP_IFF:
VERIFY(m.is_iff(e, arg1, arg2));
eval_eq(e, arg1, arg2);
break;
case OP_XOR:
VERIFY(m.is_xor(e, arg1, arg2));
eval_eq(e, arg1, arg2);
if (is_false(e)) { set_true(e); }
else if (is_true(e)) { set_false(e); }
break;
case OP_ITE:
VERIFY(m.is_ite(e, argCond, argThen, argElse));
if (is_true(argCond)) {
inherit_value(e, argThen);
} else if (is_false(argCond)) {
inherit_value(e, argElse);
} else if (argThen == argElse) {
inherit_value(e, argThen);
} else if (m.is_bool(e)) {
SASSERT(is_x(argCond));
if (is_x(argThen) || is_x(argElse)) {
set_x(e);
} else if (is_true(argThen) == is_true(argElse)) {
inherit_value(e, argThen);
} else {
set_x(e);
}
} else {
set_x(e);
}
break;
case OP_TRUE:
set_true(e);
break;
case OP_FALSE:
set_false(e);
break;
case OP_EQ:
VERIFY(m.is_eq(e, arg1, arg2));
eval_eq(e, arg1, arg2);
break;
case OP_DISTINCT: {
vector<rational> values;
for (unsigned i = 0; i < arity; ++i) {
expr* arg = e->get_arg(i);
if (is_x(arg)) {
set_x(e);
return;
}
values.push_back(get_number(arg));
}
std::sort(values.begin(), values.end());
for (unsigned i = 0; i + 1 < values.size(); ++i) {
if (values[i] == values[i + 1]) {
set_false(e);
return;
}
}
set_true(e);
break;
}
default:
IF_VERBOSE(0, verbose_stream() << "Term not handled " << mk_pp(e, m) << "\n";);
UNREACHABLE();
}
}
void model_evaluator::eval_fmls(ptr_vector<expr> const& formulas)
{
ptr_vector<expr> todo(formulas);
while (!todo.empty()) {
expr * curr_e = todo.back();
if (!is_app(curr_e)) {
todo.pop_back();
continue;
}
app * curr = to_app(curr_e);
if (!is_unknown(curr)) {
todo.pop_back();
continue;
}
unsigned arity = curr->get_num_args();
for (unsigned i = 0; i < arity; ++i) {
if (is_unknown(curr->get_arg(i))) {
todo.push_back(curr->get_arg(i));
}
}
if (todo.back() != curr) {
continue;
}
todo.pop_back();
if (curr->get_family_id() == m_arith.get_family_id()) {
eval_arith(curr);
} else if (curr->get_family_id() == m.get_basic_family_id()) {
eval_basic(curr);
} else {
expr_ref vl(m);
m_model->eval(curr, vl);
assign_value(curr, vl);
}
IF_VERBOSE(35, verbose_stream() << "assigned " << mk_pp(curr_e, m)
<< (is_true(curr_e) ? "true" : is_false(curr_e) ? "false" : "unknown") << "\n";);
SASSERT(!is_unknown(curr));
}
}
bool model_evaluator::check_model(ptr_vector<expr> const& formulas)
{
eval_fmls(formulas);
bool has_x = false;
for (unsigned i = 0; i < formulas.size(); ++i) {
expr * form = formulas[i];
SASSERT(!is_unknown(form));
TRACE("spacer_verbose",
tout << "formula is " << (is_true(form) ? "true" : is_false(form) ? "false" : "unknown") << "\n" << mk_pp(form, m) << "\n";);
if (is_false(form)) {
IF_VERBOSE(0, verbose_stream() << "formula false in model: " << mk_pp(form, m) << "\n";);
UNREACHABLE();
}
if (is_x(form)) {
IF_VERBOSE(0, verbose_stream() << "formula undetermined in model: " << mk_pp(form, m) << "\n";);
TRACE("old_spacer", model_smt2_pp(tout, m, *m_model, 0););
has_x = true;
}
}
return !has_x;
}
expr_ref model_evaluator::eval_heavy(const model_ref& model, expr* fml)
{
expr_ref result(model->get_manager());
setup_model(model);
ptr_vector<expr> fmls;
fmls.push_back(fml);
eval_fmls(fmls);
if (is_false(fml)) {
result = m.mk_false();
} else if (is_true(fml) || is_x(fml)) {
result = m.mk_true();
} else if (m_arith.is_int_real(fml)) {
result = m_arith.mk_numeral(get_number(fml), m_arith.is_int(fml));
} else {
result = get_value(fml);
}
reset();
return result;
}
expr_ref model_evaluator::eval(const model_ref& model, func_decl* d)
{
SASSERT(d->get_arity() == 0);
expr_ref result(m);
if (m_array.is_array(d->get_range())) {
expr_ref e(m);
e = m.mk_const(d);
result = eval(model, e);
} else {
result = model->get_const_interp(d);
}
return result;
}
expr_ref model_evaluator::eval(const model_ref& model, expr* e)
{
expr_ref result(m);
m_model = model.get();
VERIFY(m_model->eval(e, result, true));
if (m_array.is_array(e)) {
vector<expr_ref_vector> stores;
expr_ref_vector args(m);
expr_ref else_case(m);
if (extract_array_func_interp(result, stores, else_case)) {
result = m_array.mk_const_array(m.get_sort(e), else_case);
while (!stores.empty() && stores.back().back() == else_case) {
stores.pop_back();
}
for (unsigned i = stores.size(); i > 0;) {
--i;
args.resize(1);
args[0] = result;
args.append(stores[i]);
result = m_array.mk_store(args.size(), args.c_ptr());
}
return result;
}
}
return result;
}
}
|
[
"arie.gurfinkel@uwaterloo.ca"
] |
arie.gurfinkel@uwaterloo.ca
|
3065bc5925d62fb7c65cd47eb16d6a9c755e998e
|
26cb02ac39517585f5431bc8e042a58ba826abe9
|
/include/Dict.hh
|
3d050bdf61826b0b967b44b3e042721f987aed1f
|
[] |
no_license
|
jercheng/python_cpp_object_api
|
f4e22770869de15ef7e19267b6a2a33dea9fffaf
|
880438789757aaec429f7d025e3987b4f0ed01d8
|
refs/heads/main
| 2023-06-17T20:39:53.713137
| 2021-07-19T15:15:43
| 2021-07-19T15:15:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,377
|
hh
|
#pragma once
#include "Object.hh"
namespace Py
{
class Dict : public Object
{
public:
using Object::Object;
// construct new dictionary from key value pairs
Dict(std::initializer_list<std::pair<Str, Object>> _dict);
// Return a new dictionary that contains the same key-value pairs as p.
Dict Copy() const;
/**
@brief Iterate over mapping object other adding key-value pairs to this dictionary.
other may be a dictionary, or any object supporting PyMapping_Keys() and PyObject_GetItem().
If override is true, existing pairs in a will be replaced if a matching key is found in b,
otherwise pairs will only be added if there is not a matching key in a.
Return 0 on success or -1 if an exception was raised.
*/
int Merge(Dict other, int _override = 1);
/**
@brief This is the same as _Merge(b, 1) in C, and is similar to a.update(b) in Python except that
Update() doesn’t fall back to the iterating over a sequence of key value pairs if the second
argument has no “keys” attribute. Return 0 on success or -1 if an exception was raised.
*/
int Update(Dict other);
/**
@brief Determine if dictionary p contains key. If an item in p is matches key,
return 1, otherwise return 0. On error, return -1. This is equivalent to
the Python expression key in p.
*/
int Contains(Object key);
/**
@brief Empty an existing dictionary of all key-value pairs.
*/
void Clear();
/**
Return the object from dictionary p which has a key key. Return NULL if the
key key is not present, but without setting an exception.
Note that exceptions which occur while calling __hash__() and __eq__()
methods will get suppressed. To get error reporting use
GetItemWithError() instead.
*/
Object GetItem(Str key) const;
/*
Variant of PyDict_GetItem() that does not suppress exceptions. Return NULL
with an exception set if an exception occurred. Return NULL without an
exception set if the key wasn’t present.
*/
Object GetItemWithError(Str key) const;
/*
Insert val into the dictionary p with a key of key. key must be hashable;
if it isn’t, TypeError will be raised. Return 0 on success or -1 on failure.
This function does not steal a reference to val.
*/
int SetItem(Str key, Object new_value) const;
/*
Remove the entry in dictionary p with key key. key must be hashable;
if it isn’t, TypeError is raised. If key is not in the dictionary,
KeyError is raised. Return 0 on success or -1 on failure.
*/
int DelItem(Str key) const;
/*
Return a List containing all the items from the dictionary.
*/
List Items() const;
/*
Return a List containing all the keys from the dictionary.
*/
List Keys() const;
/*
Return a List containing all the keys from the dictionary.
*/
List Values() const;
};
}
|
[
"argmaster.world@gmail.com"
] |
argmaster.world@gmail.com
|
fcd2046df4764d078b570cd569036c0897e77e07
|
9c7c488f962e0fbdb3be81eb43decf48623d63f9
|
/hw1/Frustum.cpp
|
639ee8f094b712d351bd5dab17fd12d60cba9beb
|
[] |
no_license
|
TylerSongCS/OpenGL
|
c6c0e59a07e75c357581abb206b6cb74e837ff9e
|
822309c46d9e0ce2c451aee60cb73011e80ec40b
|
refs/heads/master
| 2022-03-14T10:32:40.010227
| 2019-12-20T21:28:37
| 2019-12-20T21:28:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,631
|
cpp
|
//
// Frustum.cpp
// hw1
//
// Created by Mingxun Song on 10/29/19.
// Copyright © 2019 Mingxun Song. All rights reserved.
// Credit to Gerlits Anatoliy of https://www.gamedev.net/articles/programming/general-and-gameplay-programming/frustum-culling-r4613/
#include "Frustum.hpp"
#include <iostream>
Frustum::Frustum(){
}
Frustum::Frustum(float fovy, float aspect, float znear, float zfar){
this->fovy = fovy;
this->aspect = aspect;
this->znear = znear;
this->zfar = zfar;
projection = glm::perspective(glm::radians(fovy),aspect, znear, zfar);
}
mat4& Frustum::getProjection(){
return projection;
}
float Frustum::getFOVY(){
return fovy;
}
float Frustum::getAspect(){
return aspect;
}
float Frustum::getZNear(){
return znear;
}
float Frustum::getZFar(){
return zfar;
}
void Frustum::setFOVY(float fovy){
this->fovy = fovy;
}
void Frustum::createPlanes(vec3 eye, vec3 center, vec3 up, Plane* plane){
//cerr << "fov: " << fovy << endl;
float tang = (float) tan(radians(fovy) / 2);
float nearHeight = znear * tang;
float nearWidth = nearHeight * aspect;
float farHeight = zfar * tang;
float farWidth = farHeight * aspect;
vec3 farCenter, nearCenter, X, Y, Z, ynh, xnw, nearTopLeft, nearTopRight, nearBotLeft, nearBotRight, farTopLeft, farTopRight, farBotLeft, farBotRight;
// opposite direction of the looking direction
Z = normalize(eye - center);
//x axis of camera
X = normalize(up * Z);
//the real up vector
Y = cross(Z, X);
//Y = (Z * X);
/*if( Y == (Z * X)){
std::cerr << "true";
}else{
std::cerr << "false";
}*/
ynh = Y * (nearHeight);
xnw = X * (nearWidth);
//center of far and near planes
nearCenter = eye - Z * znear;
farCenter = eye - Z * zfar;
//4 corners of the frustum on near plane
nearTopLeft = nearCenter + Y * nearHeight - X * nearWidth;
nearTopRight = nearCenter + Y * nearHeight + X * nearWidth;
nearBotLeft = nearCenter - Y * nearHeight - X * nearWidth;
nearBotRight = nearCenter - Y * nearHeight + X * nearWidth;
//4 corners of the frustum on far plane
farTopLeft = farCenter + Y * farHeight - X * farWidth;
farTopRight = farCenter + Y * farHeight + X * farWidth;
farBotLeft = farCenter - Y * farHeight - X * farWidth;
farBotRight = farCenter - Y * farHeight + X * farWidth;
plane[TOP].set3Points(nearTopRight,nearTopLeft,farTopLeft);
plane[BOTTOM].set3Points(nearBotLeft,nearBotRight,farBotRight);
plane[LEFT].set3Points(nearTopLeft,nearBotLeft,farBotLeft);
plane[RIGHT].set3Points(nearBotRight,nearTopRight,farBotRight);
//plane[NEAR].set3Points(nearTopLeft,nearTopRight,nearBotRight);
//plane[FAR].set3Points(farTopRight,farTopLeft,farBotLeft);
vec3 aux, normal;
/*plane[NEAR].setNormal(-Z);
plane[NEAR].setPoint(nearCenter);
plane[FAR].setNormal(Z);
plane[FAR].setPoint(farCenter);
aux = nearCenter + ynh;
plane[TOP].setPoint(aux);
aux = normalize(aux - eye);
normal = cross(aux, X);
plane[TOP].setNormal(normal);
aux = nearCenter - ynh;
plane[BOTTOM].setPoint(aux);
aux = normalize(aux - eye);
normal = cross(X, aux);
plane[BOTTOM].setNormal(normal);
aux = nearCenter - xnw;
plane[LEFT].setPoint(aux);
aux = normalize(aux - eye);
normal = cross(aux, Y);
plane[LEFT].setNormal(normal);
aux = nearCenter + xnw;
plane[RIGHT].setPoint(aux);
aux = normalize(aux - eye);
normal = cross( Y, aux);
plane[RIGHT].setNormal(normal);
/*plane[NEAR].setNormal(-Z);
plane[NEAR].setPoint(nearCenter);
plane[FAR].setNormal(Z);
plane[FAR].setPoint(farCenter);
aux = nearCenter + ynh;
plane[TOP].setPoint(aux);
aux = normalize(aux - eye);
normal = aux * X;
plane[TOP].setNormal(normal);
aux = nearCenter - ynh;
plane[BOTTOM].setPoint(aux);
aux = normalize(aux - eye);
normal = X * aux;
plane[BOTTOM].setNormal(normal);
aux = nearCenter - xnw;
plane[LEFT].setPoint(aux);
aux = normalize(aux - eye);
normal = aux * Y;
plane[LEFT].setNormal(normal);
aux = nearCenter + xnw;
plane[RIGHT].setPoint(aux);
aux = normalize(aux - eye);
normal = Y * aux;
plane[RIGHT].setNormal(normal);*/
}
void Frustum::normalizePlane(vec4 &frustum_plane)
{
float magnitude = (float)sqrt(frustum_plane[A] * frustum_plane[A] + frustum_plane[B] * frustum_plane[B] + frustum_plane[C] * frustum_plane[C]);
frustum_plane[A] /= magnitude;
frustum_plane[B] /= magnitude;
frustum_plane[C] /= magnitude;
frustum_plane[D] /= magnitude;
}
void Frustum::CalculateFrustum(mat4 &view_matrix, mat4 &proj_matrix)
{
float *proj = glm::value_ptr(proj_matrix);
float *modl = glm::value_ptr(view_matrix);
float clip[16]; //clipping planes
clip[0] = modl[0] * proj[0] + modl[1] * proj[4] + modl[2] * proj[8] + modl[3] * proj[12];
clip[1] = modl[0] * proj[1] + modl[1] * proj[5] + modl[2] * proj[9] + modl[3] * proj[13];
clip[2] = modl[0] * proj[2] + modl[1] * proj[6] + modl[2] * proj[10] + modl[3] * proj[14];
clip[3] = modl[0] * proj[3] + modl[1] * proj[7] + modl[2] * proj[11] + modl[3] * proj[15];
clip[4] = modl[4] * proj[0] + modl[5] * proj[4] + modl[6] * proj[8] + modl[7] * proj[12];
clip[5] = modl[4] * proj[1] + modl[5] * proj[5] + modl[6] * proj[9] + modl[7] * proj[13];
clip[6] = modl[4] * proj[2] + modl[5] * proj[6] + modl[6] * proj[10] + modl[7] * proj[14];
clip[7] = modl[4] * proj[3] + modl[5] * proj[7] + modl[6] * proj[11] + modl[7] * proj[15];
clip[8] = modl[8] * proj[0] + modl[9] * proj[4] + modl[10] * proj[8] + modl[11] * proj[12];
clip[9] = modl[8] * proj[1] + modl[9] * proj[5] + modl[10] * proj[9] + modl[11] * proj[13];
clip[10] = modl[8] * proj[2] + modl[9] * proj[6] + modl[10] * proj[10] + modl[11] * proj[14];
clip[11] = modl[8] * proj[3] + modl[9] * proj[7] + modl[10] * proj[11] + modl[11] * proj[15];
clip[12] = modl[12] * proj[0] + modl[13] * proj[4] + modl[14] * proj[8] + modl[15] * proj[12];
clip[13] = modl[12] * proj[1] + modl[13] * proj[5] + modl[14] * proj[9] + modl[15] * proj[13];
clip[14] = modl[12] * proj[2] + modl[13] * proj[6] + modl[14] * proj[10] + modl[15] * proj[14];
clip[15] = modl[12] * proj[3] + modl[13] * proj[7] + modl[14] * proj[11] + modl[15] * proj[15];
frustum_planes[RIGHT][A] = clip[3] - clip[0];
frustum_planes[RIGHT][B] = clip[7] - clip[4];
frustum_planes[RIGHT][C] = clip[11] - clip[8];
frustum_planes[RIGHT][D] = clip[15] - clip[12];
normalizePlane(frustum_planes[RIGHT]);
frustum_planes[LEFT][A] = clip[3] + clip[0];
frustum_planes[LEFT][B] = clip[7] + clip[4];
frustum_planes[LEFT][C] = clip[11] + clip[8];
frustum_planes[LEFT][D] = clip[15] + clip[12];
normalizePlane(frustum_planes[LEFT]);
frustum_planes[BOTTOM][A] = clip[3] + clip[1];
frustum_planes[BOTTOM][B] = clip[7] + clip[5];
frustum_planes[BOTTOM][C] = clip[11] + clip[9];
frustum_planes[BOTTOM][D] = clip[15] + clip[13];
normalizePlane(frustum_planes[BOTTOM]);
frustum_planes[TOP][A] = clip[3] - clip[1];
frustum_planes[TOP][B] = clip[7] - clip[5];
frustum_planes[TOP][C] = clip[11] - clip[9];
frustum_planes[TOP][D] = clip[15] - clip[13];
normalizePlane(frustum_planes[TOP]);
frustum_planes[BACK][A] = clip[3] - clip[2];
frustum_planes[BACK][B] = clip[7] - clip[6];
frustum_planes[BACK][C] = clip[11] - clip[10];
frustum_planes[BACK][D] = clip[15] - clip[14];
normalizePlane(frustum_planes[BACK]);
frustum_planes[FRONT][A] = clip[3] + clip[2];
frustum_planes[FRONT][B] = clip[7] + clip[6];
frustum_planes[FRONT][C] = clip[11] + clip[10];
frustum_planes[FRONT][D] = clip[15] + clip[14];
normalizePlane(frustum_planes[FRONT]);
}
bool Frustum::SphereInFrustum(vec3 &pos, float &radius)
{
bool res = true;
//test all 6 frustum planes
for (int i = 0; i < 6; i++)
{
//calculate distance from sphere center to plane.
//if distance larger then sphere radius - sphere is outside frustum
if (frustum_planes[i].x * pos.x + frustum_planes[i].y * pos.y + frustum_planes[i].z * pos.z + frustum_planes[i].w <= -radius)
//res = false;
return false; //with flag works faster
}
return res;
//return true;
}
vec4* Frustum::getFustumPlanes(){
return frustum_planes;
}
|
[
"32463378+TylerSongCS@users.noreply.github.com"
] |
32463378+TylerSongCS@users.noreply.github.com
|
da71a80dd4718fa0838d195c728fb667eeff1222
|
ee32d46014c1f2fc5ec7bb833233c24237270933
|
/0149A/main.cpp
|
1acc3faf51d4caaac68ba6318169aaf91cd0cc41
|
[] |
no_license
|
boxnos/codeforces
|
42b48367d222cc58c2bc0f408469fc6a2732cec7
|
fbc358fe7ddf48d48bda29e75ef3264f9ed19852
|
refs/heads/master
| 2023-08-27T21:18:44.163264
| 2023-08-26T18:06:59
| 2023-08-26T18:06:59
| 192,764,064
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,503
|
cpp
|
#include <cstdio>
#include <utility>
#include <cctype>
#include <array>
#include <algorithm>
using namespace std;
#ifdef __linux
#define _U(s) s##_unlocked
#else
#define _U(s) _##s##_nolock
#define _CRT_DISABLE_PERFCRIT_LOCKS
#endif
#define gcu _U(getchar)
#define pcu _U(putchar)
#define _DEF(r, n, ...) inline r n(__VA_ARGS__) noexcept
#define _T template <typename T>
#define _HT template <typename H,typename... T>
#define _I inline
#define _OP(t) _I operator t()
struct _in {
#ifdef _GLIBCXX_STRING
_OP(string){string s;for(char c;c=gcu(),c!=' '&&c!='\n';)s+=c;return s;}
//_OP(string){string s;char c;while(isspace(c = gcu()));do{s+=c;}while(c=gcu(),c!=' '&&c!='\n'&&c!=EOF);return s;}
#define _S
#endif
_OP(char){char c=gcu();gcu();return c;}
_OP(double){double d; scanf("%lf",&d); gcu();return d;}
_T _OP(T){T n{},m{1},c;while(isspace(c=gcu()));if(c=='-')m=-1,c=gcu();do{n=10*n+(c-'0'),c=gcu();}while(c>='0'&&c<='9');return m*n;}
} in;
#define _SCAN(...) _DEF(bool,scan,__VA_ARGS__)
#ifdef _S
_SCAN(string &o) {int c{gcu()};if(c==EOF)return false;else{ungetc(c,stdin);string t=move(in);o=t;return true;}}
#endif
_T _SCAN(T &o) {int c{gcu()};return c==EOF?false:(ungetc(c,stdin),o=in,true);}
_HT _SCAN(H &h,T&&... t){return scan(h)&&scan(t...);}
#define _OUT(...) _DEF(void,out,__VA_ARGS__)
#define _OUTL(...) _DEF(void,outl,__VA_ARGS__)
_OUT(bool b){pcu('0'+b);}
_OUT(const char *s){while(*s)pcu(*s++);}
_OUT(char c){pcu(c);}
#ifdef _S
_OUT(string &s){for(char c:s)pcu(c);}
#endif
_T _OUT(T n){static char b[20];char *p=b;T m=n<0?pcu('-'),-1:1;
if(!n)*p++='0';else while(n)*p++=(char)(n%10*m+'0'),n/=10;while(p!=b)pcu(*--p);}
_OUTL(){out('\n');}
#ifdef _GLIBCXX_VECTOR
_T _OUT(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);}
#endif
_HT _OUT(H &&h, T... t){out(h);out(t...);}
template <typename... T> _OUTL(T... t){out(t...);outl();}
#define dbg(...) fprintf(stderr,__VA_ARGS__)
struct range{
int e,b=0,s=1;range(int b,int e,int s):e(e),b(b),s(s){} range(int b,int e): e(e), b(b){} range(int e):e(e){}
struct it{int v,s; it(int v,int s):v(v),s(s){} operator int()const{return v;} _I operator int&(){return v;}int operator*()const{return v;}
_I it& operator++(){v+=s;return *this;} }; it begin(){return {b,s};} it end(){return {e,s};}};
#define times(i,n) for(int i=n;i;i--)
int main() {
int k {in}, r {};
array<int, 12> a;
for (int &i: a)
i = in;
sort(rbegin(a), rend(a));
for (; r < 12 && k > 0; k -= a[r++])
;
outl(k > 0 ? -1 : r);
}
/* vim: set ts=4 noet: */
|
[
"boxnos@yahoo.com"
] |
boxnos@yahoo.com
|
48bee5b9336b226226ab59a9ac673c18be2f7d5b
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5709773144064000_0/C++/dinario/main.cpp
|
cca906fe58103b2d86abca0d836ffdb89539eb95
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 843
|
cpp
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <set>
#include <map>
#include <math.h>
#include <algorithm>
using namespace std;
#define re return
#define ll long long
const ll MOD=1E9+7;
int main(){
freopen("B-small-attempt0.in","rt",stdin);
//freopen("input.txt","rt",stdin);
freopen("out.txt","wt",stdout);
ll i,j,n,k=0,T,t;
cin>>T;
cout.precision(20);
for(t=0;t<T;++t){
double C,F,X;
cin>>C>>F>>X;
double sum=0,speed=2;
double res=0;
bool bFoo=false;
for(i=0;!bFoo;++i){
double estimateX = X/speed;
double estimateC = C/speed;
double estimateX2 = estimateC+X/(speed+F);
if(estimateX2 < estimateX){
speed+=F;
res+=estimateC;
}else {
bFoo = true;
res+=estimateX;
}
}
cout<<"Case #"<<t+1<<": "<<res<<endl;
}
re 0;
}
|
[
"eewestman@gmail.com"
] |
eewestman@gmail.com
|
49b4b36854ab73c6cd405c4b62228dc11a90bb5d
|
d10c78fd9cdd3e0cd06d1da4ec105c9d2b179b6a
|
/build/VisualStudio/AIPU/ForceSensor.h
|
620ccc34189f599b72a29782614c08c8d28c5311
|
[] |
no_license
|
sleimanf/aibot
|
95768573e65d99fd7b9c6f1cab9e57a4c6285677
|
a1c31ba89f60d54aedbbb5706e2905214fb22881
|
refs/heads/master
| 2020-05-28T08:58:36.239013
| 2014-09-01T21:39:31
| 2014-09-01T21:39:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 121
|
h
|
#pragma once
class ForceSensor
{
int Force;
public:
ForceSensor();
~ForceSensor();
bool setCurrentSensorValue();
};
|
[
"hadiesper@gmail.com"
] |
hadiesper@gmail.com
|
060514ae5c77fc45abea1256b5a82290a4ddda45
|
0edbcda83b7a9542f15f706573a8e21da51f6020
|
/private/inet/mshtml/msaahtml/checkbox.h
|
c7aa1c4ffe942bc815dcc0654db76d152f82d3df
|
[] |
no_license
|
yair-k/Win2000SRC
|
fe9f6f62e60e9bece135af15359bb80d3b65dc6a
|
fd809a81098565b33f52d0f65925159de8f4c337
|
refs/heads/main
| 2023-04-12T08:28:31.485426
| 2021-05-08T22:47:00
| 2021-05-08T22:47:00
| 365,623,923
| 1
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,157
|
h
|
//================================================================================
// File: CHECKBOX.H
// Date: 6/11/97
// Desc: Contains the definition of the CCheckboxAO class. This class
// implements the accessible proxy for the Trident check box control.
//
// Author: Arunj
//
//================================================================================
#ifndef __CHECKBOXAO__
#define __CHECKBOXAO__
//================================================================================
// Includes
//================================================================================
#include "optnbtn.h"
#ifdef _MSAA_EVENTS
#include "event.h"
#endif
//================================================================================
// CCheckboxAO class definition
//================================================================================
class CCheckboxAO: public COptionButtonAO
{
public:
//--------------------------------------------------
// IUnknown
//--------------------------------------------------
virtual STDMETHODIMP QueryInterface(REFIID riid, void** ppv);
//--------------------------------------------------
// Internal IAccessible support
//--------------------------------------------------
virtual HRESULT GetAccDefaultAction( long lChild, BSTR* pbstrDefAction );
//--------------------------------------------------
// standard object methods
//--------------------------------------------------
CCheckboxAO(CTridentAO* pAOParent,CDocumentAO * pDocAO, UINT nTOMIndex,UINT nChildID,HWND hWnd);
~CCheckboxAO();
HRESULT Init(IUnknown* pTOMObjIUnk);
protected:
//--------------------------------------------------
// protected helper methods
//--------------------------------------------------
virtual HRESULT getDefaultActionString( BSTR* pbstrDefaultAction );
#ifdef _MSAA_EVENTS
//--------------------------------------------------
// Event handler implementation
//--------------------------------------------------
DECLARE_EVENT_HANDLER(ImplHTMLOptionButtonElementEvents,CEvent,DIID_HTMLOptionButtonElementEvents)
#endif
};
#endif // __CHECKBOXAO__
|
[
"ykorokhov@pace.ca"
] |
ykorokhov@pace.ca
|
ddfafa69c173a85c8ed0fd583f3f6b2a79a43044
|
987adde7bd3455da593f0201b4fe0437f65b5f27
|
/src/BackEnd/IRGeneration/NameBuilder.cpp
|
fecadeada32f0c321f4c4f65ae656ba82a1057b6
|
[] |
no_license
|
xcode2010/KawaCompiler
|
d502ca2b290d8443753bb18815dcd696715baffc
|
3c1b37f86e46084d6d43bbd6771b98808006135d
|
refs/heads/master
| 2021-12-05T15:16:56.765143
| 2015-06-30T08:16:00
| 2015-06-30T08:16:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,100
|
cpp
|
/**
* Creator Hichara
*/
#include "NameBuilder.h"
std::string NameBuilder::buildFunctionName(std::string className,
std::string name,
std::string ret_type,
std::vector<std::string> list_type,
bool isStatic) {
std::stringstream result;
std::string tmp;
if(className == "")
return "";
if(name == "")
return "";
if(isStatic)
result << KawaEnumeration::STATIC << "_";
result << className << '.' << name << "_rt_";
result << strToKawaType(ret_type);
result << "_pt_";
if (list_type.size() == 0) {
result << "_" << KawaEnumeration::KAWA_VOID;
result.str();
}
for(std::vector<std::string>::iterator it = list_type.begin();
it != list_type.end(); ++it) {
tmp = strToKawaType((*it));;
if(tmp == "")
return "";
result << "_" << tmp;
}
return result.str();
}
std::string buidClassAdHocTableIndex(std::string className) {
std::stringstream res;
res << className << "_adHoc_index";
return res.str();
}
std::string NameBuilder::buildConstructorName(std::string className,
std::vector<std::string> list_type) {
std::string tmp;
std::stringstream result;
if(className == "")
return "";
result << KawaEnumeration::CONSTRUCTOR_PREFIX << className;
if (list_type.size() == 0) {
result << "_pt_" << KawaEnumeration::KAWA_VOID;
return result.str();
}
for(int i = 0; i < list_type.size(); i++) {
tmp = strToKawaType(list_type[i]);
result << "_pt_" << tmp;
}
return result.str();
}
std::string NameBuilder::buildSubConstructorName(std::string className,
std::vector<std::string> list_type) {
std::string tmp;
std::stringstream result;
if(className == "")
return "";
result << KawaEnumeration::SUB_CONSTRUCTOR_PREFIX << className;
if (list_type.size() == 0) {
result << "_pt_" << KawaEnumeration::KAWA_VOID;
return result.str();
}
for(int i = 0; i < list_type.size(); i++) {
tmp = strToKawaType(list_type[i]);
result << "_pt_" << tmp;
}
return result.str();
}
// L'index est suceptible d'etre le meme pour toute les tables issues de la meme famille
std::string NameBuilder::buildFunctionIndexName(std::string functionBuiltName) {
std::stringstream res;
res << KawaEnumeration::METHODE_INDEX_PREFIX << functionBuiltName;
return res.str();
}
std::string NameBuilder::buildAdHocTableName(std::string classStatic,
std::string classDynamique) {
if(classStatic == "" || classDynamique == "")
return "";
std::stringstream res;
res << KawaEnumeration::ADHOCTABLE_PREFIX << "_" << classStatic << "_" << classDynamique;
return res.str();
}
std::string NameBuilder::buildgetAdHocTableFunction(std::string staticC, std::string dynamicC) {
std::stringstream res;
res << "get_table_" << buildAdHocTableName(staticC, dynamicC);
return res.str();
}
std::string NameBuilder::buildAttributIndexName(std::string className, std::string name) {
std::stringstream res;
res << KawaEnumeration::ATTRIBUT_INDEX_PREFIX << "_" << className << "_" << name;
return res.str();
}
std::string NameBuilder::buildStaticVariableName(std::string className,
std::string name) {
std::stringstream res;
res << KawaEnumeration::STATIC << "_" << className << "_" << name;
return res.str();
}
std::string NameBuilder::buildClassTypeName(std::string className) {
if(className == "")
return "";
std::stringstream result;
result << KawaEnumeration::KAWA_CLASS_PREFIX << className;
return result.str();
}
std::string NameBuilder::buildClassStructTypeName(std::string className) {
if(className == "")
return "";
std::stringstream res;
res << KawaEnumeration::KAWA_CLASS_STRUCT_PREFIX << className;
return res.str();
}
std::string NameBuilder::strToKawaType(std::string type) {
std::stringstream result;
if(type == KawaEnumeration::FLOAT)
result << KawaEnumeration::KAWA_FLOAT;
else if(type == KawaEnumeration::INT)
result << KawaEnumeration::KAWA_INT;
else if(type == KawaEnumeration::CHAR)
result << KawaEnumeration::KAWA_CHAR;
else if(type == KawaEnumeration::DOUBLE)
result << KawaEnumeration::KAWA_DOUBLE;
else if(type == KawaEnumeration::STRING)
result << KawaEnumeration::KAWA_STRING;
else
result << buildClassTypeName(type);
return result.str();
}
std::string NameBuilder::StructNameToClass(std::string n) {
return n.substr(KawaEnumeration::KAWA_CLASS_PREFIX.length());
}
std::string NameBuilder::LLVMTypeToStr(Type* type) {
LLVMContext &c = type->getContext();
if(type == (Type*)Type::getInt32Ty(c))
return KawaEnumeration::KAWA_INT;
if(type == (Type*)Type::getInt8Ty(c))
return KawaEnumeration::KAWA_CHAR;
if(type == (Type*)Type::getVoidTy(c))
return KawaEnumeration::KAWA_VOID;
if(type == (Type*)Type::getFloatTy(c))
return KawaEnumeration::KAWA_FLOAT;
if(type == (Type*)Type::getDoubleTy(c))
return KawaEnumeration::KAWA_DOUBLE;
if(type == (Type*)Type::getInt8PtrTy(c))
return KawaEnumeration::KAWA_STRING;
if(type->isStructTy())
return KawaEnumeration::KAWA_CLASS_PREFIX + (type->getStructName()).str();
return "";
}
|
[
"adjibi004@gmail.com"
] |
adjibi004@gmail.com
|
b466b2c89c8d2ddd3449bf6d3013c62e7e20aa97
|
af008dd81eda45dc54a926647efec8ac6bf6bd6b
|
/fun1/arfupt.cpp
|
4f99de181cec14c840381ed044a2bc41377c31bc
|
[] |
no_license
|
user-lmz/cmake-cpp
|
d003caa827a1deff5f403bad113b44572325f028
|
f229a8ec95655a13b3e2f1931ffb4e5c291b4e2a
|
refs/heads/master
| 2023-07-06T20:11:04.471655
| 2021-08-24T07:59:12
| 2021-08-24T07:59:12
| 339,757,218
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,441
|
cpp
|
#include <iostream>
const double * f1(const double ar[], int n);
const double * f2(const double [], int);
const double * f3(const double *, int);
int main()
{
using namespace std;
double av[3] = {1112.3, 1542.6, 2227.9};
typedef const double *(*p_fun)(const double *, int);
p_fun p1 = f1;
auto p2 = f2;
cout << "Using pointers to functions:\n";
cout << " Address Value\n";
cout << (*p1)(av,3) << ": " << *(*p1)(av,3) << endl;
cout << p2(av,3) << ": " << *p2(av,3) << endl;
p_fun pa[3] = {f1, f2, f3};
auto pb = pa;
cout << "\nUsing an array of pointers to functions:\n";
cout << " Address Value\n";
for (int i = 0; i < 3; i++)
cout << pa[i](av,3) << ": " << *pa[i](av,3) << endl;
cout << " Address Value\n";
for (int i = 0; i < 3; i++)
cout << pb[i](av,3) << ": " << *pb[i](av,3) << endl;
cout << "\nUsing an array of pointers to functions:\n";
cout << " Address Value\n";
auto pc = &pa;
cout << (*pc)[0](av,3) << ": " << *(*pc)[0](av,3) << endl;
p_fun (*pd)[3] = &pa;
const double *pdb = (*pd)[1](av,3);
cout << pdb << ": " << *pdb << endl;
cout << (*(*pd)[2])(av,3) << ": " << *(*(*pd)[2])(av,3) << endl;
return 0;
}
const double * f1(const double * ar, int n)
{
return ar;
}
const double * f2(const double ar[], int n)
{
return ar+1;
}
const double * f3(const double ar[], int n)
{
return ar+2;
}
|
[
"mingzeluo888@gmail.com"
] |
mingzeluo888@gmail.com
|
a912e284dbfbb5e12a2c4f9d2d71d9f303308f2a
|
f8517de40106c2fc190f0a8c46128e8b67f7c169
|
/AllJoyn/Samples/MyLivingRoom/Models/org.alljoyn.ControlPanel/AllJoynHelpers.h
|
4df47019afd9527f6684dd36658f2acc3d6d1579
|
[
"MIT"
] |
permissive
|
ferreiramarcelo/samples
|
eb77df10fe39567b7ebf72b75dc8800e2470108a
|
4691f529dae5c440a5df71deda40c57976ee4928
|
refs/heads/develop
| 2023-06-21T00:31:52.939554
| 2021-01-23T16:26:59
| 2021-01-23T16:26:59
| 66,746,116
| 0
| 0
|
MIT
| 2023-06-19T20:52:43
| 2016-08-28T02:48:20
|
C
|
UTF-8
|
C++
| false
| false
| 8,787
|
h
|
#pragma once
// The amount of time to wait (ms) for a response after sending a message before timing out.
const int c_MessageTimeoutInMilliseconds = 10000;
// The maximum length of an AllJoyn type signature allowed by the AllJoyn Core library.
const int c_MaximumSignatureLength = 255;
#define RETURN_IF_QSTATUS_ERROR(status) \
{ \
int32 alljoynStatus = static_cast<int32>(status); \
if (Windows::Devices::AllJoyn::AllJoynStatus::Ok != alljoynStatus) \
{ \
return status; \
} \
}
class AllJoynHelpers
{
public:
// The Windows::Devices::AllJoyn::AllJoynBusAttachment class wraps the alljoyn_busattachment type. This
// function gets the underlying alljoyn_busattachment.
static alljoyn_busattachment GetInternalBusAttachment(_In_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment);
// Create the alljoyn_interfacedescriptions described in introspectionXml and add them to the busAttachment.
static QStatus CreateInterfaces(_Inout_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment, _In_ PCSTR introspectionXml);
// Convert a UTF8 string to a wide character Platform::String.
static Platform::String^ MultibyteToPlatformString(_In_ PCSTR);
// Convert a wide character Platform::String to a UTF8 string.
static std::vector<char> PlatformToMultibyteString(_In_ Platform::String^ str);
// Get the service object path from an objectDescriptionArg. The objectDescriptionArg should
// come from an Announce signal.
static Platform::String^ AllJoynHelpers::GetObjectPath(_In_ alljoyn_aboutobjectdescription objectDescription, _In_ PCSTR interfaceName);
// Callback for alljoyn_about_announced_ptr.
// This callback expects the context to be of type T, which must implement the OnAnnounce function.
template<class T>
static void AnnounceHandler(
_In_ const void* context,
_In_ PCSTR name,
_In_ uint16_t version,
_In_ alljoyn_sessionport port,
_In_ alljoyn_msgarg objectDescriptionArg,
_In_ const alljoyn_msgarg aboutDataArg)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnAnnounce(name, version, port, objectDescriptionArg, aboutDataArg);
}
// Callback for alljoyn_proxybusobject_listener_propertieschanged_ptr.
// This callback expects the context to be of type T, which must implement the OnPropertyChanged function.
template<class T>
static void PropertyChangedHandler(_In_ alljoyn_proxybusobject obj, _In_ PCSTR interfaceName, _In_ const alljoyn_msgarg changed, _In_ const alljoyn_msgarg invalidated, _In_ void* context)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnPropertyChanged(obj, interfaceName, changed, invalidated);
}
// Callback for alljoyn_busobject_prop_get_ptr.
template<class T>
static QStatus PropertyGetHandler(_In_ const void* context, _In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg value)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
return caller->OnPropertyGet(interfaceName, propertyName, value);
}
// Callback for alljoyn_busobject_prop_set_ptr.
template<class T>
static QStatus PropertySetHandler(_In_ const void* context, _In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg value)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
return caller->OnPropertySet(interfaceName, propertyName, value);
}
// Callback for alljoyn_sessionlistener_sessionlost_ptr.
template<class T>
static void SessionLostHandler(_In_ const void* context, _In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnSessionLost(sessionId, reason);
}
// Callback for alljoyn_sessionlistener_sessionmemberadded_ptr.
template<class T>
static void SessionMemberAddedHandler(_In_ const void* context, _In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnSessionMemberAdded(sessionId, uniqueName);
}
// Callback for alljoyn_sessionlistener_sessionmemberremoved_ptr.
template<class T>
static void SessionMemberRemovedHandler(_In_ const void* context, _In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnSessionMemberRemoved(sessionId, uniqueName);
}
// Create an AllJoyn bus object.
template<class T>
static QStatus CreateBusObject(_Inout_ Platform::WeakReference* target)
{
alljoyn_busobject_callbacks callbacks =
{
PropertyGetHandler<T>,
PropertySetHandler<T>,
nullptr,
nullptr,
};
T^ caller = target->Resolve<T>();
auto serviceObjectPath = PlatformToMultibyteString(caller->ServiceObjectPath);
alljoyn_busobject busObject = alljoyn_busobject_create(serviceObjectPath.data(), false, &callbacks, target);
if (busObject == nullptr)
{
return ER_FAIL;
}
caller->BusObject = busObject;
return ER_OK;
}
// Callback for alljoyn_sessionportlistener_acceptsessionjoiner_ptr.
// This callback expects the context to be of type T, which must implement the OnAcceptSessionJoiner function.
template<class T>
static QCC_BOOL AcceptSessionJoinerHandler(
_In_ const void* context,
_In_ alljoyn_sessionport sessionPort,
_In_ PCSTR joiner,
_In_ const alljoyn_sessionopts opts)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
return caller->OnAcceptSessionJoiner(sessionPort, joiner, opts);
}
// Callback for alljoyn_sessionportlistener_sessionjoined_ptr.
// This callback expects the context to be of type T, which must implement the OnSessionJoined function.
template<class T>
static void SessionJoinedHandler(
_In_ const void* context,
_In_ alljoyn_sessionport sessionPort,
_In_ alljoyn_sessionid id,
_In_ PCSTR joiner)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnSessionJoined(sessionPort, id, joiner);
}
// Create the session for an AllJoyn producer.
template<class T>
static QStatus CreateProducerSession(_Inout_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment, _Inout_ Platform::WeakReference* target)
{
alljoyn_sessionopts opts = alljoyn_sessionopts_create(ALLJOYN_TRAFFIC_TYPE_MESSAGES, true, ALLJOYN_PROXIMITY_ANY, ALLJOYN_TRANSPORT_ANY);
alljoyn_sessionportlistener_callbacks callbacks =
{
AcceptSessionJoinerHandler<T>,
SessionJoinedHandler<T>
};
T^ producer = target->Resolve<T>();
producer->SessionPortListener = alljoyn_sessionportlistener_create(&callbacks, target);
alljoyn_sessionport sessionPort = 42;
alljoyn_busattachment_unbindsessionport(AllJoynHelpers::GetInternalBusAttachment(busAttachment), sessionPort);
RETURN_IF_QSTATUS_ERROR(alljoyn_busattachment_bindsessionport(AllJoynHelpers::GetInternalBusAttachment(busAttachment), &sessionPort, opts, producer->SessionPortListener));
producer->SessionPort = sessionPort;
alljoyn_sessionopts_destroy(opts);
return ER_OK;
}
};
// Passed to property get callbacks to allow them to report when the async operation is completed.
template<class T>
class PropertyGetContext
{
public:
void SetEvent()
{
m_event.set();
}
void Wait()
{
m_event.wait();
}
QStatus GetStatus()
{
return m_status;
}
void SetStatus(QStatus value)
{
m_status = value;
}
T GetValue()
{
return m_value;
}
void SetValue(T value)
{
m_value = value;
}
private:
Concurrency::event m_event;
QStatus m_status;
T m_value;
};
// Passed to property set callbacks to allow them to report when the async operation is completed.
class PropertySetContext
{
public:
void SetEvent()
{
m_event.set();
}
void Wait()
{
m_event.wait();
}
QStatus GetStatus()
{
return m_status;
}
void SetStatus(QStatus value)
{
m_status = value;
}
private:
Concurrency::event m_event;
QStatus m_status;
};
|
[
"artemz@microsoft.com"
] |
artemz@microsoft.com
|
fdbe0397e3b64fd79912fe8d8cbcbca1e5d0bdba
|
85266696a160174b0a0708233fb6f0270bc8d7d7
|
/eos/utils/concrete-cacheable-observable.hh
|
2bd48c06131bb291bf98d96365502407d02fd7b3
|
[] |
no_license
|
dvandyk/eos
|
0596bdf978340043081b296f7d90fdb2e5a75fac
|
5e3f68989713078d010e0451bcb0049032dba6e8
|
refs/heads/master
| 2023-08-25T04:24:51.590382
| 2021-04-08T10:09:44
| 2021-05-25T14:19:00
| 46,611,195
| 0
| 1
| null | 2020-03-18T13:43:13
| 2015-11-21T10:39:59
|
C++
|
UTF-8
|
C++
| false
| false
| 13,560
|
hh
|
/* vim: set sw=4 sts=4 et foldmethod=syntax : */
/*
* Copyright (c) 2021 Danny van Dyk
*
* This file is part of the EOS project. EOS is free software;
* you can redistribute it and/or modify it under the terms of the GNU General
* Public License version 2, as published by the Free Software Foundation.
*
* EOS is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef EOS_GUARD_SRC_UTILS_CONCRETE_CACHEABLE_OBSERVABLE_HH
#define EOS_GUARD_SRC_UTILS_CONCRETE_CACHEABLE_OBSERVABLE_HH 1
#include <eos/observable-impl.hh>
#include <eos/utils/apply.hh>
#include <eos/utils/join.hh>
#include <eos/utils/tuple-maker.hh>
#include <eos/utils/wrapped_forward_iterator-impl.hh>
#include <array>
#include <functional>
#include <string>
namespace eos
{
template <typename Decay_, typename ... Args_>
class ConcreteCacheableObservable;
template <typename Decay_, typename ... Args_>
class ConcreteCachedObservable :
public Observable
{
private:
QualifiedName _name;
Parameters _parameters;
Kinematics _kinematics;
Options _options;
std::shared_ptr<Decay_> _decay;
const typename Decay_::IntermediateResult * _intermediate_result;
std::function<const typename Decay_::IntermediateResult * (const Decay_ *, const Args_ & ...)> _prepare_fn;
std::function<double (const Decay_ *, const typename Decay_::IntermediateResult *)> _evaluate_fn;
std::tuple<typename impl::ConvertTo<Args_, const char *>::Type ...> _kinematics_names;
public:
ConcreteCachedObservable(const QualifiedName & name,
const Parameters & parameters,
const Kinematics & kinematics,
const Options & options,
const std::shared_ptr<Decay_> & decay,
const typename Decay_::IntermediateResult * intermediate_result,
const std::function<const typename Decay_::IntermediateResult * (const Decay_ *, const Args_ & ...)> & prepare_fn,
const std::function<double (const Decay_ *, const typename Decay_::IntermediateResult *)> & evaluate_fn,
const std::tuple<typename impl::ConvertTo<Args_, const char *>::Type ...> & kinematics_names) :
_name(name),
_parameters(parameters),
_kinematics(kinematics),
_options(options),
_decay(decay),
_intermediate_result(intermediate_result),
_prepare_fn(prepare_fn),
_evaluate_fn(evaluate_fn),
_kinematics_names(kinematics_names)
{
uses(*_decay);
}
~ConcreteCachedObservable() = default;
virtual const QualifiedName & name() const
{
return _name;
}
virtual double evaluate() const
{
return _evaluate_fn(_decay.get(), _intermediate_result);
};
virtual Parameters parameters()
{
return _parameters;
};
virtual Kinematics kinematics()
{
return _kinematics;
};
virtual Options options()
{
return _options;
}
virtual ObservablePtr clone() const
{
return ObservablePtr(new ConcreteCacheableObservable<Decay_, Args_ ...>(_name, _parameters.clone(), _kinematics.clone(), _options, _prepare_fn, _evaluate_fn, _kinematics_names));
}
virtual ObservablePtr clone(const Parameters & parameters) const
{
return ObservablePtr(new ConcreteCacheableObservable<Decay_, Args_ ...>(_name, parameters, _kinematics.clone(), _options, _prepare_fn, _evaluate_fn, _kinematics_names));
}
};
template <typename Decay_, typename ... Args_>
class ConcreteCacheableObservable :
public CacheableObservable
{
private:
QualifiedName _name;
Parameters _parameters;
Kinematics _kinematics;
Options _options;
std::shared_ptr<Decay_> _decay;
std::function<const typename Decay_::IntermediateResult * (const Decay_ *, const Args_ & ...)> _prepare_fn;
std::function<double (const Decay_ *, const typename Decay_::IntermediateResult *)> _evaluate_fn;
std::tuple<typename impl::ConvertTo<Args_, const char *>::Type ...> _kinematics_names;
std::tuple<const Decay_ *, typename impl::ConvertTo<Args_, KinematicVariable>::Type ...> _argument_tuple;
public:
ConcreteCacheableObservable(const QualifiedName & name,
const Parameters & parameters,
const Kinematics & kinematics,
const Options & options,
const std::function<const typename Decay_::IntermediateResult * (const Decay_ *, const Args_ & ...)> & prepare_fn,
const std::function<double (const Decay_ *, const typename Decay_::IntermediateResult *)> & evaluate_fn,
const std::tuple<typename impl::ConvertTo<Args_, const char *>::Type ...> & kinematics_names) :
_name(name),
_parameters(parameters),
_kinematics(kinematics),
_options(options),
_decay(new Decay_(parameters, options)),
_prepare_fn(prepare_fn),
_evaluate_fn(evaluate_fn),
_kinematics_names(kinematics_names),
_argument_tuple(impl::TupleMaker<sizeof...(Args_)>::make(_kinematics, _kinematics_names, _decay.get()))
{
uses(*_decay);
}
~ConcreteCacheableObservable() = default;
virtual const QualifiedName & name() const
{
return _name;
}
virtual double evaluate() const
{
std::tuple<const Decay_ *, typename impl::ConvertTo<Args_, double>::Type ...> values = _argument_tuple;
const typename Decay_::IntermediateResult * intermediate_result = apply(_prepare_fn, values);
return _evaluate_fn(_decay.get(), intermediate_result);
};
virtual const CacheableObservable::IntermediateResult * prepare() const
{
std::tuple<const Decay_ *, typename impl::ConvertTo<Args_, double>::Type ...> values = _argument_tuple;
return apply(_prepare_fn, values);
}
virtual double evaluate(const CacheableObservable::IntermediateResult * intermediate_result) const
{
return _evaluate_fn(_decay.get(), static_cast<const typename Decay_::IntermediateResult *>(intermediate_result));
}
virtual Parameters parameters()
{
return _parameters;
};
virtual Kinematics kinematics()
{
return _kinematics;
};
virtual Options options()
{
return _options;
}
virtual ObservablePtr make_cached_observable(const CacheableObservable * _other) const
{
auto other = dynamic_cast<decltype(this)>(_other);
if (nullptr == other)
return { nullptr };
if (other->_parameters != this->_parameters)
return { nullptr };
if (other->_kinematics != this->_kinematics)
return { nullptr };
if (other->_options != this->_options)
return { nullptr };
/*
* The values tuple contains a pointer to the Decay_ object, which owns the persistent pointer
* to the intermediate result. We make sure to use _other->_argument tuples, to ensure that
* the correct pointer to the intermediate result is used.
*/
std::tuple<const Decay_ *, typename impl::ConvertTo<Args_, double>::Type ...> values = other->_argument_tuple;
return ObservablePtr(new ConcreteCachedObservable<Decay_, Args_ ...>(_name, _parameters, _kinematics, _options, other->_decay, apply(other->_prepare_fn, values), _prepare_fn, _evaluate_fn, _kinematics_names));
}
virtual ObservablePtr clone() const
{
return ObservablePtr(new ConcreteCacheableObservable(_name, _parameters.clone(), _kinematics.clone(), _options, _prepare_fn, _evaluate_fn, _kinematics_names));
}
virtual ObservablePtr clone(const Parameters & parameters) const
{
return ObservablePtr(new ConcreteCacheableObservable(_name, parameters, _kinematics.clone(), _options, _prepare_fn, _evaluate_fn, _kinematics_names));
}
};
template <typename Decay_, typename ... Args_>
class ConcreteCacheableObservableEntry :
public ObservableEntry
{
private:
QualifiedName _name;
std::string _latex;
std::function<const typename Decay_::IntermediateResult * (const Decay_ *, const Args_ & ...)> _prepare_fn;
std::function<double (const Decay_ *, const typename Decay_::IntermediateResult *)> _evaluate_fn;
std::tuple<typename impl::ConvertTo<Args_, const char *>::Type ...> _kinematics_names;
std::array<const std::string, sizeof...(Args_)> _kinematics_names_array;
Options _forced_options;
public:
ConcreteCacheableObservableEntry(const QualifiedName & name, const std::string & latex,
const std::function<const typename Decay_::IntermediateResult * (const Decay_ *, const Args_ & ...)> & prepare_fn,
const std::function<double (const Decay_ *, const typename Decay_::IntermediateResult *)> & evaluate_fn,
const std::tuple<typename impl::ConvertTo<Args_, const char *>::Type ...> & kinematics_names,
const Options & forced_options) :
_name(name),
_latex(latex),
_prepare_fn(prepare_fn),
_evaluate_fn(evaluate_fn),
_kinematics_names(kinematics_names),
_kinematics_names_array(impl::make_array<const std::string>(kinematics_names)),
_forced_options(forced_options)
{
}
~ConcreteCacheableObservableEntry()
{
}
virtual const QualifiedName & name() const
{
return _name;
}
virtual const std::string & latex() const
{
return _latex;
}
virtual ObservableEntry::KinematicVariableIterator begin_kinematic_variables() const
{
return _kinematics_names_array.begin();
}
virtual ObservableEntry::KinematicVariableIterator end_kinematic_variables() const
{
return _kinematics_names_array.end();
}
virtual ObservablePtr make(const Parameters & parameters, const Kinematics & kinematics, const Options & options) const
{
return ObservablePtr(new ConcreteCacheableObservable<Decay_, Args_ ...>(_name, parameters, kinematics, options + _forced_options, _prepare_fn, _evaluate_fn, _kinematics_names));
}
virtual std::ostream & insert(std::ostream & os) const
{
os << " type: cacheable observable" << std::endl;
if (sizeof...(Args_) > 0)
{
os << " kinematic variables: " << join(std::begin(_kinematics_names_array), std::end(_kinematics_names_array)) << std::endl;
}
return os;
}
};
template <typename Decay_, typename Tuple_, typename ... Args_>
ObservableEntryPtr make_concrete_cacheable_observable_entry(const QualifiedName & name, const std::string & latex,
const typename Decay_::IntermediateResult * (Decay_::* prepare_fn)(const Args_ & ...) const,
double (Decay_::* evaluate_fn)(const typename Decay_::IntermediateResult *) const,
const Tuple_ & kinematics_names,
const Options & forced_options)
{
static_assert(sizeof...(Args_) == impl::TupleSize<Tuple_>::size, "Need as many function arguments as kinematics names!");
return std::make_shared<ConcreteCacheableObservableEntry<Decay_, Args_ ...>>(name, latex,
std::function<const typename Decay_::IntermediateResult * (const Decay_ *, const Args_ & ...)>(std::mem_fn(prepare_fn)),
std::function<double (const Decay_ *, const typename Decay_::IntermediateResult *)>(std::mem_fn(evaluate_fn)),
kinematics_names, forced_options);
}
}
#endif
|
[
"danny.van.dyk@gmail.com"
] |
danny.van.dyk@gmail.com
|
e936d997c65d00067631eb971a0b7d7205676fe4
|
8908b42d07771a4c50d1adae1b13481b55d6c189
|
/ConsoleJanken/StatePrepare.h
|
f786aa2f7ac38416d57a910754fd69dd9a217d62
|
[] |
no_license
|
haraki/ConsoleJanken
|
6010630647c7586138bc18107d040ff7e9e7f7bf
|
e0802f91e0b6fed18d377a570dd6ab42c347b747
|
refs/heads/master
| 2021-01-22T09:09:08.861952
| 2014-05-19T17:41:05
| 2014-05-19T17:41:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 803
|
h
|
//
// StatePrepare.h
// ConsoleJanken
//
// Created by 原木 正志 on 2014/04/23.
// Copyright (c) 2014年 Masashi Haraki. All rights reserved.
//
#ifndef __ConsoleJanken__StatePrepare__
#define __ConsoleJanken__StatePrepare__
#include <iostream>
#include "StateMachine.h"
class StatePrepare : public StateMachine, public SingletonState <StatePrepare>
{
public:
StatePrepare();
~StatePrepare();
int entry();
int execute();
int exit();
int eventFrame(StateContext& context, const Leap::Controller& controller);
int eventHandLost(StateContext& context, const Leap::Controller& controller);
int eventDisconnect(StateContext& context, const Leap::Controller& controller);
private:
int m_count;
};
#endif /* defined(__ConsoleJanken__StatePrepare__) */
|
[
"masa.haraki@gmail.com"
] |
masa.haraki@gmail.com
|
26fbfd9c162e773bc79d7db3b707cc333a1b8e56
|
c2305575458830fbf9bdabdf26dbfc17d037dcc2
|
/Old/minimumArraySet.cpp
|
4d954c76e358ae73f44702856979e25fa110c279
|
[] |
no_license
|
shribadiger/CPPStudy
|
6adc747ebf67e903d1b00920c276d55712edd0ed
|
75aa4c1033f0c72322ab68ea320c1c120dfbfced
|
refs/heads/master
| 2023-02-19T22:38:38.372271
| 2023-02-09T08:44:30
| 2023-02-09T08:44:30
| 183,357,549
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,510
|
cpp
|
/*
Leet code program to identify minimum size of elements remove from the array
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int minSetSize(vector<int> &arr)
{
std::vector<int> maxChecker;
int counter = 1;
std::sort(arr.begin(), arr.end());
for (int i = 1; i < arr.size(); i++)
{
//cout<<"\n"<<arr[i]<<":"<<arr[i-1]<<endl;
if (arr[i] == arr[i - 1])
{
counter++;
continue;
}
maxChecker.push_back(counter);
counter = 1;
}
maxChecker.push_back(counter);
std::sort(maxChecker.begin(), maxChecker.end(), greater<int>());
// printing the iterator and check the logic is working or not
std::vector<int>::iterator itr = maxChecker.begin();
cout << "\n Max Repeater List\n";
int devider = 0;
int excluder = 0;
while (itr != maxChecker.end())
{
cout << "\t" << *itr;
devider += *itr;
if (arr.size() - devider <= arr.size() / 2)
{
excluder++;
break;
}
itr++;
excluder++;
}
return excluder;
}
int main()
{
std::vector<int> input1 = {3, 3, 3, 3, 5, 5, 5, 2, 2, 7};
cout << "\n Result: " << minSetSize(input1);
std::vector<int> input2 = {7, 7, 7, 7, 7, 7};
cout << "\n Result: " << minSetSize(input2);
std::vector<int> input3 = {9, 77, 63, 22, 92, 9, 14, 54, 8, 38, 18, 19, 38, 68, 58, 19};
cout << "\n Result: " << minSetSize(input3);
// cout<<"\n Size of Input: "<<input.size();
return 0;
}
|
[
"shrikant200@gmail.com"
] |
shrikant200@gmail.com
|
45531e257ed6672a0bb50b0bdf27dc79b533b004
|
db111ff94903f0b24658c328d93f5cc28b670b8d
|
/components/page_load_metrics/browser/metrics_web_contents_observer.cc
|
d9f4123665703db635e066025b92e232498f06c8
|
[
"BSD-3-Clause"
] |
permissive
|
nibilin33/chromium
|
21e505ab4c6dec858d3b0fe2bfbaf56d023d9f0d
|
3dea9ffa737bc9c9a9f58d4bab7074e3bc84f349
|
refs/heads/master
| 2023-01-16T10:54:57.353825
| 2020-04-02T04:24:11
| 2020-04-02T04:24:11
| 252,359,157
| 1
| 0
|
BSD-3-Clause
| 2020-04-02T04:57:37
| 2020-04-02T04:57:37
| null |
UTF-8
|
C++
| false
| false
| 33,365
|
cc
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/page_load_metrics/browser/metrics_web_contents_observer.h"
#include <algorithm>
#include <ostream>
#include <string>
#include <utility>
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "components/page_load_metrics/browser/page_load_metrics_embedder_interface.h"
#include "components/page_load_metrics/browser/page_load_metrics_update_dispatcher.h"
#include "components/page_load_metrics/browser/page_load_metrics_util.h"
#include "components/page_load_metrics/browser/page_load_tracker.h"
#include "components/page_load_metrics/common/page_load_timing.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/global_request_id.h"
#include "content/public/browser/media_player_id.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
#include "third_party/blink/public/common/loader/resource_type_util.h"
#include "ui/base/page_transition_types.h"
namespace page_load_metrics {
namespace {
// Returns the HTTP status code for the current page, or -1 if no status code
// is available. Can only be called if the |navigation_handle| has committed.
int GetHttpStatusCode(content::NavigationHandle* navigation_handle) {
DCHECK(navigation_handle->HasCommitted());
const net::HttpResponseHeaders* response_headers =
navigation_handle->GetResponseHeaders();
if (!response_headers)
return -1;
return response_headers->response_code();
}
UserInitiatedInfo CreateUserInitiatedInfo(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsRendererInitiated())
return UserInitiatedInfo::BrowserInitiated();
return UserInitiatedInfo::RenderInitiated(
navigation_handle->HasUserGesture(),
!navigation_handle->NavigationInputStart().is_null());
}
} // namespace
// static
void MetricsWebContentsObserver::RecordFeatureUsage(
content::RenderFrameHost* render_frame_host,
const mojom::PageLoadFeatures& new_features) {
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
MetricsWebContentsObserver* observer =
MetricsWebContentsObserver::FromWebContents(web_contents);
if (observer)
observer->OnBrowserFeatureUsage(render_frame_host, new_features);
}
MetricsWebContentsObserver::MetricsWebContentsObserver(
content::WebContents* web_contents,
std::unique_ptr<PageLoadMetricsEmbedderInterface> embedder_interface)
: content::WebContentsObserver(web_contents),
in_foreground_(web_contents->GetVisibility() !=
content::Visibility::HIDDEN),
embedder_interface_(std::move(embedder_interface)),
has_navigated_(false),
page_load_metrics_receiver_(web_contents, this) {
// Prerenders erroneously report that they are initially visible, so we
// manually override visibility state for prerender.
if (embedder_interface_->IsPrerender(web_contents))
in_foreground_ = false;
RegisterInputEventObserver(web_contents->GetRenderViewHost());
}
// static
MetricsWebContentsObserver* MetricsWebContentsObserver::CreateForWebContents(
content::WebContents* web_contents,
std::unique_ptr<PageLoadMetricsEmbedderInterface> embedder_interface) {
DCHECK(web_contents);
MetricsWebContentsObserver* metrics = FromWebContents(web_contents);
if (!metrics) {
metrics = new MetricsWebContentsObserver(web_contents,
std::move(embedder_interface));
web_contents->SetUserData(UserDataKey(), base::WrapUnique(metrics));
}
return metrics;
}
MetricsWebContentsObserver::~MetricsWebContentsObserver() {}
void MetricsWebContentsObserver::WebContentsWillSoonBeDestroyed() {
web_contents_will_soon_be_destroyed_ = true;
}
void MetricsWebContentsObserver::WebContentsDestroyed() {
// TODO(csharrison): Use a more user-initiated signal for CLOSE.
NotifyPageEndAllLoads(END_CLOSE, UserInitiatedInfo::NotUserInitiated());
// We tear down PageLoadTrackers in WebContentsDestroyed, rather than in the
// destructor, since |web_contents()| returns nullptr in the destructor, and
// PageLoadMetricsObservers can cause code to execute that wants to be able to
// access the current WebContents.
committed_load_ = nullptr;
provisional_loads_.clear();
aborted_provisional_loads_.clear();
for (auto& observer : testing_observers_)
observer.OnGoingAway();
}
void MetricsWebContentsObserver::RegisterInputEventObserver(
content::RenderViewHost* host) {
if (host != nullptr)
host->GetWidget()->AddInputEventObserver(this);
}
void MetricsWebContentsObserver::UnregisterInputEventObserver(
content::RenderViewHost* host) {
if (host != nullptr)
host->GetWidget()->RemoveInputEventObserver(this);
}
void MetricsWebContentsObserver::RenderViewHostChanged(
content::RenderViewHost* old_host,
content::RenderViewHost* new_host) {
UnregisterInputEventObserver(old_host);
RegisterInputEventObserver(new_host);
}
void MetricsWebContentsObserver::FrameDeleted(content::RenderFrameHost* rfh) {
if (committed_load_)
committed_load_->FrameDeleted(rfh);
}
void MetricsWebContentsObserver::MediaStartedPlaying(
const content::WebContentsObserver::MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
if (!id.render_frame_host->GetMainFrame()->IsCurrent()) {
// Ignore media that starts playing in a page that was navigated away
// from.
return;
}
if (committed_load_)
committed_load_->MediaStartedPlaying(video_type, id.render_frame_host);
}
void MetricsWebContentsObserver::WillStartNavigationRequest(
content::NavigationHandle* navigation_handle) {
// Same-document navigations should never go through
// WillStartNavigationRequest.
DCHECK(!navigation_handle->IsSameDocument());
if (!navigation_handle->IsInMainFrame())
return;
WillStartNavigationRequestImpl(navigation_handle);
has_navigated_ = true;
}
void MetricsWebContentsObserver::WillStartNavigationRequestImpl(
content::NavigationHandle* navigation_handle) {
UserInitiatedInfo user_initiated_info(
CreateUserInitiatedInfo(navigation_handle));
std::unique_ptr<PageLoadTracker> last_aborted =
NotifyAbortedProvisionalLoadsNewNavigation(navigation_handle,
user_initiated_info);
int chain_size_same_url = 0;
int chain_size = 0;
if (last_aborted) {
if (last_aborted->MatchesOriginalNavigation(navigation_handle)) {
chain_size_same_url = last_aborted->aborted_chain_size_same_url() + 1;
} else if (last_aborted->aborted_chain_size_same_url() > 0) {
LogAbortChainSameURLHistogram(
last_aborted->aborted_chain_size_same_url());
}
chain_size = last_aborted->aborted_chain_size() + 1;
}
if (!ShouldTrackMainFrameNavigation(navigation_handle))
return;
// Pass in the last committed url to the PageLoadTracker. If the MWCO has
// never observed a committed load, use the last committed url from this
// WebContent's opener. This is more accurate than using referrers due to
// referrer sanitizing and origin referrers. Note that this could potentially
// be inaccurate if the opener has since navigated.
content::RenderFrameHost* opener = web_contents()->GetOpener();
const GURL& opener_url = !has_navigated_ && opener
? opener->GetLastCommittedURL()
: GURL::EmptyGURL();
const GURL& currently_committed_url =
committed_load_ ? committed_load_->url() : opener_url;
// Passing raw pointers to observers_ and embedder_interface_ is safe because
// the MetricsWebContentsObserver owns them both list and they are torn down
// after the PageLoadTracker. The PageLoadTracker does not hold on to
// committed_load_ or navigation_handle beyond the scope of the constructor.
auto insertion_result = provisional_loads_.insert(std::make_pair(
navigation_handle,
std::make_unique<PageLoadTracker>(
in_foreground_, embedder_interface_.get(), currently_committed_url,
!has_navigated_, navigation_handle, user_initiated_info, chain_size,
chain_size_same_url)));
DCHECK(insertion_result.second)
<< "provisional_loads_ already contains NavigationHandle.";
for (auto& observer : testing_observers_)
observer.OnTrackerCreated(insertion_result.first->second.get());
}
void MetricsWebContentsObserver::WillProcessNavigationResponse(
content::NavigationHandle* navigation_handle) {
auto it = provisional_loads_.find(navigation_handle);
if (it == provisional_loads_.end())
return;
it->second->WillProcessNavigationResponse(navigation_handle);
}
PageLoadTracker* MetricsWebContentsObserver::GetTrackerOrNullForRequest(
const content::GlobalRequestID& request_id,
content::RenderFrameHost* render_frame_host_or_null,
network::mojom::RequestDestination request_destination,
base::TimeTicks creation_time) {
if (request_destination == network::mojom::RequestDestination::kDocument) {
DCHECK(request_id != content::GlobalRequestID());
// The main frame request can complete either before or after commit, so we
// look at both provisional loads and the committed load to find a
// PageLoadTracker with a matching request id. See https://goo.gl/6TzCYN for
// more details.
for (const auto& kv : provisional_loads_) {
PageLoadTracker* candidate = kv.second.get();
if (candidate->HasMatchingNavigationRequestID(request_id)) {
return candidate;
}
}
if (committed_load_ &&
committed_load_->HasMatchingNavigationRequestID(request_id)) {
return committed_load_.get();
}
} else {
// Non main frame resources are always associated with the currently
// committed load. If the resource request was started before this
// navigation then it should be ignored.
if (!committed_load_ || creation_time < committed_load_->navigation_start())
return nullptr;
// Sub-frame resources have a null RFH when browser-side navigation is
// enabled, so we can't perform the RFH check below for them.
//
// TODO(bmcquade): consider tracking GlobalRequestIDs for sub-frame
// navigations in each PageLoadTracker, and performing a lookup for
// sub-frames similar to the main-frame lookup above.
if (blink::IsRequestDestinationFrame(request_destination))
return committed_load_.get();
// This was originally a DCHECK but it fails when the document load happened
// after client certificate selection.
if (!render_frame_host_or_null)
return nullptr;
// There is a race here: a completed resource for the previously committed
// page can arrive after the new page has committed. In this case, we may
// attribute the resource to the wrong page load. We do our best to guard
// against this by verifying that the RFH for the resource matches the RFH
// for the currently committed load, however there are cases where the same
// RFH is used across page loads (same origin navigations, as well as some
// cross-origin render-initiated navigations).
//
// TODO(crbug.com/738577): use a DocumentId here instead, to eliminate this
// race.
if (render_frame_host_or_null->GetMainFrame()->IsCurrent()) {
return committed_load_.get();
}
}
return nullptr;
}
void MetricsWebContentsObserver::ResourceLoadComplete(
content::RenderFrameHost* render_frame_host,
const content::GlobalRequestID& request_id,
const blink::mojom::ResourceLoadInfo& resource_load_info) {
if (!resource_load_info.final_url.SchemeIsHTTPOrHTTPS())
return;
PageLoadTracker* tracker = GetTrackerOrNullForRequest(
request_id, render_frame_host, resource_load_info.request_destination,
resource_load_info.load_timing_info.request_start);
if (tracker) {
// TODO(crbug.com/721403): Fill in data reduction proxy fields when this is
// available in the network service.
// int original_content_length =
// was_cached ? 0
// : data_reduction_proxy::util::EstimateOriginalBodySize(
// request, lofi_decider);
int original_content_length = 0;
std::unique_ptr<data_reduction_proxy::DataReductionProxyData>
data_reduction_proxy_data;
const blink::mojom::CommonNetworkInfoPtr& network_info =
resource_load_info.network_info;
ExtraRequestCompleteInfo extra_request_complete_info(
url::Origin::Create(resource_load_info.final_url),
network_info->remote_endpoint.value(),
render_frame_host->GetFrameTreeNodeId(), resource_load_info.was_cached,
resource_load_info.raw_body_bytes, original_content_length,
std::move(data_reduction_proxy_data),
resource_load_info.request_destination, resource_load_info.net_error,
std::make_unique<net::LoadTimingInfo>(
resource_load_info.load_timing_info));
tracker->OnLoadedResource(extra_request_complete_info);
}
}
void MetricsWebContentsObserver::FrameReceivedFirstUserActivation(
content::RenderFrameHost* render_frame_host) {
if (committed_load_)
committed_load_->FrameReceivedFirstUserActivation(render_frame_host);
}
void MetricsWebContentsObserver::FrameDisplayStateChanged(
content::RenderFrameHost* render_frame_host,
bool is_display_none) {
if (committed_load_)
committed_load_->FrameDisplayStateChanged(render_frame_host,
is_display_none);
}
void MetricsWebContentsObserver::FrameSizeChanged(
content::RenderFrameHost* render_frame_host,
const gfx::Size& frame_size) {
if (committed_load_)
committed_load_->FrameSizeChanged(render_frame_host, frame_size);
}
void MetricsWebContentsObserver::OnCookiesRead(
const GURL& url,
const GURL& first_party_url,
const net::CookieList& cookie_list,
bool blocked_by_policy) {
if (committed_load_)
committed_load_->OnCookiesRead(url, first_party_url, cookie_list,
blocked_by_policy);
}
void MetricsWebContentsObserver::OnCookieChange(
const GURL& url,
const GURL& first_party_url,
const net::CanonicalCookie& cookie,
bool blocked_by_policy) {
if (committed_load_)
committed_load_->OnCookieChange(url, first_party_url, cookie,
blocked_by_policy);
}
void MetricsWebContentsObserver::OnStorageAccessed(const GURL& url,
const GURL& first_party_url,
bool blocked_by_policy,
StorageType storage_type) {
if (committed_load_)
committed_load_->OnStorageAccessed(url, first_party_url, blocked_by_policy,
storage_type);
}
const PageLoadMetricsObserverDelegate&
MetricsWebContentsObserver::GetDelegateForCommittedLoad() {
DCHECK(committed_load_);
return *committed_load_.get();
}
void MetricsWebContentsObserver::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
if (committed_load_)
committed_load_->ReadyToCommitNavigation(navigation_handle);
}
void MetricsWebContentsObserver::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame()) {
if (committed_load_ && navigation_handle->GetParentFrame() &&
navigation_handle->GetParentFrame()->GetMainFrame()->IsCurrent()) {
committed_load_->DidFinishSubFrameNavigation(navigation_handle);
committed_load_->metrics_update_dispatcher()->DidFinishSubFrameNavigation(
navigation_handle);
}
return;
}
// Not all navigations trigger the WillStartNavigationRequest callback (for
// example, navigations to about:blank). DidFinishNavigation is guaranteed to
// be called for every navigation, so we also update has_navigated_ here, to
// ensure it is set consistently for all navigations.
has_navigated_ = true;
std::unique_ptr<PageLoadTracker> navigation_handle_tracker(
std::move(provisional_loads_[navigation_handle]));
provisional_loads_.erase(navigation_handle);
// Ignore same-document navigations.
if (navigation_handle->HasCommitted() &&
navigation_handle->IsSameDocument()) {
if (navigation_handle_tracker)
navigation_handle_tracker->StopTracking();
if (committed_load_)
committed_load_->DidCommitSameDocumentNavigation(navigation_handle);
return;
}
// Ignore internally generated aborts for navigations with HTTP responses that
// don't commit, such as HTTP 204 responses and downloads.
if (!navigation_handle->HasCommitted() &&
navigation_handle->GetNetErrorCode() == net::ERR_ABORTED &&
navigation_handle->GetResponseHeaders()) {
if (navigation_handle_tracker) {
navigation_handle_tracker->DidInternalNavigationAbort(navigation_handle);
navigation_handle_tracker->StopTracking();
}
return;
}
if (navigation_handle->HasCommitted()) {
// A new navigation is committing, so finalize and destroy the tracker for
// the currently committed navigation.
FinalizeCurrentlyCommittedLoad(navigation_handle,
navigation_handle_tracker.get());
committed_load_.reset();
}
if (!navigation_handle_tracker)
return;
if (!ShouldTrackMainFrameNavigation(navigation_handle)) {
navigation_handle_tracker->StopTracking();
return;
}
if (navigation_handle->HasCommitted()) {
HandleCommittedNavigationForTrackedLoad(
navigation_handle, std::move(navigation_handle_tracker));
} else {
HandleFailedNavigationForTrackedLoad(navigation_handle,
std::move(navigation_handle_tracker));
}
}
// Handle a pre-commit error. Navigations that result in an error page will be
// ignored.
void MetricsWebContentsObserver::HandleFailedNavigationForTrackedLoad(
content::NavigationHandle* navigation_handle,
std::unique_ptr<PageLoadTracker> tracker) {
const base::TimeTicks now = base::TimeTicks::Now();
tracker->FailedProvisionalLoad(navigation_handle, now);
const net::Error error = navigation_handle->GetNetErrorCode();
// net::OK: This case occurs when the NavigationHandle finishes and reports
// !HasCommitted(), but reports no net::Error. This represents the navigation
// being stopped by the user before it was ready to commit.
// net::ERR_ABORTED: An aborted provisional load has error net::ERR_ABORTED.
const bool is_aborted_provisional_load =
error == net::OK || error == net::ERR_ABORTED;
// If is_aborted_provisional_load, the page end reason is not yet known, and
// will be updated as additional information is available from subsequent
// navigations.
tracker->NotifyPageEnd(
is_aborted_provisional_load ? END_OTHER : END_PROVISIONAL_LOAD_FAILED,
UserInitiatedInfo::NotUserInitiated(), now, true);
if (is_aborted_provisional_load)
aborted_provisional_loads_.push_back(std::move(tracker));
}
void MetricsWebContentsObserver::HandleCommittedNavigationForTrackedLoad(
content::NavigationHandle* navigation_handle,
std::unique_ptr<PageLoadTracker> tracker) {
committed_load_ = std::move(tracker);
committed_load_->Commit(navigation_handle);
DCHECK(committed_load_->did_commit());
for (auto& observer : testing_observers_)
observer.OnCommit(committed_load_.get());
}
void MetricsWebContentsObserver::FinalizeCurrentlyCommittedLoad(
content::NavigationHandle* newly_committed_navigation,
PageLoadTracker* newly_committed_navigation_tracker) {
UserInitiatedInfo user_initiated_info =
newly_committed_navigation_tracker
? newly_committed_navigation_tracker->user_initiated_info()
: CreateUserInitiatedInfo(newly_committed_navigation);
// Notify other loads that they may have been aborted by this committed
// load. is_certainly_browser_timestamp is set to false because
// NavigationStart() could be set in either the renderer or browser process.
NotifyPageEndAllLoadsWithTimestamp(
EndReasonForPageTransition(
newly_committed_navigation->GetPageTransition()),
user_initiated_info, newly_committed_navigation->NavigationStart(),
/*is_certainly_browser_timestamp=*/false);
if (committed_load_) {
bool is_non_user_initiated_client_redirect =
!IsNavigationUserInitiated(newly_committed_navigation) &&
(newly_committed_navigation->GetPageTransition() &
ui::PAGE_TRANSITION_CLIENT_REDIRECT) != 0;
if (is_non_user_initiated_client_redirect) {
committed_load_->NotifyClientRedirectTo(newly_committed_navigation);
}
}
}
void MetricsWebContentsObserver::NavigationStopped() {
// TODO(csharrison): Use a more user-initiated signal for STOP.
NotifyPageEndAllLoads(END_STOP, UserInitiatedInfo::NotUserInitiated());
}
void MetricsWebContentsObserver::OnInputEvent(
const blink::WebInputEvent& event) {
// Ignore browser navigation or reload which comes with type Undefined.
if (event.GetType() == blink::WebInputEvent::Type::kUndefined)
return;
if (committed_load_)
committed_load_->OnInputEvent(event);
}
void MetricsWebContentsObserver::FlushMetricsOnAppEnterBackground() {
// Note that, while a call to FlushMetricsOnAppEnterBackground usually
// indicates that the app is about to be backgrounded, there are cases where
// the app may not end up getting backgrounded. Thus, we should not assume
// anything about foreground / background state of the associated tab as part
// of this method call.
if (committed_load_)
committed_load_->FlushMetricsOnAppEnterBackground();
for (const auto& kv : provisional_loads_) {
kv.second->FlushMetricsOnAppEnterBackground();
}
for (const auto& tracker : aborted_provisional_loads_) {
tracker->FlushMetricsOnAppEnterBackground();
}
}
void MetricsWebContentsObserver::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame())
return;
auto it = provisional_loads_.find(navigation_handle);
if (it == provisional_loads_.end())
return;
it->second->Redirect(navigation_handle);
}
void MetricsWebContentsObserver::OnVisibilityChanged(
content::Visibility visibility) {
if (web_contents_will_soon_be_destroyed_)
return;
bool was_in_foreground = in_foreground_;
in_foreground_ = visibility == content::Visibility::VISIBLE;
if (in_foreground_ == was_in_foreground)
return;
if (in_foreground_) {
if (committed_load_)
committed_load_->PageShown();
for (const auto& kv : provisional_loads_) {
kv.second->PageShown();
}
} else {
if (committed_load_)
committed_load_->PageHidden();
for (const auto& kv : provisional_loads_) {
kv.second->PageHidden();
}
}
}
// This will occur when the process for the main RenderFrameHost exits, either
// normally or from a crash. We eagerly log data from the last committed load if
// we have one.
void MetricsWebContentsObserver::RenderProcessGone(
base::TerminationStatus status) {
// Other code paths will be run for normal renderer shutdown. Note that we
// sometimes get the STILL_RUNNING value on fast shutdown.
if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
status == base::TERMINATION_STATUS_STILL_RUNNING) {
return;
}
// RenderProcessGone is associated with the render frame host for the
// currently committed load. We don't know if the pending navs or aborted
// pending navs are associated w/ the render process that died, so we can't be
// sure the info should propagate to them.
if (committed_load_) {
committed_load_->NotifyPageEnd(END_RENDER_PROCESS_GONE,
UserInitiatedInfo::NotUserInitiated(),
base::TimeTicks::Now(), true);
}
// If this is a crash, eagerly log the aborted provisional loads and the
// committed load. |provisional_loads_| don't need to be destroyed here
// because their lifetime is tied to the NavigationHandle.
committed_load_.reset();
aborted_provisional_loads_.clear();
}
void MetricsWebContentsObserver::NotifyPageEndAllLoads(
PageEndReason page_end_reason,
UserInitiatedInfo user_initiated_info) {
NotifyPageEndAllLoadsWithTimestamp(page_end_reason, user_initiated_info,
base::TimeTicks::Now(),
/*is_certainly_browser_timestamp=*/true);
}
void MetricsWebContentsObserver::NotifyPageEndAllLoadsWithTimestamp(
PageEndReason page_end_reason,
UserInitiatedInfo user_initiated_info,
base::TimeTicks timestamp,
bool is_certainly_browser_timestamp) {
if (committed_load_) {
committed_load_->NotifyPageEnd(page_end_reason, user_initiated_info,
timestamp, is_certainly_browser_timestamp);
}
for (const auto& kv : provisional_loads_) {
kv.second->NotifyPageEnd(page_end_reason, user_initiated_info, timestamp,
is_certainly_browser_timestamp);
}
for (const auto& tracker : aborted_provisional_loads_) {
if (tracker->IsLikelyProvisionalAbort(timestamp)) {
tracker->UpdatePageEnd(page_end_reason, user_initiated_info, timestamp,
is_certainly_browser_timestamp);
}
}
aborted_provisional_loads_.clear();
}
std::unique_ptr<PageLoadTracker>
MetricsWebContentsObserver::NotifyAbortedProvisionalLoadsNewNavigation(
content::NavigationHandle* new_navigation,
UserInitiatedInfo user_initiated_info) {
// If there are multiple aborted loads that can be attributed to this one,
// just count the latest one for simplicity. Other loads will fall into the
// OTHER bucket, though there shouldn't be very many.
if (aborted_provisional_loads_.empty())
return nullptr;
if (aborted_provisional_loads_.size() > 1)
RecordInternalError(ERR_NAVIGATION_SIGNALS_MULIPLE_ABORTED_LOADS);
std::unique_ptr<PageLoadTracker> last_aborted_load =
std::move(aborted_provisional_loads_.back());
aborted_provisional_loads_.pop_back();
base::TimeTicks timestamp = new_navigation->NavigationStart();
if (last_aborted_load->IsLikelyProvisionalAbort(timestamp)) {
last_aborted_load->UpdatePageEnd(
EndReasonForPageTransition(new_navigation->GetPageTransition()),
user_initiated_info, timestamp, false);
}
aborted_provisional_loads_.clear();
return last_aborted_load;
}
void MetricsWebContentsObserver::OnTimingUpdated(
content::RenderFrameHost* render_frame_host,
mojom::PageLoadTimingPtr timing,
mojom::FrameMetadataPtr metadata,
mojom::PageLoadFeaturesPtr new_features,
const std::vector<mojom::ResourceDataUpdatePtr>& resources,
mojom::FrameRenderDataUpdatePtr render_data,
mojom::CpuTimingPtr cpu_timing,
mojom::DeferredResourceCountsPtr new_deferred_resource_data,
mojom::InputTimingPtr input_timing_delta) {
// We may receive notifications from frames that have been navigated away
// from. We simply ignore them.
// TODO(crbug.com/1061060): We should not ignore page timings if the page is
// in bfcache.
if (!render_frame_host->GetMainFrame()->IsCurrent()) {
RecordInternalError(ERR_IPC_FROM_WRONG_FRAME);
return;
}
const bool is_main_frame = (render_frame_host->GetParent() == nullptr);
if (is_main_frame) {
// While timings arriving for the wrong frame are expected, we do not expect
// any of the errors below for main frames. Thus, we track occurrences of
// all errors below, rather than returning early after encountering an
// error.
// TODO(crbug/1061090): Update page load metrics IPC validation to ues
// mojo::ReportBadMessage.
bool error = false;
if (!committed_load_) {
RecordInternalError(ERR_IPC_WITH_NO_RELEVANT_LOAD);
error = true;
}
if (!web_contents()->GetLastCommittedURL().SchemeIsHTTPOrHTTPS()) {
RecordInternalError(ERR_IPC_FROM_BAD_URL_SCHEME);
error = true;
}
if (error)
return;
} else if (!committed_load_) {
RecordInternalError(ERR_SUBFRAME_IPC_WITH_NO_RELEVANT_LOAD);
}
if (committed_load_) {
committed_load_->metrics_update_dispatcher()->UpdateMetrics(
render_frame_host, std::move(timing), std::move(metadata),
std::move(new_features), resources, std::move(render_data),
std::move(cpu_timing), std::move(new_deferred_resource_data),
std::move(input_timing_delta));
}
}
void MetricsWebContentsObserver::UpdateTiming(
mojom::PageLoadTimingPtr timing,
mojom::FrameMetadataPtr metadata,
mojom::PageLoadFeaturesPtr new_features,
std::vector<mojom::ResourceDataUpdatePtr> resources,
mojom::FrameRenderDataUpdatePtr render_data,
mojom::CpuTimingPtr cpu_timing,
mojom::DeferredResourceCountsPtr new_deferred_resource_data,
mojom::InputTimingPtr input_timing_delta) {
content::RenderFrameHost* render_frame_host =
page_load_metrics_receiver_.GetCurrentTargetFrame();
OnTimingUpdated(render_frame_host, std::move(timing), std::move(metadata),
std::move(new_features), resources, std::move(render_data),
std::move(cpu_timing), std::move(new_deferred_resource_data),
std::move(input_timing_delta));
}
bool MetricsWebContentsObserver::ShouldTrackMainFrameNavigation(
content::NavigationHandle* navigation_handle) const {
DCHECK(navigation_handle->IsInMainFrame());
DCHECK(!navigation_handle->HasCommitted() ||
!navigation_handle->IsSameDocument());
// If there is an outer WebContents, then this WebContents is embedded into
// another one (it is either a portal or a Chrome App <webview>). Ignore these
// navigations for now.
if (web_contents()->GetOuterWebContents())
return false;
// Ignore non-HTTP schemes (e.g. chrome://).
if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS())
return false;
// Ignore NTP loads.
if (embedder_interface_->IsNewTabPageUrl(navigation_handle->GetURL()))
return false;
if (navigation_handle->HasCommitted()) {
// Ignore Chrome error pages (e.g. No Internet connection).
if (navigation_handle->IsErrorPage())
return false;
// Ignore network error pages (e.g. 4xx, 5xx).
int http_status_code = GetHttpStatusCode(navigation_handle);
if (http_status_code > 0 &&
(http_status_code < 200 || http_status_code >= 400))
return false;
}
// TODO(crbug.com/1014174): Ignore back-forward cached navigations for now.
if (navigation_handle->IsServedFromBackForwardCache())
return false;
return true;
}
void MetricsWebContentsObserver::OnBrowserFeatureUsage(
content::RenderFrameHost* render_frame_host,
const mojom::PageLoadFeatures& new_features) {
// Since this call is coming directly from the browser, it should not pass us
// data from frames that have already been navigated away from.
DCHECK(render_frame_host->GetMainFrame()->IsCurrent());
if (!committed_load_) {
RecordInternalError(ERR_BROWSER_USAGE_WITH_NO_RELEVANT_LOAD);
return;
}
committed_load_->metrics_update_dispatcher()->UpdateFeatures(
render_frame_host, new_features);
}
void MetricsWebContentsObserver::AddTestingObserver(TestingObserver* observer) {
if (!testing_observers_.HasObserver(observer))
testing_observers_.AddObserver(observer);
}
void MetricsWebContentsObserver::RemoveTestingObserver(
TestingObserver* observer) {
testing_observers_.RemoveObserver(observer);
}
MetricsWebContentsObserver::TestingObserver::TestingObserver(
content::WebContents* web_contents)
: observer_(page_load_metrics::MetricsWebContentsObserver::FromWebContents(
web_contents)) {
observer_->AddTestingObserver(this);
}
MetricsWebContentsObserver::TestingObserver::~TestingObserver() {
if (observer_) {
observer_->RemoveTestingObserver(this);
observer_ = nullptr;
}
}
void MetricsWebContentsObserver::TestingObserver::OnGoingAway() {
observer_ = nullptr;
}
const PageLoadMetricsObserverDelegate&
MetricsWebContentsObserver::TestingObserver::GetDelegateForCommittedLoad() {
return observer_->GetDelegateForCommittedLoad();
}
void MetricsWebContentsObserver::BroadcastEventToObservers(
const void* const event_key) {
if (committed_load_)
committed_load_->BroadcastEventToObservers(event_key);
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(MetricsWebContentsObserver)
} // namespace page_load_metrics
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
54f1ef2b37b264555d964a42601ffec5009971fb
|
26d039bffb2ba5b878184e75f7a1a55accba8229
|
/Logger.hpp
|
2c30067d2c2e96b4cfdf26851350be6b6edd605f
|
[] |
no_license
|
taylorconor/bittrader
|
56ff46997288feddb3e80fcd23bf4d8501002bf7
|
fb1d2a5ffbaec47d80e57f9985e5aa962e534c93
|
refs/heads/master
| 2021-01-15T12:19:31.800683
| 2016-03-11T10:14:03
| 2016-03-11T10:14:03
| 47,073,634
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 521
|
hpp
|
//
// Logger.hpp
// bittrader
//
// Created by Conor Taylor on 14/11/2015.
// Copyright © 2015 Conor Taylor. All rights reserved.
//
#ifndef Logger_hpp
#define Logger_hpp
#include <iostream>
#include <sstream>
#include "time.h"
using namespace std;
class Logger {
private:
static Logger *_instance;
Logger();
string timestr(int ts);
public:
static Logger *instance();
void log(string s);
void log_ts(string s);
void log_tick(int ts, double ask, double moving_average);
};
#endif /* Logger_hpp */
|
[
"taylorconor@me.com"
] |
taylorconor@me.com
|
58d49d145753a209805b7d5afa1fd18fb5135bfc
|
a9c12a1da0794eaf9a1d1f37ab5c404e3b95e4ec
|
/CTPServer/CTPPositionUpdated.cpp
|
3e2e55bdc51df8ed7415aed8e61641b076372a98
|
[] |
no_license
|
shzdtech/FutureXPlatform
|
37d395511d603a9e92191f55b8f8a6d60e4095d6
|
734cfc3c3d2026d60361874001fc20f00e8bb038
|
refs/heads/master
| 2021-03-30T17:49:22.010954
| 2018-06-19T13:21:53
| 2018-06-19T13:21:53
| 56,828,437
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,731
|
cpp
|
#include "CTPPositionUpdated.h"
#include "CTPUtility.h"
#include "CTPMapping.h"
#include "CTPConstant.h"
#include "../message/MessageUtility.h"
#include "CTPTradeWorkerProcessor.h"
#include "CTPWorkerProcessorID.h"
#include "../litelogger/LiteLogger.h"
#include "../dataobject/OrderDO.h"
#include "../message/DefMessageID.h"
#include "CTPAPISwitch.h"
dataobj_ptr CTPPositionUpdated::HandleResponse(const uint32_t serialId, const param_vector& rawRespParams, IRawAPI* rawAPI, const IMessageProcessor_Ptr& msgProcessor, const IMessageSession_Ptr& session)
{
if (auto pData = (CThostFtdcInvestorPositionField*)rawRespParams[0])
{
if (auto pWorkerProc = MessageUtility::WorkerProcessorPtr<CTPTradeWorkerProcessorBase>(msgProcessor))
{
auto& userId = session->getUserInfo().getUserId();
auto position_ptr = CTPUtility::ParseRawPosition(pData, userId);
LOG_DEBUG << pData->InstrumentID << ',' << pData->PositionDate << ',' << pData->PosiDirection;
pWorkerProc->UpdateSysYdPosition(userId, position_ptr);
if (!pWorkerProc->IsLoadPositionFromDB())
{
if (position_ptr->ExchangeID() == EXCHANGE_SHFE)
{
if (pData->PositionDate == THOST_FTDC_PSD_Today)
{
position_ptr = pWorkerProc->GetUserPositionContext()->UpsertPosition(userId, *position_ptr, false, false);
}
else
{
position_ptr = pWorkerProc->GetUserPositionContext()->UpsertPosition(userId, *position_ptr, true, false);
}
}
else
{
position_ptr = pWorkerProc->GetUserPositionContext()->UpsertPosition(userId, *position_ptr, false, true);
}
if (position_ptr)
pWorkerProc->DispatchUserMessage(MSG_ID_POSITION_UPDATED, 0, userId, position_ptr);
}
}
}
return nullptr;
}
|
[
"rainmilk@gmail.com"
] |
rainmilk@gmail.com
|
acdb4f552e8ac8a7e626dafb571d1ba656226cfc
|
8f608437957f7c9eb03f0ee00457e10282059ec8
|
/Codeforces/617B.cpp
|
7ef8cb998afd8cf9735fc65027a38ae9fe1137d6
|
[] |
no_license
|
npkhang99/Competitive-Programming
|
0ddf3cfcfc13825f7fadaf5b53fdef16ca77522f
|
1a5e3799e5855996aa56688680765511b0de7281
|
refs/heads/master
| 2023-06-28T15:17:44.489901
| 2021-07-30T05:31:15
| 2021-07-30T05:31:15
| 66,803,586
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 618
|
cpp
|
#include <iostream>
#include <stdio.h>
using namespace std;
const int N=109;
#define long long long
int n, a[N], d[N];
void xuly(){
int d[N], k=0, vt=1;
for(int i=1; i<=n; i++)
if(a[i]==1){
int vt=i; break;
}
for(int i=vt; i<=n; i++)
if(a[i]==1) d[++k]=1;
else d[k]++;
long c=1;
for(int i=1; i<=k-1; i++){
c*=d[i];
}
cout<< c<< endl;
}
int main(){
scanf("%d", &n);
int c=0;
for(int i=1; i<=n; i++){
scanf("%d", &a[i]);
if(a[i]==1) c++;
}
if(c>1) xuly();
else printf("%d\n",c);
return 0;
}
|
[
"curoa99@gmail.com"
] |
curoa99@gmail.com
|
86e939cecbb1fec89cf05b1288a6c92bfad50a2a
|
52507f7928ba44b7266eddf0f1a9bf6fae7322a4
|
/SDK/BP_TextInputDialog_classes.h
|
4e1200925016ac4dd20a23c2c74d2086ed0a7b18
|
[] |
no_license
|
LuaFan2/mordhau-sdk
|
7268c9c65745b7af511429cfd3bf16aa109bc20c
|
ab10ad70bc80512e51a0319c2f9b5effddd47249
|
refs/heads/master
| 2022-11-30T08:14:30.825803
| 2020-08-13T16:31:27
| 2020-08-13T16:31:27
| 287,329,560
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,550
|
h
|
#pragma once
// Name: Mordhau, Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass BP_TextInputDialog.BP_TextInputDialog_C
// 0x0080 (0x0288 - 0x0208)
class UBP_TextInputDialog_C : public UMordhauDialog
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0208(0x0008) (Transient, DuplicateTransient)
class UBP_TwoButtonDialog_C* BP_TwoButtonDialog; // 0x0210(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UEditableTextBox* NormalTextBox; // 0x0218(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UEditableTextBox* PasswordTextBox; // 0x0220(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
struct FText HintText; // 0x0228(0x0018) (Edit, BlueprintVisible)
struct FScriptMulticastDelegate LeftButtonClicked; // 0x0240(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable)
struct FScriptMulticastDelegate RightButtonClicked; // 0x0250(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable)
bool bIsPassword; // 0x0260(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x7]; // 0x0261(0x0007) MISSED OFFSET
struct FScriptMulticastDelegate TextCommitted; // 0x0268(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable)
struct FScriptMulticastDelegate TextChanged; // 0x0278(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass BP_TextInputDialog.BP_TextInputDialog_C");
return ptr;
}
void SetEnteredText(const struct FText& EnteredText);
void GetEnteredText(struct FText* Text);
void SetTitleText(const struct FText& Title);
void SetRightButtonText(const struct FText& Text);
void SetLeftButtonText(const struct FText& Text);
struct FText GetHintText();
void BndEvt__PasswordTextbox_K2Node_ComponentBoundEvent_23_OnEditableTextBoxCommittedEvent__DelegateSignature(const struct FText& Text, TEnumAsByte<ETextCommit> CommitMethod);
void BndEvt__BP_TwoButtonDialog_K2Node_ComponentBoundEvent_183_LeftButtonClicked__DelegateSignature();
void BndEvt__BP_TwoButtonDialog_K2Node_ComponentBoundEvent_187_RightButtonClicked__DelegateSignature();
void Show();
void Hide();
void BndEvt__PasswordTextBox_K2Node_ComponentBoundEvent_7_OnEditableTextBoxCommittedEvent__DelegateSignature(const struct FText& Text, TEnumAsByte<ETextCommit> CommitMethod);
void BndEvt__NormalTextBox_K2Node_ComponentBoundEvent_19_OnEditableTextBoxChangedEvent__DelegateSignature(const struct FText& Text);
void BndEvt__PasswordTextBox_K2Node_ComponentBoundEvent_20_OnEditableTextBoxChangedEvent__DelegateSignature(const struct FText& Text);
void ExecuteUbergraph_BP_TextInputDialog(int EntryPoint);
void TextChanged__DelegateSignature(const struct FText& Text);
void TextCommitted__DelegateSignature(const struct FText& Text, TEnumAsByte<ETextCommit> Commit_Method);
void RightButtonClicked__DelegateSignature();
void LeftButtonClicked__DelegateSignature();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"51294434+LuaFan2@users.noreply.github.com"
] |
51294434+LuaFan2@users.noreply.github.com
|
17a68e715d1d16fec3078399b1b59f9b2ca160d3
|
8b3d9d31b9fc91f92d823b373eebed85b0216e6d
|
/sketches/synths/polyphonic-guitar-synth/polyphonic-guitar-synth.ino
|
2776279993a9c4b069597a0e60bf55554aa690eb
|
[
"MIT"
] |
permissive
|
runjumplabs/dreammaker_fx_sketches
|
ede710d3d43be33d60231d38590a57135f0d5c05
|
76c6ad5d7b0c1369a60950896fed5f2485b0d50e
|
refs/heads/master
| 2020-12-22T12:39:19.295525
| 2020-02-21T01:42:56
| 2020-02-21T01:42:56
| 236,784,207
| 0
| 1
|
MIT
| 2020-09-09T01:26:46
| 2020-01-28T16:41:07
|
C++
|
UTF-8
|
C++
| false
| false
| 3,620
|
ino
|
/******************************************************************************
* DreamMaker FX / www.dreammakerfx.com
*****************************************************************************/
/*
Effect name: Polyphonic guitar synth pedal
Effect description: This is a polyphonic guitar synth meaning that it tracks
multiple strings. It uses an FM synth engine along with ADSR envelope generator
and an output filter. The pedal is configured by default to use a triangle
(OSC_TRIANGLE) wave that is modulated with a sine wave (OSC_SINE). However, lots
of interesting sounds can be created by swapping these out with out types of oscillators
(e.g. OSC_SQUARE, OSC_RAMP_POS, OSC_RAMP_NEG, OSC_RANDOM, etc).
Left pot label: FM mod depth
Left pot function: The depth of the FM mod in the synthesizer
Center pot label: Attack time
Center pot function: The attack time of the synth sound (i.e. how long it takes
to ramp to full volume when you play a new string)
Right pot label: Modulation frequency
Right pot function: The frequency of the FM modulator ranging from 0.25 x the note played
to 4.25x.
Left footswitch label: Bypass
Left footswitch function: Bypasses the effect
Right footswitch label:
Right footswitch function: describe right footswitch function
Youtube Url:
Soundcloud Url: https://soundcloud.com/dreammakerfx/polyphonic-synth-guitar-effect-on-dreammaker-fx
Created by: DreamMaker
DreamMakerFx package version: 1.5.3
Sketch version: 1.0
*/
#include <dreammakerfx.h>
// Add your fx module declarations here
fx_instrument_synth synth(OSC_TRIANGLE, // Primary oscillator
OSC_RAMP_NEG, // FM mod oscillator
0.1, // FM mod depth
1.0, // Freq ratio (ratio of instrument frequency to synth frequency (1.0 = same)
2.0, // FM mod frequency ratio (1.0 = same frequency as primary oscillator)
250.0, // Attack time in milliseconds
3.0, // Filter resonance
0.6); // Filter response (0.0 to 1.0)
void setup() {
// put your setup code here, to run once:
// Initialize the pedal!
pedal.init();
// Route audio through effects from pedal.instr_in to pedal.amp_out
pedal.route_audio(synth.output, pedal.amp_out);
// Optionally use a bypass switch FOOTSWITCH_LEFT or FOOTSWITCH_RIGHT
pedal.add_bypass_button(FOOTSWITCH_LEFT);
if (true) {
pedal.print_instance_stack();
pedal.print_routing_table();
pedal.print_param_tables();
}
// Optionally use a tap tempo / delay switch
// Can also be FOOTSWITCH_LEFT or FOOTSWITCH_RIGHT but different than
// the bypass switch
// pedal.add_tap_interval_button(FOOTSWITCH_RIGHT, true);
// Run this effect
pedal.run();
}
void loop() {
// put your main code here, to run repeatedly:
// Left pot control
if (pedal.pot_left.has_changed()) {
// Left pot value is: pedal.pot_left.val
synth.set_fm_mod_depth(pedal.pot_left.val);
}
// Center pot control
if (pedal.pot_center.has_changed()) {
// Center pot value is: pedal.pot_center.val
synth.set_attack_ms(25.0 + pedal.pot_center.val*975.0);
}
// Right pot set control
if (pedal.pot_right.has_changed()) {
// Right pot value is: pedal.pot_right.val
float x = 0.25 + round(pedal.pot_right.val * 16.0)*0.25;
synth.set_fm_mod_ratio(x);
}
// Run pedal service to take care of stuff
pedal.service();
}
|
[
"dan@runjumplabs.com"
] |
dan@runjumplabs.com
|
3823170ca2526b7b1618b236d6bca0edf090a2d9
|
3e69b159d352a57a48bc483cb8ca802b49679d65
|
/tags/release-2005-10-27/pcbnew/netlist.cpp
|
7707b586004638238f618260d1327606a22517e2
|
[] |
no_license
|
BackupTheBerlios/kicad-svn
|
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
|
4c97bbde4b1b12ec5616a57c17298c77a9790398
|
refs/heads/master
| 2021-01-01T19:38:40.000652
| 2006-06-19T20:01:24
| 2006-06-19T20:01:24
| 40,799,911
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 31,012
|
cpp
|
/************************************/
/* PCBNEW: traitement des netlistes */
/************************************/
/* Fichier NETLIST.CPP */
/*
Fonction de lecture de la netliste pour:
- Chargement modules et nouvelles connexions
- Test des modules (modules manquants ou en trop
- Recalcul du chevelu
Remarque importante:
Lors de la lecture de la netliste pour Chargement modules
et nouvelles connexions, l'identification des modules peut se faire selon
2 criteres:
- la reference (U2, R5 ..): c'est le mode normal
- le Time Stamp (Signature Temporelle), a utiliser apres reannotation
d'un schema, donc apres modification des references sans pourtant
avoir reellement modifie le schema
*/
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "pcbnew.h"
#include "autorout.h"
#include "protos.h"
#define TESTONLY 1 /* ctes utilisees lors de l'appel a */
#define READMODULE 0 /* ReadNetModuleORCADPCB */
/* Structures locales */
class MODULEtoLOAD : public EDA_BaseStruct
{
public:
wxString m_LibName;
wxString m_CmpName;
public:
MODULEtoLOAD(const wxString & libname, const wxString & cmpname, int timestamp);
~MODULEtoLOAD(void){};
MODULEtoLOAD * Next(void) { return (MODULEtoLOAD *) Pnext; }
};
/* Fonctions locales : */
static void SortListModulesToLoadByLibname(int NbModules);
/* Variables locales */
static int s_NbNewModules;
static MODULEtoLOAD * s_ModuleToLoad_List;
FILE * source;
static bool ChangeExistantModule;
static bool DisplayWarning = TRUE;
static int DisplayWarningCount ;
/*****************************/
/* class WinEDA_NetlistFrame */
/*****************************/
enum id_netlist_functions
{
ID_READ_NETLIST_FILE = 1900,
ID_TEST_NETLIST,
ID_CLOSE_NETLIST,
ID_COMPILE_RATSNEST,
ID_OPEN_NELIST
};
class WinEDA_NetlistFrame: public wxDialog
{
private:
WinEDA_PcbFrame * m_Parent;
wxDC * m_DC;
wxRadioBox * m_Select_By_Timestamp;
wxRadioBox * m_DeleteBadTracks;
wxRadioBox * m_ChangeExistantModuleCtrl;
wxCheckBox * m_DisplayWarningCtrl;
wxTextCtrl * m_MessageWindow;
public:
// Constructor and destructor
WinEDA_NetlistFrame(WinEDA_PcbFrame *parent, wxDC * DC, const wxPoint & pos);
~WinEDA_NetlistFrame(void)
{
}
private:
void OnQuit(wxCommandEvent& event);
void ReadPcbNetlist(wxCommandEvent& event);
void Set_NetlisteName(wxCommandEvent& event);
bool OpenNetlistFile(wxCommandEvent& event);
int BuildListeNetModules(wxCommandEvent& event, char * BufName);
void ModulesControle(wxCommandEvent& event);
void RecompileRatsnest(wxCommandEvent& event);
int ReadListeModules(const char * RefCmp, int TimeStamp, char * NameModule);
int SetPadNetName( char * Line, MODULE * Module);
MODULE * ReadNetModule( char * Text,
int * UseFichCmp, int TstOnly);
void AddToList(const char * NameLibCmp, const char * NameCmp,int TimeStamp );
void LoadListeModules(wxDC *DC);
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(WinEDA_NetlistFrame, wxDialog)
EVT_BUTTON(ID_READ_NETLIST_FILE, WinEDA_NetlistFrame::ReadPcbNetlist)
EVT_BUTTON(ID_CLOSE_NETLIST, WinEDA_NetlistFrame::OnQuit)
EVT_BUTTON(ID_OPEN_NELIST, WinEDA_NetlistFrame::Set_NetlisteName)
EVT_BUTTON(ID_TEST_NETLIST, WinEDA_NetlistFrame::ModulesControle)
EVT_BUTTON(ID_COMPILE_RATSNEST, WinEDA_NetlistFrame::RecompileRatsnest)
END_EVENT_TABLE()
/*************************************************************************/
void WinEDA_PcbFrame::InstallNetlistFrame( wxDC * DC, const wxPoint & pos)
/*************************************************************************/
{
WinEDA_NetlistFrame * frame = new WinEDA_NetlistFrame(this, DC, pos);
frame->ShowModal(); frame->Destroy();
}
/******************************************************************/
WinEDA_NetlistFrame::WinEDA_NetlistFrame(WinEDA_PcbFrame *parent,
wxDC * DC, const wxPoint & framepos):
wxDialog(parent, -1, "", framepos, wxSize(-1, -1),
DIALOG_STYLE)
/******************************************************************/
{
wxPoint pos;
wxString number;
wxString title;
wxButton * Button;
m_Parent = parent;
SetFont(*g_DialogFont);
m_DC = DC;
Centre();
/* Mise a jour du Nom du fichier NETLISTE correspondant */
NetNameBuffer = m_Parent->m_CurrentScreen->m_FileName;
ChangeFileNameExt(NetNameBuffer, NetExtBuffer);
title = _("Netlist: ") + NetNameBuffer;
SetTitle(title);
/* Creation des boutons de commande */
pos.x = 170; pos.y = 10;
Button = new wxButton(this, ID_OPEN_NELIST,
_("Select"), pos);
Button->SetForegroundColour(*wxRED);
pos.y += Button->GetDefaultSize().y + 10;
Button = new wxButton(this, ID_READ_NETLIST_FILE,
_("Read"), pos);
Button->SetForegroundColour(wxColor(0,80,0) );
pos.y += Button->GetDefaultSize().y + 10;
Button = new wxButton(this, ID_TEST_NETLIST,
_("Module Test"), pos);
Button->SetForegroundColour(wxColor(0,80,80) );
pos.y += Button->GetDefaultSize().y + 10;
Button = new wxButton(this, ID_COMPILE_RATSNEST,
_("Compile"), pos);
Button->SetForegroundColour(wxColor(0,0,80) );
pos.y += Button->GetDefaultSize().y + 10;
Button = new wxButton(this, ID_CLOSE_NETLIST,
_("Close"), pos);
Button->SetForegroundColour(*wxBLUE);
// Options:
wxString opt_select[2] = { _("Reference"), _("Timestamp") };
pos.x = 15; pos.y = 10;
m_Select_By_Timestamp = new wxRadioBox( this, -1, _("Module Selection:"),
pos, wxDefaultSize, 2, opt_select, 1);
wxString track_select[2] = { _("Keep"), _("Delete") };
int x, y;
m_Select_By_Timestamp->GetSize(&x, &y);
pos.y += 5 + y;
m_DeleteBadTracks = new wxRadioBox(this, -1, _("Bad Tracks Deletion:"),
pos, wxDefaultSize, 2, track_select, 1);
m_DeleteBadTracks->GetSize(&x, &y);
pos.y += 5 + y;
wxString change_module_select[2] = { _("Keep"), _("Change") };
m_ChangeExistantModuleCtrl = new wxRadioBox(this, -1, _("Exchange Module:"),
pos, wxDefaultSize, 2, change_module_select, 1);
m_ChangeExistantModuleCtrl->GetSize(&x, &y);
pos.y += 15 + y;
m_DisplayWarningCtrl = new wxCheckBox(this, -1, _("Display Warnings"), pos);
m_DisplayWarningCtrl->SetValue(DisplayWarning);
m_DisplayWarningCtrl->GetSize(&x, &y);
pos.x = 5; pos.y += 10 + y;
m_MessageWindow = new wxTextCtrl(this, -1, "",
pos, wxSize(265, 120),wxTE_READONLY|wxTE_MULTILINE);
m_MessageWindow->GetSize(&x, &y);
pos.y += 10 + y;
SetClientSize(280, pos.y);
}
/**********************************************************************/
void WinEDA_NetlistFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
/**********************************************************************/
{
// true is to force the frame to close
Close(true);
}
/*****************************************************************/
void WinEDA_NetlistFrame::RecompileRatsnest(wxCommandEvent& event)
/*****************************************************************/
{
m_Parent->Compile_Ratsnest(m_DC, TRUE);
}
/***************************************************************/
bool WinEDA_NetlistFrame::OpenNetlistFile(wxCommandEvent& event)
/***************************************************************/
/*
routine de selection et d'ouverture du fichier Netlist
*/
{
wxString FullFileName;
wxString msg;
if( NetNameBuffer == "" ) /* Pas de nom specifie */
Set_NetlisteName(event);
if( NetNameBuffer == "" ) return(FALSE); /* toujours Pas de nom specifie */
FullFileName = NetNameBuffer;
source = fopen(FullFileName.GetData(),"rt");
if (source == 0)
{
msg.Printf(_("Netlist file %s not found"),FullFileName.GetData()) ;
DisplayError(this, msg) ;
return FALSE ;
}
msg.Printf("Netlist %s",FullFileName.GetData());
SetTitle(msg);
return TRUE;
}
/**************************************************************/
void WinEDA_NetlistFrame::ReadPcbNetlist(wxCommandEvent& event)
/**************************************************************/
/* mise a jour des empreintes :
corrige les Net Names, les textes, les "TIME STAMP"
Analyse les lignes:
# EESchema Netlist Version 1.0 generee le 18/5/2005-12:30:22
(
( 40C08647 $noname R20 4,7K {Lib=R}
( 1 VCC )
( 2 MODB_1 )
)
( 40C0863F $noname R18 4,7_k {Lib=R}
( 1 VCC )
( 2 MODA_1 )
)
}
#End
*/
{
int LineNum, State, Comment;
MODULE * Module = NULL;
D_PAD * PtPad;
char Line[256], *Text;
int UseFichCmp = 1;
wxString msg;
ChangeExistantModule = m_ChangeExistantModuleCtrl->GetSelection() == 1 ? TRUE : FALSE;
DisplayWarning = m_DisplayWarningCtrl->GetValue();
if ( DisplayWarning ) DisplayWarningCount = 8;
else DisplayWarningCount = 0;
if( ! OpenNetlistFile(event) ) return;
msg = _("Read Netlist ") + NetNameBuffer;
m_MessageWindow->AppendText(msg);
m_Parent->m_CurrentScreen->SetModify();
m_Parent->m_Pcb->m_Status_Pcb = 0 ; State = 0; LineNum = 0; Comment = 0;
s_NbNewModules = 0;
/* Premiere lecture de la netliste: etablissement de la liste
des modules a charger
*/
while( GetLine( source, Line, &LineNum) )
{
Text = StrPurge(Line);
if ( Comment ) /* Commentaires en cours */
{
if( (Text = strchr(Text,'}') ) == NULL )continue;
Comment = 0;
}
if ( *Text == '{' ) /* Commentaires */
{
Comment = 1;
if( (Text = strchr(Text,'}') ) == NULL ) continue;
}
if ( *Text == '(' ) State++;
if ( *Text == ')' ) State--;
if( State == 2 )
{
Module = ReadNetModule(Text, & UseFichCmp, TESTONLY);
continue;
}
if( State >= 3 ) /* la ligne de description d'un pad est ici non analysee */
{
State--;
}
}
/* Chargement des nouveaux modules */
if( s_NbNewModules )
{
LoadListeModules(m_DC);
// Free module list:
MODULEtoLOAD * item, *next_item;
for ( item = s_ModuleToLoad_List; item != NULL; item = next_item )
{
next_item = item->Next();
delete item;
}
s_ModuleToLoad_List = NULL;
}
/* Relecture de la netliste, tous les modules sont ici charges */
fseek(source, 0, SEEK_SET); LineNum = 0;
while( GetLine( source, Line, &LineNum) )
{
Text = StrPurge(Line);
if ( Comment ) /* Commentaires en cours */
{
if( (Text = strchr(Text,'}') ) == NULL )continue;
Comment = 0;
}
if ( *Text == '{' ) /* Commentaires */
{
Comment = 1;
if( (Text = strchr(Text,'}') ) == NULL ) continue;
}
if ( *Text == '(' ) State++;
if ( *Text == ')' ) State--;
if( State == 2 )
{
Module = ReadNetModule(Text, & UseFichCmp, READMODULE );
if( Module == NULL )
{ /* empreinte non trouvee dans la netliste */
continue ;
}
else /* Raz netnames sur pads */
{
PtPad = Module->m_Pads;
for( ; PtPad != NULL; PtPad = (D_PAD *)PtPad->Pnext )
{
PtPad->m_Netname = "";
}
}
continue;
}
if( State >= 3 )
{
if ( Module )
{
SetPadNetName( Text, Module);
}
State--;
}
}
fclose(source);
/* Mise a jour et Cleanup du circuit imprime: */
m_Parent->Compile_Ratsnest(m_DC, TRUE);
if( m_Parent->m_Pcb->m_Track )
{
if( m_DeleteBadTracks->GetSelection() == 1 )
{
wxBeginBusyCursor();;
Netliste_Controle_piste(m_Parent, m_DC, TRUE);
m_Parent->Compile_Ratsnest(m_DC, TRUE);
wxEndBusyCursor();;
}
}
Affiche_Infos_Status_Pcb(m_Parent);
}
/****************************************************************************/
MODULE * WinEDA_NetlistFrame::ReadNetModule(char * Text, int * UseFichCmp,
int TstOnly)
/****************************************************************************/
/* charge la description d'une empreinte ,netliste type PCBNEW
et met a jour le module correspondant
Si TstOnly == 0 si le module n'existe pas, il est charge
Si TstOnly != 0 si le module n'existe pas, il est ajoute a la liste des
modules a charger
Text contient la premiere ligne de la description
* UseFichCmp est un flag
si != 0, le fichier des composants .CMP sera utilise
est remis a 0 si le fichier n'existe pas
Analyse les lignes type:
( 40C08647 $noname R20 4,7K {Lib=R}
( 1 VCC )
( 2 MODB_1 )
*/
{
MODULE * Module;
char *TextTimeStamp;
char *TextNameLibMod;
char *TextValeur;
char *TextCmpName;
int TimeStamp = -1, Error = 0;
char Line[1024], NameLibCmp[256];
bool Found;
strcpy(Line,Text);
if( (TextTimeStamp = strtok(Line, " ()\t\n")) == NULL ) Error = 1;
if( (TextNameLibMod = strtok(NULL, " ()\t\n")) == NULL ) Error = 1;
if( (TextCmpName = strtok(NULL, " ()\t\n")) == NULL ) Error = 1;
if( (TextValeur = strtok(NULL, " ()\t\n")) == NULL ) Error = 1;
if( Error ) return( NULL );
sscanf(TextTimeStamp,"%X", &TimeStamp);
/* Tst si composant deja charge */
Module = (MODULE*) m_Parent->m_Pcb->m_Modules;
MODULE * NextModule;
for( Found = FALSE; Module != NULL; Module = NextModule )
{
NextModule = (MODULE*)Module->Pnext;
if( m_Select_By_Timestamp->GetSelection() == 1 ) /* Reconnaissance par signature temporelle */
{
if( TimeStamp == Module->m_TimeStamp) Found = TRUE;
}
else /* Reconnaissance par Reference */
{
if( stricmp(TextCmpName,Module->m_Reference->GetText()) == 0 )
Found = TRUE;
}
if ( Found ) // Test si module (m_LibRef) et module specifie en netlist concordent
{
if( TstOnly != TESTONLY )
{
strcpy(NameLibCmp, TextNameLibMod);
if( *UseFichCmp )
{
if( m_Select_By_Timestamp->GetSelection() == 1 )
{ /* Reconnaissance par signature temporelle */
*UseFichCmp = ReadListeModules(NULL, TimeStamp, NameLibCmp);
}
else /* Reconnaissance par Reference */
{
*UseFichCmp = ReadListeModules(TextCmpName, 0, NameLibCmp);
}
}
if ( stricmp(Module->m_LibRef.GetData(), NameLibCmp) != 0 )
{// Module Mismatch: Current module and module specified in netlist are diff.
if ( ChangeExistantModule )
{
MODULE * NewModule =
m_Parent->Get_Librairie_Module(this, "", NameLibCmp, TRUE);
if( NewModule ) /* Nouveau module trouve : changement de module */
Module = m_Parent->Exchange_Module(this, Module, NewModule);
}
else
{
wxString msg;
msg.Printf(
_("Cmp %s: Mismatch! module is [%s] and netlist said [%s]\n"),
TextCmpName, Module->m_LibRef.GetData(), NameLibCmp);
m_MessageWindow->AppendText(msg);
if ( DisplayWarningCount > 0)
{
DisplayError(this, msg, 2);
DisplayWarningCount--;
}
}
}
}
break;
}
}
if( Module == NULL ) /* Module a charger */
{
strcpy(NameLibCmp, TextNameLibMod);
if( *UseFichCmp )
{
if( m_Select_By_Timestamp->GetSelection() == 1)
{ /* Reconnaissance par signature temporelle */
*UseFichCmp = ReadListeModules(NULL, TimeStamp, NameLibCmp);
}
else /* Reconnaissance par Reference */
{
*UseFichCmp = ReadListeModules(TextCmpName, 0, NameLibCmp);
}
}
if( TstOnly == TESTONLY)
AddToList(NameLibCmp, TextCmpName, TimeStamp);
else
{
wxString msg;
msg.Printf(_("Componant [%s] not found"), TextCmpName);
m_MessageWindow->AppendText(msg+"\n");
if (DisplayWarningCount> 0)
{
DisplayError(this, msg, 2);
DisplayWarningCount--;
}
}
return(NULL); /* Le module n'avait pas pu etre charge */
}
/* mise a jour des reperes ( nom et ref "Time Stamp") si module charge */
Module->m_Reference->m_Text = TextCmpName;
Module->m_Value->m_Text = TextValeur;
Module->m_TimeStamp = TimeStamp;
return(Module) ; /* composant trouve */
}
/********************************************************************/
int WinEDA_NetlistFrame::SetPadNetName( char * Text, MODULE * Module)
/********************************************************************/
/*
Met a jour le netname de 1 pastille, Netliste ORCADPCB
entree :
Text = ligne de netliste lue ( (pad = net) )
Module = adresse de la structure MODULE a qui appartient les pads
*/
{
D_PAD * pad;
char * TextPinName, * TextNetName;
int Error = 0;
bool trouve;
char Line[256], Msg[80];
if( Module == NULL ) return ( 0 );
strcpy( Line, Text);
if( (TextPinName = strtok(Line, " ()\t\n")) == NULL ) Error = 1;
if( (TextNetName = strtok(NULL, " ()\t\n")) == NULL ) Error = 1;
if(Error) return(0);
/* recherche du pad */
pad = Module->m_Pads; trouve = FALSE;
for( ; pad != NULL; pad = (D_PAD *)pad->Pnext )
{
if( strnicmp( TextPinName, pad->m_Padname, 4) == 0 )
{ /* trouve */
trouve = TRUE;
if( *TextNetName != '?' ) pad->m_Netname = TextNetName;
else pad->m_Netname = "";
}
}
if( !trouve && (DisplayWarningCount > 0) )
{
sprintf(Msg,_("Module [%s]: Pad [%s] not found"),
Module->m_Reference->GetText(), TextPinName);
DisplayError(this, Msg, 1);
DisplayWarningCount--;
}
return(trouve);
}
/*****************************************************/
MODULE * WinEDA_PcbFrame::ListAndSelectModuleName(void)
/*****************************************************/
/* liste les noms des modules du PCB
Retourne:
un pointeur sur le module selectionne
NULL si pas de selection
*/
{
int ii, jj, nb_empr;
MODULE * Module;
WinEDAListBox * ListBox;
const char ** ListNames = NULL;
if( m_Pcb->m_Modules == NULL )
{
DisplayError(this, _("No Modules") ) ; return(0);
}
/* Calcul du nombre des modules */
nb_empr = 0; Module = (MODULE*)m_Pcb->m_Modules;
for( ;Module != NULL; Module = (MODULE*)Module->Pnext) nb_empr++;
ListNames = (const char**) MyZMalloc( (nb_empr + 1) * sizeof(char*) );
Module = (MODULE*) m_Pcb->m_Modules;
for( ii = 0; Module != NULL; Module = (MODULE*)Module->Pnext, ii++)
{
ListNames[ii] = Module->m_Reference->GetText();
}
ListBox = new WinEDAListBox(this, _("Componants"),
ListNames, "");
ii = ListBox->ShowModal(); ListBox->Destroy();
if( ii < 0 ) /* Pas de selection */
{
Module = NULL;
}
else /* Recherche du module selectionne */
{
Module = (MODULE*) m_Pcb->m_Modules;
for( jj = 0; Module != NULL; Module = (MODULE*)Module->Pnext, jj++)
{
if( Module->m_Reference->GetText() == ListNames[ii] ) break;
}
}
free(ListNames);
return(Module);
}
/***************************************************************/
void WinEDA_NetlistFrame::ModulesControle(wxCommandEvent& event)
/***************************************************************/
/* donne la liste :
1 - des empreintes doublées sur le PCB
2 - des empreintes manquantes par rapport a la netliste
3 - des empreintes supplémentaires par rapport a la netliste
*/
#define MAX_LEN_TXT 32
{
int ii, NbModulesPcb;
MODULE * Module, * pt_aux;
int NbModulesNetListe ,nberr = 0 ;
char *ListeNetModules, * NameNetMod;
WinEDA_TextFrame * List;
/* determination du nombre des modules du PCB*/
NbModulesPcb = 0; Module = (MODULE*) m_Parent->m_Pcb->m_Modules;
for( ;Module != NULL; Module = (MODULE*)Module->Pnext)
{
NbModulesPcb++;
}
if( NbModulesPcb == 0 )
{
DisplayError(this, _("No modules"), 10); return;
}
/* Construction de la liste des references des modules de la netliste */
NbModulesNetListe = BuildListeNetModules(event, NULL);
if( NbModulesNetListe < 0 ) return; /* fichier non trouve */
if( NbModulesNetListe == 0 )
{
DisplayError(this, _("No modules in NetList"), 10); return;
}
ii = NbModulesNetListe * (MAX_LEN_TXT + 1);
ListeNetModules = (char*)MyZMalloc ( ii );
if( NbModulesNetListe ) BuildListeNetModules(event, ListeNetModules);
List = new WinEDA_TextFrame(this, _("Check Modules"));
/* recherche des doubles */
List->Append(_("Duplicates"));
Module = (MODULE*) m_Parent->m_Pcb->m_Modules;
for( ;Module != NULL; Module = (MODULE*)Module->Pnext)
{
pt_aux = (MODULE*)Module->Pnext;
for( ; pt_aux != NULL; pt_aux = (MODULE*)pt_aux->Pnext)
{
if( strnicmp(Module->m_Reference->GetText(),
pt_aux->m_Reference->GetText(),MAX_LEN_TXT) == 0 )
{
List->Append(Module->m_Reference->GetText());
nberr++ ;
break;
}
}
}
/* recherche des manquants par rapport a la netliste*/
List->Append(_("Lack:") );
NameNetMod = ListeNetModules;
for ( ii = 0 ; ii < NbModulesNetListe ; ii++, NameNetMod += MAX_LEN_TXT+1 )
{
Module = (MODULE*) m_Parent->m_Pcb->m_Modules;
for( ;Module != NULL; Module = (MODULE*)Module->Pnext)
{
if( strnicmp(Module->m_Reference->GetText(), NameNetMod, MAX_LEN_TXT)
== 0 )
{
break;
}
}
if( Module == NULL )
{
List->Append(NameNetMod);
nberr++ ;
}
}
/* recherche des modules supplementaires (i.e. Non en Netliste) */
List->Append(_("Not in Netlist:") );
Module = (MODULE*) m_Parent->m_Pcb->m_Modules;
for( ;Module != NULL; Module = Module->Next())
{
NameNetMod = ListeNetModules;
for (ii = 0; ii < NbModulesNetListe ; ii++, NameNetMod += MAX_LEN_TXT+1 )
{
if( strnicmp(Module->m_Reference->GetText(), NameNetMod, MAX_LEN_TXT)
== 0 )
{
break ;/* Module trouve en netliste */
}
}
if( ii == NbModulesNetListe ) /* Module en trop */
{
List->Append(Module->m_Reference->GetText());
nberr++ ;
}
}
sprintf(cbuf, _("%d Errors"), nberr);
List->ShowModal(); List->Destroy();
MyFree(ListeNetModules);
}
/***********************************************************************************/
int WinEDA_NetlistFrame::BuildListeNetModules(wxCommandEvent& event, char * BufName)
/***********************************************************************************/
/*
charge en BufName la liste des noms des modules de la netliste,
( chaque nom est en longueur fixe, sizeof(pt_texte_ref->name) + code 0 )
retourne le nombre des modules cités dans la netliste
Si BufName == NULL: determination du nombre des Module uniquement
*/
{
int textlen;
int nb_modules_lus ;
int State, LineNum, Comment;
char Line[256], *Text, * LibModName;
if( ! OpenNetlistFile(event) ) return -1;
State = 0; LineNum = 0; Comment = 0;
nb_modules_lus = 0;
textlen = MAX_LEN_TXT;
while( GetLine( source, Line, &LineNum) )
{
Text = StrPurge(Line);
if ( Comment ) /* Commentaires en cours */
{
if( (Text = strchr(Text,'}') ) == NULL )continue;
Comment = 0;
}
if ( *Text == '{' ) /* Commentaires */
{
Comment = 1;
if( (Text = strchr(Text,'}') ) == NULL ) continue;
}
if ( *Text == '(' ) State++;
if ( *Text == ')' ) State--;
if( State == 2 )
{
int Error = 0;
if( strtok(Line, " ()\t\n") == NULL ) Error = 1; /* TimeStamp */
if( ( LibModName = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; /* nom Lib */
/* Lecture du nom (reference) du composant: */
if( (Text = strtok(NULL, " ()\t\n")) == NULL ) Error = 1;
nb_modules_lus++;
if( BufName )
{
strncpy( BufName, Text, textlen ); BufName[textlen] = 0;
BufName += textlen+1;
}
continue;
}
if( State >= 3 )
{
State--; /* Lecture 1 ligne relative au Pad */
}
}
fclose(source);
return(nb_modules_lus);
}
/*****************************************************************************************/
int WinEDA_NetlistFrame::ReadListeModules(const char * RefCmp, int TimeStamp, char * NameModule)
/*****************************************************************************************/
/*
Lit le fichier .CMP donnant l'equivalence Modules / Composants
Retourne:
Si ce fichier existe:
1 et le nom module dans NameModule
-1 si module non trouve en fichier
sinon 0;
parametres d'appel:
RefCmp (NULL si selection par TimeStamp)
TimeStamp (signature temporelle si elle existe, NULL sinon)
pointeur sur le buffer recevant le nom du module
Exemple de fichier:
Cmp-Mod V01 Genere par PcbNew le 29/10/2003-13:11:6
BeginCmp
TimeStamp = 322D3011;
Reference = BUS1;
ValeurCmp = BUSPC;
IdModule = BUS_PC;
EndCmp
BeginCmp
TimeStamp = 32307DE2;
Reference = C1;
ValeurCmp = 47uF;
IdModule = CP6;
EndCmp
*/
{
wxString CmpFullFileName;
char refcurrcmp[512], idmod[512], ia[1024];
int timestamp;
char *ptcar;
FILE * FichCmp;
if( (RefCmp == NULL) && (TimeStamp == 0) ) return(0);
CmpFullFileName = NetNameBuffer;
ChangeFileNameExt(CmpFullFileName,NetCmpExtBuffer) ;
FichCmp = fopen(CmpFullFileName.GetData(),"rt");
if (FichCmp == NULL)
{
wxString msg;
msg.Printf( _("File <%s> not found, use Netlist for lib module selection"),
CmpFullFileName.GetData()) ;
DisplayError(this, cbuf, 20) ;
return(0);
}
while( fgets(ia,sizeof(ia),FichCmp) != NULL )
{
if( strnicmp(ia,"BeginCmp",8) != 0 ) continue;
/* Ici une description de 1 composant commence */
*refcurrcmp = *idmod = 0;
timestamp = -1;
while( fgets(ia,sizeof(ia),FichCmp) != NULL )
{
if( strnicmp(ia,"EndCmp",6) == 0 ) break;
if( strnicmp(ia,"Reference =",11) == 0 )
{
ptcar = ia+11;
ptcar = strtok(ptcar," =;\t\n");
if( ptcar ) strcpy(refcurrcmp,ptcar);
continue;
}
if( strnicmp(ia,"IdModule =",11) == 0 )
{
ptcar = ia+11;
ptcar = strtok(ptcar," =;\t\n");
if( ptcar ) strcpy(idmod,ptcar);
continue;
}
if( strnicmp(ia,"TimeStamp =",11) == 0 )
{
ptcar = ia+11;
ptcar = strtok(ptcar," =;\t\n");
if( ptcar ) sscanf(ptcar, "%X", ×tamp);
}
}/* Fin lecture 1 descr composant */
/* Test du Composant lu en fichier: est-il le bon */
if( RefCmp )
{
if( stricmp(RefCmp, refcurrcmp) == 0 )
{
fclose(FichCmp);
strcpy(NameModule, idmod);
return(1);
}
}
else if( TimeStamp != -1 )
{
if( TimeStamp == timestamp )
{
fclose(FichCmp);
strcpy(NameModule, idmod);
return(1);
}
}
}
fclose(FichCmp);
return(-1);
}
/***************************************************************/
void WinEDA_NetlistFrame::Set_NetlisteName(wxCommandEvent& event)
/***************************************************************/
/* Selection un nouveau nom de netliste
Affiche la liste des fichiers netlistes pour selection sur liste
*/
{
wxString fullfilename, mask("*");
mask += NetExtBuffer;
fullfilename = EDA_FileSelector( _("Netlist Selection:"),
"", /* Chemin par defaut */
NetNameBuffer, /* nom fichier par defaut */
NetExtBuffer, /* extension par defaut */
mask, /* Masque d'affichage */
this,
0,
TRUE
);
if ( fullfilename == "" ) return;
NetNameBuffer = fullfilename;
SetTitle(fullfilename);
}
/***********************************************************************************/
void WinEDA_NetlistFrame::AddToList(const char * NameLibCmp, const char * CmpName,int TimeStamp )
/************************************************************************************/
/* Fontion copiant en memoire de travail les caracteristiques
des nouveaux modules
*/
{
MODULEtoLOAD * NewMod;
NewMod = new MODULEtoLOAD(NameLibCmp, CmpName, TimeStamp);
NewMod->Pnext = s_ModuleToLoad_List;
s_ModuleToLoad_List = NewMod;
s_NbNewModules++;
}
/***************************************************************/
void WinEDA_NetlistFrame::LoadListeModules(wxDC * DC)
/***************************************************************/
/* Routine de chargement des nouveaux modules en une seule lecture des
librairies
Si un module vient d'etre charge il est duplique, ce qui evite une lecture
inutile de la librairie
*/
{
MODULEtoLOAD * ref, *cmp;
int ii;
MODULE * Module = NULL;
wxPoint OldPos = m_Parent->m_CurrentScreen->m_Curseur;
if( s_NbNewModules == 0 ) return;
SortListModulesToLoadByLibname(s_NbNewModules);
ref = cmp = s_ModuleToLoad_List;
// Calcul de la coordonnée de placement des modules:
if ( m_Parent->SetBoardBoundaryBoxFromEdgesOnly() )
{
m_Parent->m_CurrentScreen->m_Curseur.x = m_Parent->m_Pcb->m_BoundaryBox.GetRight() + 5000;
m_Parent->m_CurrentScreen->m_Curseur.y = m_Parent->m_Pcb->m_BoundaryBox.GetBottom() + 10000;
}
else
{
m_Parent->m_CurrentScreen->m_Curseur = wxPoint(0,0);
}
for( ii = 0; ii < s_NbNewModules; ii++, cmp = cmp->Next() )
{
if( (ii == 0) || ( ref->m_LibName != cmp->m_LibName) )
{ /* Nouveau Module a charger */
Module = m_Parent->Get_Librairie_Module(this, "", cmp->m_LibName, TRUE );
ref = cmp;
if ( Module == NULL ) continue;
m_Parent->Place_Module(Module, DC);
/* mise a jour des reperes ( nom et ref "Time Stamp")
si module charge */
Module->m_Reference->m_Text = cmp->m_CmpName;
Module->m_TimeStamp = cmp->m_TimeStamp;
}
else
{ /* module deja charge, on peut le dupliquer */
MODULE * newmodule;
if ( Module == NULL ) continue; /* module non existant en libr */
newmodule = new MODULE(m_Parent->m_Pcb);
newmodule->Copy(Module);
newmodule->AddToChain(Module);
Module = newmodule;
Module->m_Reference->m_Text = cmp->m_CmpName;
Module->m_TimeStamp = cmp->m_TimeStamp;
}
}
m_Parent->m_CurrentScreen->m_Curseur = OldPos;
}
/* Routine utilisee par qsort pour le tri des modules a charger
*/
static int SortByLibName( MODULEtoLOAD ** ref, MODULEtoLOAD ** cmp )
{
return (strcmp( (*ref)->m_LibName.GetData(), (*cmp)->m_LibName.GetData() ) );
}
/*************************************************/
void SortListModulesToLoadByLibname(int NbModules)
/**************************************************/
/* Rearrage la liste des modules List par ordre alphabetique des noms lib des modules
*/
{
MODULEtoLOAD ** base_list, * item;
int ii;
base_list = (MODULEtoLOAD **) MyMalloc( NbModules * sizeof(MODULEtoLOAD *) );
for ( ii = 0, item = s_ModuleToLoad_List; ii < NbModules; ii++ )
{
base_list[ii] = item;
item = item->Next();
}
qsort( base_list, NbModules, sizeof(MODULEtoLOAD*),
(int(*)(const void *, const void *) )SortByLibName);
// Reconstruction du chainage:
s_ModuleToLoad_List = *base_list;
for ( ii = 0; ii < NbModules-1; ii++ )
{
item = base_list[ii];
item->Pnext = base_list[ii + 1];
}
// Dernier item: Pnext = NULL:
item = base_list[ii];
item->Pnext = NULL;
free(base_list);
}
/*****************************************************************************/
MODULEtoLOAD::MODULEtoLOAD(const wxString & libname, const wxString & cmpname,
int timestamp) : EDA_BaseStruct(TYPE_NOT_INIT)
/*****************************************************************************/
{
m_LibName = libname;
m_CmpName = cmpname;
m_TimeStamp = timestamp;
}
|
[
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
] |
bokeoa@244deca0-f506-0410-ab94-f4f3571dea26
|
7e0c75c5fc877a898df1589010e04d6cf30693df
|
3295316f85d069650a0dee5df5a64b332011a8c4
|
/NativeDLL/Wamedia/mp4muxer/include/mp4flavoridentifier.h
|
8dbe98272c034e7d0753e5a6d9f545e04bc5748b
|
[] |
no_license
|
whitespeed/UnityRealtimeCapture
|
6cf3135fbc7c5d81548cc5528e4bf381c4797fa4
|
4f1c48bb4ce2647c989b55a0867d8c2622a1060f
|
refs/heads/master
| 2020-03-08T09:18:23.853786
| 2018-04-04T10:03:11
| 2018-04-04T10:03:11
| 128,043,858
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 483
|
h
|
#pragma once
#include "mp4errors.h"
#ifdef __cplusplus
namespace libmp4operations
{
extern "C"
{
#endif // __cplusplus
typedef enum
{
MP4_FORMAT_FLAVOR_UNIDENTIFIED = 0,
MP4_FORMAT_FLAVOR_ISO_3G2_3GPP,
MP4_FORMAT_FLAVOR_APPLE_QUICK_TIME_MOV,
MP4_FORMAT_FLAVOR_FRAGMENTED_MP4
} eMP4_FORMAT_FLAVOR;
uint32_t determineMp4FormatFlavor(const char* pStrInputFilename, eMP4_FORMAT_FLAVOR* pFlavor);
#ifdef __cplusplus
}
}; // namespace libmp4operations
#endif // __cplusplus
|
[
"whitespeed@qq.com"
] |
whitespeed@qq.com
|
7d7598898c8b3c04621809639c48717b9068b925
|
27f3ddc8ff6f5994fa1c0377dfbb0b7559f6aa90
|
/course1/algorithms/5_graphs/L_strong.cpp
|
b062f7fa98ea7acf3c972d99149e3020293d3436
|
[] |
no_license
|
vlad-mk/ifmo-kt
|
8240d6e9be6aeffc2eb5287198a367c6e23d4f4c
|
7481e2977dc986339920fd0cc69b360bcfa3d072
|
refs/heads/master
| 2023-07-03T21:01:43.823212
| 2019-01-12T06:11:10
| 2019-01-12T06:11:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,630
|
cpp
|
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
FILE *fin = fopen("strong.in", "r");
FILE *fout = fopen("strong.out", "w");
const int MAXN = 20000 + 1;
int n, m;
vector<int> g[MAXN], gr[MAXN];
vector<char> used;
vector<int> order, component, answer;
int counter = 0;
void dfs1 (int v) {
used[v] = true;
for (size_t i = 0; i < g[v].size(); ++i){
if (!used[g[v][i]]){
dfs1(g[v][i]);
}
}
order.push_back(v);
}
void dfs2 (int v) {
used[v] = true;
component.push_back(v);
for (size_t i = 0; i < gr[v].size(); ++i){
if (!used[gr[v][i]]){
dfs2 (gr[v][i]);
}
}
}
int main(int argc, char **argv) {
fscanf(fin, "%d %d", &n, &m);
answer.assign(n, 0);
for(int i = 0, v1, v2; i < m; i++) {
fscanf(fin, "%d %d", &v1, &v2);
v1--; v2--;
g[v1].push_back(v2);
gr[v2].push_back(v1);
}
used.assign(n, false);
for (int i = 0; i < n; ++i)
if (!used[i]){
dfs1(i);
}
used.assign(n, false);
for (int i = 0; i < n; ++i) {
int v = order[n-1-i];
if (!used[v]) {
dfs2(v);
if(component.size() > 0){
counter++;
for(size_t j = 0; j < component.size(); j++){
answer[component[j]] = counter;
}
}
component.clear();
}
}
fprintf(fout, "%d\n", counter);
for (int i = 0; i < n; ++i) {
fprintf(fout, "%d ", answer[i]);
}
fprintf(fout, "\n");
fclose(fin);
fclose(fout);
}
|
[
"egormkn@yandex.ru"
] |
egormkn@yandex.ru
|
7ae1fe8a5872b203664dc1f31a0563069113810e
|
8cf763c4c29db100d15f2560953c6e6cbe7a5fd4
|
/src/qt/qtbase/src/testlib/qxunittestlogger.cpp
|
e98ddb5e4ff440e82cbcaaf6604994b068f32b52
|
[
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GFDL-1.3-only",
"Qt-LGPL-exception-1.1",
"LicenseRef-scancode-digia-qt-commercial",
"LGPL-3.0-only",
"GPL-3.0-only",
"LicenseRef-scancode-digia-qt-preview",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"BSD-3-Clause"
] |
permissive
|
chihlee/phantomjs
|
69d6bbbf1c9199a78e82ae44af072aca19c139c3
|
644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c
|
refs/heads/master
| 2021-01-19T13:49:41.265514
| 2018-06-15T22:48:11
| 2018-06-15T22:48:11
| 82,420,380
| 0
| 0
|
BSD-3-Clause
| 2018-06-15T22:48:12
| 2017-02-18T22:34:48
|
C++
|
UTF-8
|
C++
| false
| false
| 11,384
|
cpp
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtTest module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/private/qxunittestlogger_p.h>
#include <QtTest/private/qtestelement_p.h>
#include <QtTest/private/qtestxunitstreamer_p.h>
#include <QtTest/qtestcase.h>
#include <QtTest/private/qtestresult_p.h>
#include <QtTest/private/qbenchmark_p.h>
#ifdef min // windows.h without NOMINMAX is included by the benchmark headers.
# undef min
#endif
#ifdef max
# undef max
#endif
#include <QtCore/qlibraryinfo.h>
#include <string.h>
QT_BEGIN_NAMESPACE
QXunitTestLogger::QXunitTestLogger(const char *filename)
: QAbstractTestLogger(filename)
, listOfTestcases(0)
, currentLogElement(0)
, errorLogElement(0)
, logFormatter(0)
, testCounter(0)
, failureCounter(0)
, errorCounter(0)
{
}
QXunitTestLogger::~QXunitTestLogger()
{
delete currentLogElement;
delete logFormatter;
}
void QXunitTestLogger::startLogging()
{
QAbstractTestLogger::startLogging();
logFormatter = new QTestXunitStreamer(this);
delete errorLogElement;
errorLogElement = new QTestElement(QTest::LET_SystemError);
}
void QXunitTestLogger::stopLogging()
{
QTestElement *iterator = listOfTestcases;
char buf[10];
currentLogElement = new QTestElement(QTest::LET_TestSuite);
currentLogElement->addAttribute(QTest::AI_Name, QTestResult::currentTestObjectName());
qsnprintf(buf, sizeof(buf), "%i", testCounter);
currentLogElement->addAttribute(QTest::AI_Tests, buf);
qsnprintf(buf, sizeof(buf), "%i", failureCounter);
currentLogElement->addAttribute(QTest::AI_Failures, buf);
qsnprintf(buf, sizeof(buf), "%i", errorCounter);
currentLogElement->addAttribute(QTest::AI_Errors, buf);
QTestElement *property;
QTestElement *properties = new QTestElement(QTest::LET_Properties);
property = new QTestElement(QTest::LET_Property);
property->addAttribute(QTest::AI_Name, "QTestVersion");
property->addAttribute(QTest::AI_PropertyValue, QTEST_VERSION_STR);
properties->addLogElement(property);
property = new QTestElement(QTest::LET_Property);
property->addAttribute(QTest::AI_Name, "QtVersion");
property->addAttribute(QTest::AI_PropertyValue, qVersion());
properties->addLogElement(property);
property = new QTestElement(QTest::LET_Property);
property->addAttribute(QTest::AI_Name, "QtBuild");
property->addAttribute(QTest::AI_PropertyValue, QLibraryInfo::build());
properties->addLogElement(property);
currentLogElement->addLogElement(properties);
currentLogElement->addLogElement(iterator);
/* For correct indenting, make sure every testcase knows its parent */
QTestElement* testcase = iterator;
while (testcase) {
testcase->setParent(currentLogElement);
testcase = testcase->nextElement();
}
currentLogElement->addLogElement(errorLogElement);
QTestElement *it = currentLogElement;
logFormatter->output(it);
QAbstractTestLogger::stopLogging();
}
void QXunitTestLogger::enterTestFunction(const char *function)
{
currentLogElement = new QTestElement(QTest::LET_TestCase);
currentLogElement->addAttribute(QTest::AI_Name, function);
currentLogElement->addToList(&listOfTestcases);
++testCounter;
}
void QXunitTestLogger::leaveTestFunction()
{
}
void QXunitTestLogger::addIncident(IncidentTypes type, const char *description,
const char *file, int line)
{
const char *typeBuf = 0;
char buf[100];
switch (type) {
case QAbstractTestLogger::XPass:
++failureCounter;
typeBuf = "xpass";
break;
case QAbstractTestLogger::Pass:
typeBuf = "pass";
break;
case QAbstractTestLogger::XFail:
typeBuf = "xfail";
break;
case QAbstractTestLogger::Fail:
++failureCounter;
typeBuf = "fail";
break;
case QAbstractTestLogger::BlacklistedPass:
typeBuf = "bpass";
break;
case QAbstractTestLogger::BlacklistedFail:
++failureCounter;
typeBuf = "bfail";
break;
default:
typeBuf = "??????";
break;
}
if (type == QAbstractTestLogger::Fail || type == QAbstractTestLogger::XPass) {
QTestElement *failureElement = new QTestElement(QTest::LET_Failure);
failureElement->addAttribute(QTest::AI_Result, typeBuf);
if (file)
failureElement->addAttribute(QTest::AI_File, file);
else
failureElement->addAttribute(QTest::AI_File, "");
qsnprintf(buf, sizeof(buf), "%i", line);
failureElement->addAttribute(QTest::AI_Line, buf);
failureElement->addAttribute(QTest::AI_Description, description);
addTag(failureElement);
currentLogElement->addLogElement(failureElement);
}
/*
Only one result can be shown for the whole testfunction.
Check if we currently have a result, and if so, overwrite it
iff the new result is worse.
*/
QTestElementAttribute* resultAttr =
const_cast<QTestElementAttribute*>(currentLogElement->attribute(QTest::AI_Result));
if (resultAttr) {
const char* oldResult = resultAttr->value();
bool overwrite = false;
if (!strcmp(oldResult, "pass")) {
overwrite = true;
}
else if (!strcmp(oldResult, "bpass")) {
overwrite = (type == QAbstractTestLogger::XPass || type == QAbstractTestLogger::Fail) || (type == QAbstractTestLogger::XFail)
|| (type == QAbstractTestLogger::BlacklistedFail);
}
else if (!strcmp(oldResult, "bfail")) {
overwrite = (type == QAbstractTestLogger::XPass || type == QAbstractTestLogger::Fail) || (type == QAbstractTestLogger::XFail);
}
else if (!strcmp(oldResult, "xfail")) {
overwrite = (type == QAbstractTestLogger::XPass || type == QAbstractTestLogger::Fail);
}
else if (!strcmp(oldResult, "xpass")) {
overwrite = (type == QAbstractTestLogger::Fail);
}
if (overwrite) {
resultAttr->setPair(QTest::AI_Result, typeBuf);
}
}
else {
currentLogElement->addAttribute(QTest::AI_Result, typeBuf);
}
if (file)
currentLogElement->addAttribute(QTest::AI_File, file);
else
currentLogElement->addAttribute(QTest::AI_File, "");
qsnprintf(buf, sizeof(buf), "%i", line);
currentLogElement->addAttribute(QTest::AI_Line, buf);
/*
Since XFAIL does not add a failure to the testlog in xunitxml, add a message, so we still
have some information about the expected failure.
*/
if (type == QAbstractTestLogger::XFail) {
QXunitTestLogger::addMessage(QAbstractTestLogger::Info, QString::fromUtf8(description), file, line);
}
}
void QXunitTestLogger::addBenchmarkResult(const QBenchmarkResult &result)
{
QTestElement *benchmarkElement = new QTestElement(QTest::LET_Benchmark);
benchmarkElement->addAttribute(
QTest::AI_Metric,
QTest::benchmarkMetricName(QBenchmarkTestMethodData::current->result.metric));
benchmarkElement->addAttribute(QTest::AI_Tag, result.context.tag.toUtf8().data());
const qreal valuePerIteration = qreal(result.value) / qreal(result.iterations);
benchmarkElement->addAttribute(QTest::AI_Value, QByteArray::number(valuePerIteration).constData());
char buf[100];
qsnprintf(buf, sizeof(buf), "%i", result.iterations);
benchmarkElement->addAttribute(QTest::AI_Iterations, buf);
currentLogElement->addLogElement(benchmarkElement);
}
void QXunitTestLogger::addTag(QTestElement* element)
{
const char *tag = QTestResult::currentDataTag();
const char *gtag = QTestResult::currentGlobalDataTag();
const char *filler = (tag && gtag) ? ":" : "";
if ((!tag || !tag[0]) && (!gtag || !gtag[0])) {
return;
}
if (!tag) {
tag = "";
}
if (!gtag) {
gtag = "";
}
QTestCharBuffer buf;
QTest::qt_asprintf(&buf, "%s%s%s", gtag, filler, tag);
element->addAttribute(QTest::AI_Tag, buf.constData());
}
void QXunitTestLogger::addMessage(MessageTypes type, const QString &message, const char *file, int line)
{
QTestElement *errorElement = new QTestElement(QTest::LET_Error);
const char *typeBuf = 0;
switch (type) {
case QAbstractTestLogger::Warn:
typeBuf = "warn";
break;
case QAbstractTestLogger::QSystem:
typeBuf = "system";
break;
case QAbstractTestLogger::QDebug:
typeBuf = "qdebug";
break;
case QAbstractTestLogger::QWarning:
typeBuf = "qwarn";
break;
case QAbstractTestLogger::QFatal:
typeBuf = "qfatal";
break;
case QAbstractTestLogger::Skip:
typeBuf = "skip";
break;
case QAbstractTestLogger::Info:
typeBuf = "info";
break;
default:
typeBuf = "??????";
break;
}
errorElement->addAttribute(QTest::AI_Type, typeBuf);
errorElement->addAttribute(QTest::AI_Description, message.toUtf8().constData());
addTag(errorElement);
if (file)
errorElement->addAttribute(QTest::AI_File, file);
else
errorElement->addAttribute(QTest::AI_File, "");
char buf[100];
qsnprintf(buf, sizeof(buf), "%i", line);
errorElement->addAttribute(QTest::AI_Line, buf);
currentLogElement->addLogElement(errorElement);
++errorCounter;
// Also add the message to the system error log (i.e. stderr), if one exists
if (errorLogElement) {
QTestElement *systemErrorElement = new QTestElement(QTest::LET_Error);
systemErrorElement->addAttribute(QTest::AI_Description, message.toUtf8().constData());
errorLogElement->addLogElement(systemErrorElement);
}
}
QT_END_NAMESPACE
|
[
"ariya.hidayat@gmail.com"
] |
ariya.hidayat@gmail.com
|
f4a385972682954409236cd20967da31fb5226f6
|
f5ac7da57d433201a3c802e5f1611ff7914ca5bd
|
/src/ec/GF2X/affine/utils.cpp
|
730996d4a6864b923d985ef2f3784fbe2a228a64
|
[] |
no_license
|
natalikovaleva/iso-iec-9796-3
|
c4740b42001099f863b0b274d45029d8bc773a83
|
1d9926960026059dd90671c9c3d05d8b44c81900
|
refs/heads/master
| 2021-01-01T04:01:05.518073
| 2011-12-18T09:48:05
| 2011-12-18T09:48:05
| 56,810,825
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,378
|
cpp
|
#include "ec/GF2X/affine/utils.hpp"
#include "generic/gf2x_utils.hpp"
using namespace std;
using namespace NTL;
using namespace ECGF2X::Affine;
/* Smart stupid !! OCTET !! concatentaion. Be carefull! :] */
#include <stdio.h>
namespace ECGF2X
{
namespace Affine
{
ByteSeq EC2OSP(const EC_Point & Point, EC::EC2OSP_COMPRESS_MODE mode)
{
const unsigned char tY =
((mode == EC::EC2OSP_COMPRESSED) ||
(mode == EC::EC2OSP_HYBRID)) ?
EC_CPoint::compress_tY(Point) : 0;
if (Point.isZero())
return ByteSeq(0);
/* Pad - according to example of 2^m/ECNR.
* Check this. Don't see much sense */
const long Pad = L(Point.getEC().getModulus());
const unsigned int U = ((mode == EC::EC2OSP_UNCOMPRESSED) ||
(mode == EC::EC2OSP_HYBRID)) ? 1 : 0;
const unsigned int C = ((mode == EC::EC2OSP_COMPRESSED) ||
(mode == EC::EC2OSP_HYBRID)) ? 1 : 0;
const ByteSeq X(FE2OSP(Point.getX(), Pad));
const ByteSeq H(FE2OSP(4*U+C*(2+tY)));
if (U)
return H || X || FE2OSP(Point.getY(), Pad);
else
return H || X;
}
}
}
|
[
"avatar@IIT"
] |
avatar@IIT
|
f341ff88ef3dc5883f65135b2eca02023597cc15
|
768316ed72470715e641fda62a9166b610b27350
|
/05-CodeChef-Challenge/103--Art in Digital Age.cpp
|
a15a5e53544022cc0878f8d938d3b626be5a54ee
|
[] |
no_license
|
dhnesh12/codechef-solutions
|
41113bb5922156888d9e57fdc35df89246e194f7
|
55bc7a69f76306bc0c3694180195c149cf951fb6
|
refs/heads/master
| 2023-03-31T15:42:04.649785
| 2021-04-06T05:38:38
| 2021-04-06T05:38:38
| 355,063,355
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,837
|
cpp
|
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <bitset>
#include <sstream>
#include <deque>
#include <queue>
#include <complex>
#include <random>
#include <cassert>
#include <chrono>
using namespace std;
#define DEBUG
#define FAST ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define FIXED cout << fixed << setprecision(12)
#define int long long
#define ll long long
#define ld long double
#define pii pair<int, int>
#define pll pair<ll, ll>
#define graph vector<vector<int>>
#define pb push_back
#define pf push_front
#define popb pop_back
#define popf pop_front
#define f first
#define s second
#define hashmap unordered_map
#define hashset unordered_set
#define eps 1e-9
#define mod 1000000007
#define inf 3000000000000000007ll
#define sz(a) signed((a).size())
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#ifdef DEBUG
mt19937 gen(857204);
#else
mt19937 gen(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif
#ifdef DEBUG
template<class T> T to_dbg(T x) { return x; }
template<class T, class U> string to_dbg(pair<T, U> p) {
stringstream ss;
ss << '{' << p.f << ',' << p.s << '}';
return ss.str();
}
string to_dbg(string s) { return "\"" + s + "\""; }
template<class It> string to_dbg(It begin, It end, string d = "") {
stringstream ss;
ss << '{';
if (begin != end) ss << to_dbg(*begin++);
while (begin != end)
ss << "," << d << to_dbg(*begin++);
ss << '}';
return ss.str();
}
template<class T> string to_dbg(vector<T> a) { return to_dbg(all(a)); }
template<class T> string to_dbg(set<T> a) { return to_dbg(all(a)); }
template<class T> string to_dbg(hashset<T> a) { return to_dbg(all(a)); }
template<class T, class U> string to_dbg(map<T, U> a) { return to_dbg(all(a), "\n"); }
template<class T, class U> string to_dbg(hashmap<T, U> a) { return to_dbg(all(a), "\n"); }
template<class T> void dbgout(T x) { cout << to_dbg(x) << endl; }
template<class T, class... U>
void dbgout(T t, U... u) {
cout << to_dbg(t) << " ";
dbgout(u...);
}
#define dbg(...) cout << "[" << #__VA_ARGS__ << "] = ", dbgout(__VA_ARGS__)
#else
#define dbg(...) 0
#endif
template<class T, class U> inline bool chmax(T &x, U y) { return x < y ? x = y, 1 : 0; }
template<class T, class U> inline bool chmin(T &x, U y) { return x > y ? x = y, 1 : 0; }
template<class T> inline void sort(T &a) { sort(all(a)); }
template<class T> inline void rsort(T &a) { sort(rall(a)); }
template<class T> inline void reverse(T &a) { reverse(all(a)); }
template<class T, class U> inline istream& operator>>(istream& str, pair<T, U> &p) { return str >> p.f >> p.s; }
template<class T> inline istream& operator>>(istream& str, vector<T> &a) { for (auto &i : a) str >> i; return str; }
template<class T> inline T sorted(T a) { sort(a); return a; }
void read() {} void print() {} void println() { cout << '\n'; }
template<class T, class ...U> void read(T &x, U& ... u) { cin >> x; read(u...); }
template<class T, class ...U> void print(const T &x, const U& ... u) { cout << x; print(u...); }
template<class T, class ...U> void println(const T &x, const U& ... u) { cout << x; println(u...); }
const int N = 1200;
int a[N][N], mark[N][N];
int Check(int x,int y,int l,int r) {
for (int i = l; i <= r; i++) if (a[i][y] == 0 || mark[i][y]) return 0;
for (int i = l; i <= r; i++) if (a[i][y] != a[i][x]) return 1;
return 2;
}
void Fill(int l,int r,int j)
{
for (int i = l; i <= r; i++)
mark[i][j] = 1;
}
vector<int> Re[5];
main() {
//FAST;
int n; cin >> n;
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) cin >> a[i][j];
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) {
if (mark[i][j] || !a[i][j]) continue;
mark[i][j] = 1;
int J = j;
while (J < n && a[i][J + 1] == a[i][j]) J++, mark[i][J] = 1;
int I = i;
while (I < n)
{
bool flag = 0;
for(int u = j; u <= J; u++) if (a[i][j] != a[I + 1][u]) {flag = 1; break;}
if (flag) break;
for(int u = j; u <= J; u++) mark[I][u] = 1;
I++;
}
//cout << i << " " << I << " " << j << " " << J << "\n";
for(int x = i; x <= I; x++) for(int y = j; y <= J; y++) {
mark[x][y] = 1;
}
//dbg(i, j);
Re[0].push_back(a[i][j]);
Re[1].push_back(i);
Re[2].push_back(I);
Re[3].push_back(j);
Re[4].push_back(J);
}
cout << Re[0].size() << "\n";
for (int i = 0; i < Re[0].size(); i++)
cout << Re[0][i] << " " << Re[1][i] << " " << Re[2][i] << " " << Re[3][i] << " " << Re[4][i] << "\n";
return 0;
}
|
[
"dhneshwod@gmail.com"
] |
dhneshwod@gmail.com
|
82b5bf759fd5720cae6fad5fa1432f473079ccf7
|
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
|
/content/browser/devtools/protocol/target_handler.cc
|
254a4ac1f18d2bf98d56f8994177e9dab1d841a7
|
[
"BSD-3-Clause"
] |
permissive
|
massnetwork/mass-browser
|
7de0dfc541cbac00ffa7308541394bac1e945b76
|
67526da9358734698c067b7775be491423884339
|
refs/heads/master
| 2022-12-07T09:01:31.027715
| 2017-01-19T14:29:18
| 2017-01-19T14:29:18
| 73,799,690
| 4
| 4
|
BSD-3-Clause
| 2022-11-26T11:53:23
| 2016-11-15T09:49:29
| null |
UTF-8
|
C++
| false
| false
| 15,389
|
cc
|
// 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 "content/browser/devtools/protocol/target_handler.h"
#include "content/browser/devtools/devtools_manager.h"
#include "content/browser/devtools/service_worker_devtools_agent_host.h"
#include "content/browser/frame_host/frame_tree.h"
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
namespace content {
namespace devtools {
namespace target {
using Response = DevToolsProtocolClient::Response;
namespace {
using ScopeAgentsMap =
std::map<GURL, std::unique_ptr<ServiceWorkerDevToolsAgentHost::List>>;
void GetMatchingHostsByScopeMap(
const ServiceWorkerDevToolsAgentHost::List& agent_hosts,
const std::set<GURL>& urls,
ScopeAgentsMap* scope_agents_map) {
std::set<base::StringPiece> host_name_set;
for (const GURL& url : urls)
host_name_set.insert(url.host_piece());
for (const auto& host : agent_hosts) {
if (host_name_set.find(host->scope().host_piece()) == host_name_set.end())
continue;
const auto& it = scope_agents_map->find(host->scope());
if (it == scope_agents_map->end()) {
std::unique_ptr<ServiceWorkerDevToolsAgentHost::List> new_list(
new ServiceWorkerDevToolsAgentHost::List());
new_list->push_back(host);
(*scope_agents_map)[host->scope()] = std::move(new_list);
} else {
it->second->push_back(host);
}
}
}
void AddEligibleHosts(const ServiceWorkerDevToolsAgentHost::List& list,
ServiceWorkerDevToolsAgentHost::Map* result) {
base::Time last_installed_time;
base::Time last_doomed_time;
for (const auto& host : list) {
if (host->version_installed_time() > last_installed_time)
last_installed_time = host->version_installed_time();
if (host->version_doomed_time() > last_doomed_time)
last_doomed_time = host->version_doomed_time();
}
for (const auto& host : list) {
// We don't attech old redundant Service Workers when there is newer
// installed Service Worker.
if (host->version_doomed_time().is_null() ||
(last_installed_time < last_doomed_time &&
last_doomed_time == host->version_doomed_time())) {
(*result)[host->GetId()] = host;
}
}
}
ServiceWorkerDevToolsAgentHost::Map GetMatchingServiceWorkers(
BrowserContext* browser_context,
const std::set<GURL>& urls) {
ServiceWorkerDevToolsAgentHost::Map result;
if (!browser_context)
return result;
ServiceWorkerDevToolsAgentHost::List agent_hosts;
ServiceWorkerDevToolsManager::GetInstance()
->AddAllAgentHostsForBrowserContext(browser_context, &agent_hosts);
ScopeAgentsMap scope_agents_map;
GetMatchingHostsByScopeMap(agent_hosts, urls, &scope_agents_map);
for (const auto& it : scope_agents_map)
AddEligibleHosts(*it.second.get(), &result);
return result;
}
scoped_refptr<TargetInfo> CreateInfo(DevToolsAgentHost* host) {
return TargetInfo::Create()
->set_target_id(host->GetId())
->set_title(host->GetTitle())
->set_url(host->GetURL().spec())
->set_type(host->GetType());
}
} // namespace
TargetHandler::TargetHandler()
: discover_(false),
auto_attach_(false),
wait_for_debugger_on_start_(false),
attach_to_frames_(false),
render_frame_host_(nullptr) {
}
TargetHandler::~TargetHandler() {
Detached();
}
void TargetHandler::SetRenderFrameHost(RenderFrameHostImpl* render_frame_host) {
render_frame_host_ = render_frame_host;
UpdateFrames();
}
void TargetHandler::SetClient(std::unique_ptr<Client> client) {
client_.swap(client);
}
void TargetHandler::Detached() {
SetAutoAttach(false, false);
SetDiscoverTargets(false);
for (const auto& id_host : attached_hosts_)
id_host.second->DetachClient(this);
attached_hosts_.clear();
}
void TargetHandler::UpdateServiceWorkers() {
UpdateServiceWorkers(false);
}
void TargetHandler::UpdateFrames() {
if (!auto_attach_ || !attach_to_frames_)
return;
HostsMap new_hosts;
if (render_frame_host_) {
FrameTreeNode* root = render_frame_host_->frame_tree_node();
std::queue<FrameTreeNode*> queue;
queue.push(root);
while (!queue.empty()) {
FrameTreeNode* node = queue.front();
queue.pop();
bool cross_process = node->current_frame_host()->IsCrossProcessSubframe();
if (node != root && cross_process) {
scoped_refptr<DevToolsAgentHost> new_host =
DevToolsAgentHost::GetOrCreateFor(node->current_frame_host());
new_hosts[new_host->GetId()] = new_host;
} else {
for (size_t i = 0; i < node->child_count(); ++i)
queue.push(node->child_at(i));
}
}
}
// TODO(dgozman): support wait_for_debugger_on_start_.
ReattachTargetsOfType(new_hosts, DevToolsAgentHost::kTypeFrame, false);
}
void TargetHandler::UpdateServiceWorkers(bool waiting_for_debugger) {
if (!auto_attach_)
return;
frame_urls_.clear();
BrowserContext* browser_context = nullptr;
if (render_frame_host_) {
// TODO(dgozman): do not traverse inside cross-process subframes.
for (FrameTreeNode* node :
render_frame_host_->frame_tree_node()->frame_tree()->Nodes()) {
frame_urls_.insert(node->current_url());
}
browser_context = render_frame_host_->GetProcess()->GetBrowserContext();
}
auto matching = GetMatchingServiceWorkers(browser_context, frame_urls_);
HostsMap new_hosts;
for (const auto& pair : matching)
new_hosts[pair.first] = pair.second;
ReattachTargetsOfType(
new_hosts, DevToolsAgentHost::kTypeServiceWorker, waiting_for_debugger);
}
void TargetHandler::ReattachTargetsOfType(
const HostsMap& new_hosts,
const std::string& type,
bool waiting_for_debugger) {
HostsMap old_hosts = attached_hosts_;
for (const auto& pair : old_hosts) {
if (pair.second->GetType() == type &&
new_hosts.find(pair.first) == new_hosts.end()) {
DetachFromTargetInternal(pair.second.get());
}
}
for (const auto& pair : new_hosts) {
if (old_hosts.find(pair.first) == old_hosts.end())
AttachToTargetInternal(pair.second.get(), waiting_for_debugger);
}
}
void TargetHandler::TargetCreatedInternal(DevToolsAgentHost* host) {
if (reported_hosts_.find(host->GetId()) != reported_hosts_.end())
return;
client_->TargetCreated(
TargetCreatedParams::Create()->set_target_info(CreateInfo(host)));
reported_hosts_[host->GetId()] = host;
}
void TargetHandler::TargetDestroyedInternal(
DevToolsAgentHost* host) {
auto it = reported_hosts_.find(host->GetId());
if (it == reported_hosts_.end())
return;
client_->TargetDestroyed(TargetDestroyedParams::Create()
->set_target_id(host->GetId()));
reported_hosts_.erase(it);
}
bool TargetHandler::AttachToTargetInternal(
DevToolsAgentHost* host, bool waiting_for_debugger) {
if (!host->AttachClient(this))
return false;
attached_hosts_[host->GetId()] = host;
client_->AttachedToTarget(AttachedToTargetParams::Create()
->set_target_info(CreateInfo(host))
->set_waiting_for_debugger(waiting_for_debugger));
return true;
}
void TargetHandler::DetachFromTargetInternal(DevToolsAgentHost* host) {
auto it = attached_hosts_.find(host->GetId());
if (it == attached_hosts_.end())
return;
host->DetachClient(this);
client_->DetachedFromTarget(DetachedFromTargetParams::Create()->
set_target_id(host->GetId()));
attached_hosts_.erase(it);
}
// ----------------- Protocol ----------------------
Response TargetHandler::SetDiscoverTargets(bool discover) {
if (discover_ == discover)
return Response::OK();
discover_ = discover;
if (discover_) {
DevToolsAgentHost::AddObserver(this);
} else {
DevToolsAgentHost::RemoveObserver(this);
RawHostsMap copy = reported_hosts_;
for (const auto& id_host : copy)
TargetDestroyedInternal(id_host.second);
}
return Response::OK();
}
Response TargetHandler::SetAutoAttach(
bool auto_attach, bool wait_for_debugger_on_start) {
wait_for_debugger_on_start_ = wait_for_debugger_on_start;
if (auto_attach_ == auto_attach)
return Response::FallThrough();
auto_attach_ = auto_attach;
if (auto_attach_) {
ServiceWorkerDevToolsManager::GetInstance()->AddObserver(this);
UpdateServiceWorkers();
UpdateFrames();
} else {
ServiceWorkerDevToolsManager::GetInstance()->RemoveObserver(this);
HostsMap empty;
ReattachTargetsOfType(empty, DevToolsAgentHost::kTypeFrame, false);
ReattachTargetsOfType(empty, DevToolsAgentHost::kTypeServiceWorker, false);
}
return Response::FallThrough();
}
Response TargetHandler::SetAttachToFrames(bool value) {
if (attach_to_frames_ == value)
return Response::OK();
attach_to_frames_ = value;
if (attach_to_frames_) {
UpdateFrames();
} else {
HostsMap empty;
ReattachTargetsOfType(empty, DevToolsAgentHost::kTypeFrame, false);
}
return Response::OK();
}
Response TargetHandler::SetRemoteLocations(
const std::vector<std::unique_ptr<base::DictionaryValue>>& locations) {
return Response::ServerError("Not supported");
}
Response TargetHandler::AttachToTarget(const std::string& target_id,
bool* out_success) {
// TODO(dgozman): only allow reported hosts.
scoped_refptr<DevToolsAgentHost> agent_host =
DevToolsAgentHost::GetForId(target_id);
if (!agent_host)
return Response::ServerError("No target with given id found");
*out_success = AttachToTargetInternal(agent_host.get(), false);
return Response::OK();
}
Response TargetHandler::DetachFromTarget(const std::string& target_id) {
auto it = attached_hosts_.find(target_id);
if (it == attached_hosts_.end())
return Response::InternalError("Not attached to the target");
DevToolsAgentHost* agent_host = it->second.get();
DetachFromTargetInternal(agent_host);
return Response::OK();
}
Response TargetHandler::SendMessageToTarget(
const std::string& target_id,
const std::string& message) {
auto it = attached_hosts_.find(target_id);
if (it == attached_hosts_.end())
return Response::FallThrough();
it->second->DispatchProtocolMessage(this, message);
return Response::OK();
}
Response TargetHandler::GetTargetInfo(
const std::string& target_id,
scoped_refptr<TargetInfo>* target_info) {
// TODO(dgozman): only allow reported hosts.
scoped_refptr<DevToolsAgentHost> agent_host(
DevToolsAgentHost::GetForId(target_id));
if (!agent_host)
return Response::InvalidParams("No target with given id found");
*target_info = CreateInfo(agent_host.get());
return Response::OK();
}
Response TargetHandler::ActivateTarget(const std::string& target_id) {
// TODO(dgozman): only allow reported hosts.
scoped_refptr<DevToolsAgentHost> agent_host(
DevToolsAgentHost::GetForId(target_id));
if (!agent_host)
return Response::InvalidParams("No target with given id found");
agent_host->Activate();
return Response::OK();
}
Response TargetHandler::CloseTarget(const std::string& target_id,
bool* out_success) {
scoped_refptr<DevToolsAgentHost> agent_host =
DevToolsAgentHost::GetForId(target_id);
if (!agent_host)
return Response::ServerError("No target with given id found");
*out_success = agent_host->Close();
return Response::OK();
}
Response TargetHandler::CreateBrowserContext(std::string* out_context_id) {
return Response::ServerError("Not supported");
}
Response TargetHandler::DisposeBrowserContext(const std::string& context_id,
bool* out_success) {
return Response::ServerError("Not supported");
}
Response TargetHandler::CreateTarget(const std::string& url,
const int* width,
const int* height,
const std::string* context_id,
std::string* out_target_id) {
DevToolsManagerDelegate* delegate =
DevToolsManager::GetInstance()->delegate();
if (!delegate)
return Response::ServerError("Not supported");
scoped_refptr<content::DevToolsAgentHost> agent_host =
delegate->CreateNewTarget(GURL(url));
if (!agent_host)
return Response::ServerError("Not supported");
*out_target_id = agent_host->GetId();
return Response::OK();
}
Response TargetHandler::GetTargets(
std::vector<scoped_refptr<TargetInfo>>* target_infos) {
for (const auto& host : DevToolsAgentHost::GetOrCreateAll())
target_infos->push_back(CreateInfo(host.get()));
return Response::OK();
}
// ---------------- DevToolsAgentHostClient ----------------
void TargetHandler::DispatchProtocolMessage(
DevToolsAgentHost* host,
const std::string& message) {
auto it = attached_hosts_.find(host->GetId());
if (it == attached_hosts_.end())
return; // Already disconnected.
client_->ReceivedMessageFromTarget(
ReceivedMessageFromTargetParams::Create()->
set_target_id(host->GetId())->
set_message(message));
}
void TargetHandler::AgentHostClosed(
DevToolsAgentHost* host,
bool replaced_with_another_client) {
client_->DetachedFromTarget(DetachedFromTargetParams::Create()->
set_target_id(host->GetId()));
attached_hosts_.erase(host->GetId());
}
// -------------- DevToolsAgentHostObserver -----------------
bool TargetHandler::ShouldForceDevToolsAgentHostCreation() {
return true;
}
void TargetHandler::DevToolsAgentHostCreated(DevToolsAgentHost* agent_host) {
DCHECK(attached_hosts_.find(agent_host->GetId()) == attached_hosts_.end());
TargetCreatedInternal(agent_host);
}
void TargetHandler::DevToolsAgentHostDestroyed(DevToolsAgentHost* agent_host) {
DCHECK(attached_hosts_.find(agent_host->GetId()) == attached_hosts_.end());
TargetDestroyedInternal(agent_host);
}
// -------- ServiceWorkerDevToolsManager::Observer ----------
void TargetHandler::WorkerCreated(
ServiceWorkerDevToolsAgentHost* host) {
BrowserContext* browser_context = nullptr;
if (render_frame_host_)
browser_context = render_frame_host_->GetProcess()->GetBrowserContext();
auto hosts = GetMatchingServiceWorkers(browser_context, frame_urls_);
if (hosts.find(host->GetId()) != hosts.end() && !host->IsAttached() &&
!host->IsPausedForDebugOnStart() && wait_for_debugger_on_start_) {
host->PauseForDebugOnStart();
}
}
void TargetHandler::WorkerReadyForInspection(
ServiceWorkerDevToolsAgentHost* host) {
if (ServiceWorkerDevToolsManager::GetInstance()
->debug_service_worker_on_start()) {
// When debug_service_worker_on_start is true, a new DevTools window will
// be opened in ServiceWorkerDevToolsManager::WorkerReadyForInspection.
return;
}
UpdateServiceWorkers(host->IsPausedForDebugOnStart());
}
void TargetHandler::WorkerVersionInstalled(
ServiceWorkerDevToolsAgentHost* host) {
UpdateServiceWorkers();
}
void TargetHandler::WorkerVersionDoomed(
ServiceWorkerDevToolsAgentHost* host) {
UpdateServiceWorkers();
}
void TargetHandler::WorkerDestroyed(
ServiceWorkerDevToolsAgentHost* host) {
UpdateServiceWorkers();
}
} // namespace target
} // namespace devtools
} // namespace content
|
[
"xElvis89x@gmail.com"
] |
xElvis89x@gmail.com
|
93e8482fa12d4d6d54a1911f5e2bed22ac6591ef
|
ba63886c2366679dbd132a1142bd55cf8870b0bf
|
/lab_03/implementation/visitor/draw_visitor/draw_visitor.cpp
|
3b5a0727a9e4488f93d60b0a0d1f166f83e7ae45
|
[] |
no_license
|
ivaaahn/bmstu-oop
|
27d2edf96584ba784e112c7b0b69b2eab00f5f6b
|
bcbf6d289f782d5104860c60eb99f5206bf3f5d9
|
refs/heads/main
| 2023-05-13T03:19:35.359648
| 2021-06-08T11:40:47
| 2021-06-08T11:40:47
| 345,132,023
| 4
| 1
| null | 2021-03-12T13:39:46
| 2021-03-06T15:51:04
| null |
UTF-8
|
C++
| false
| false
| 1,202
|
cpp
|
//
// Created by ivaaahn on 30.05.2021.
//
#include <iostream>
#include <scene/scene.hpp>
#include "draw_visitor.hpp"
#include "drawer/drawer.hpp"
#include "objects/model/model.hpp"
DrawVisitor::DrawVisitor(const std::shared_ptr<Drawer> &drawer, const std::shared_ptr<Camera> &camera) : drawer(drawer),
camera(camera) {}
void DrawVisitor::visit(const Model &model) {
auto points = model.getDetails()->getPoints();
for (const auto &edge : model.getDetails()->getEdges())
this->drawer->drawLine(
this->projectPoint(points.at(edge.getFirst())),
this->projectPoint(points.at(edge.getSecond())));
}
Point DrawVisitor::projectPoint(const Point &point) {
Point new_point(point);
Point camera_position(this->camera->getPosition());
new_point.setX(new_point.getX() - camera_position.getX());
new_point.setY(new_point.getY() - camera_position.getY());
return new_point;
}
void DrawVisitor::visit(const Camera &camera) {}
void DrawVisitor::visit(const Scene &scene) {}
void DrawVisitor::visit(const Composite &composite) {}
|
[
"ivahnencko01@gmail.com"
] |
ivahnencko01@gmail.com
|
a47f95a6251e82bc0ed72c12dc0e6b083761a4d0
|
6bc873c4067f82f34c5bad570aac02d662aeaf4c
|
/pokerGameWithComputer/computerPlayerBehavior.cpp
|
b70e0f5539191c108afcf7d21892d500f488a5f5
|
[] |
no_license
|
chouguting/PokerGameWithComputer
|
5c0a5d6c40172edbf47c46cd7ea85b7d5ec2fa42
|
ce1293e400999aa69dfcac7fb26fd41c0ad16408
|
refs/heads/master
| 2021-06-12T16:47:19.098318
| 2020-04-15T15:15:11
| 2020-04-15T15:15:11
| 254,360,385
| 0
| 0
| null | null | null | null |
BIG5
|
C++
| false
| false
| 9,747
|
cpp
|
#include <cstdio>
#include "funclib.h"
/*
main idea:先把重要的牌填到handCardTemp中,不重要的先空著(例如四條中的那四張一樣的是重要的,剩下那張不重要)
等所有重要的都牌完後再把剩下牌填入TEMP,最後再複製回去手牌
*/
void sortByComPlayer(Card* handCard, int size)
{
int hasFilled[13] = {0}; //儲存Temp牌堆中該位置有沒有填入值
Card handCardTemp[13]; //暫存用手牌(把確定的牌先填進去)
int sortIndex = size - 1; //這個index會存下一個應該填值的位置
int currentRound = 0; //第幾輪
int i, j;
int sortedIdIndex = 120; //已經整理過的牌ID會暫時被改成100多,這樣sort時他們就會在後面
int currentSize = size; //目前未整理區域的大小
//三個牌敦
for (currentRound = 0; currentRound < 3; currentRound++)
{
if (currentRound > 0)
{
sort(handCard, size); //先整理牌(第一ROUND不用)
}
//printf("\n\n");
int hasStrightFlush = 0; //有沒有同花順
int hasStright = 0; //有沒有順
int hasFlush = 0; //有沒有同花
int straightFlushCardIndex[5]; //同花順位置INDEX
int straightCardIndex[5]; //順位置 INDEX
int flushCardIndex[5]; //同花位置 INDEX
int fourOfaKindIndex = 0; //四條的位置
int hasFourOfaKind = 0; //有沒有四條
int threeOfaKindIndex = 0; //三條的位置
int hasThreeOfaKind = 0; //有沒有三條
int hasPair = 0; //有沒有對子
int pairIndex = 0; //對子的位置
int hasSecondPair = 0; //有沒有第二個對子
int secondPairIndex = 0; //第二個對子的位置
//這邊都是5張牌才會出現的牌型
if (currentRound < 2)
{
//同時抓 同花順,順,同花 的位置(如果有)
for (i = currentSize - 1; i >= 4; i--)
{
/*利用indexCurrent=4填入找到的同花順,順or同花的位置
每找到一張符合的牌indexCurrent就減一
如果indexCurrent<0的話,代表以經找到五張了(代表成立)*/
int straightFlushIndexCurrent = 4;
int straightIndexCurrent = 4;
int flushIndexCurrent = 4;
//同花順順位最大,找到就不用再找順or同花了
straightFlushCardIndex[straightFlushIndexCurrent] = i;
straightFlushIndexCurrent--;
if (hasStright == 0) //已經找到順就不用再找順了
{
straightCardIndex[straightIndexCurrent] = i;
straightIndexCurrent--;
}
if (hasFlush == 0) //已經找到同花就不用再找同花了
{
flushCardIndex[flushIndexCurrent] = i;
flushIndexCurrent--;
}
int lastFaceByStraightFlush = (handCard[i].id) / 4; //數字
int lastFace = (handCard[i].id) / 4; //數字
int lastSuit = (handCard[i].id + 1) % 4; //花色
for (j = i - 1; j >= 0; j--) //從手牌尾端開始找,這樣找到的就是最大的
{
//找同花順
if (lastFaceByStraightFlush - 1 == (handCard[j].id) / 4 && lastSuit == (handCard[j].id + 1) % 4 &&
hasStrightFlush == 0)
{
straightFlushCardIndex[straightFlushIndexCurrent] = j;
straightFlushIndexCurrent--;
lastFaceByStraightFlush = (handCard[j].id) / 4;
}
if (straightFlushIndexCurrent < 0)
{
hasStrightFlush = 1;
break;
}
//找順
if (lastFace - 1 == (handCard[j].id) / 4 && hasStright == 0)
{
straightCardIndex[straightIndexCurrent] = j;
straightIndexCurrent--;
lastFace = (handCard[j].id) / 4;
}
if (straightIndexCurrent < 0)
{
hasStright = 1;
}
//找同花
if (lastSuit == (handCard[j].id + 1) % 4 && hasFlush == 0)
{
flushCardIndex[flushIndexCurrent] = j;
flushIndexCurrent--;
}
if (flushIndexCurrent < 0)
{
hasFlush = 1;
}
}
if (hasStrightFlush == 1)
{
break;
}
}
//抓四條
for (i = currentSize - 4; i >= 0; i--)
{
if (howManyOfaKind(4, handCard + i, 4) == 1)
{
hasFourOfaKind = 1;
fourOfaKindIndex = i;
break;
}
}
}
//抓一個三條
for (i = currentSize - 3; i >= 0; i--)
{
if (howManyOfaKind(3, handCard + i, 3) == 1 && howManyOfaKind(3, handCard + i + 1, 3) == 0 && i > 0)
{
hasThreeOfaKind = 1;
threeOfaKindIndex = i;
break;
}
if (howManyOfaKind(3, handCard + i, 3) == 1 && i == 0)
{
hasThreeOfaKind = 1;
threeOfaKindIndex = i;
break;
}
}
//if (hasThreeOfaKind == 1)printf("ThreeOfaKind Index:%d\n", threeOfaKindIndex);
//抓兩個對子(第一個取小的第二個取大的)
for (i = currentSize; i >= 1; i--)
{
if (hasSecondPair == 0 && hasPair == 1 && whereIsHowManyOfaKind(2, handCard, i) != -1)
{
if (whereIsHowManyOfaKind(3, handCard, i) != whereIsHowManyOfaKind(2, handCard, i))
{
hasSecondPair = 1;
secondPairIndex = pairIndex;
}
}
if (whereIsHowManyOfaKind(2, handCard, i) != -1)
{
if (hasThreeOfaKind == 1 && threeOfaKindIndex == whereIsHowManyOfaKind(2, handCard, i))
{
}
else
{
hasPair = 1;
pairIndex = whereIsHowManyOfaKind(2, handCard, i);
}
}
}
if (pairIndex == secondPairIndex)hasSecondPair = 0;
//if (hasPair == 1)printf("pair Index:%d\n", pairIndex);
//if (hasSecondPair == 1)printf("SECOND pair Index:%d\n", secondPairIndex);
//已經找完了 開始填入CardTemp
if (currentRound < 2)
{
//順位1: 同花順
if (hasStrightFlush == 1)
{
for (i = 0; i < 5; i++)
{
handCardTemp[sortIndex] = handCard[straightFlushCardIndex[i]];
hasFilled[sortIndex] = 1;
handCard[straightFlushCardIndex[i]].id = sortedIdIndex;
sortedIdIndex = sortedIdIndex - 1;
sortIndex = sortIndex - 1;
}
currentSize = currentSize - 5;
continue;
}
//順位2: 鐵支
if (hasFourOfaKind == 1)
{
for (i = 0; i < 4; i++)
{
handCardTemp[sortIndex] = handCard[fourOfaKindIndex + i];
hasFilled[sortIndex] = 1;
handCard[fourOfaKindIndex + i].id = sortedIdIndex;
sortedIdIndex = sortedIdIndex - 1;
sortIndex = sortIndex - 1;
}
currentSize = currentSize - 4;
sortIndex--; //先空一格
continue;
}
//順位3: 葫蘆
if (hasThreeOfaKind == 1 && hasPair == 1)
{
for (i = 0; i < 3; i++)
{
handCardTemp[sortIndex] = handCard[threeOfaKindIndex + i];
hasFilled[sortIndex] = 1;
handCard[threeOfaKindIndex + i].id = sortedIdIndex;
sortedIdIndex = sortedIdIndex - 1;
sortIndex = sortIndex - 1;
}
for (i = 0; i < 2; i++)
{
handCardTemp[sortIndex] = handCard[pairIndex + i];
hasFilled[sortIndex] = 1;
handCard[pairIndex + i].id = sortedIdIndex;
sortedIdIndex = sortedIdIndex - 1;
sortIndex = sortIndex - 1;
}
currentSize = currentSize - 5;
continue;
}
//順位4: 同花
if (hasFlush == 1)
{
for (i = 0; i < 5; i++)
{
handCardTemp[sortIndex] = handCard[flushCardIndex[i]];
hasFilled[sortIndex] = 1;
handCard[flushCardIndex[i]].id = sortedIdIndex;
sortedIdIndex = sortedIdIndex - 1;
sortIndex = sortIndex - 1;
}
currentSize = currentSize - 5;
continue;
}
//順位5: 順子
if (hasStright == 1)
{
for (i = 0; i < 5; i++)
{
handCardTemp[sortIndex] = handCard[straightCardIndex[i]];
hasFilled[sortIndex] = 1;
handCard[straightCardIndex[i]].id = sortedIdIndex;
sortedIdIndex = sortedIdIndex - 1;
sortIndex = sortIndex - 1;
}
currentSize = currentSize - 5;
continue;
}
}
//順位6: 三條
if (hasThreeOfaKind == 1)
{
for (i = 0; i < 3; i++)
{
handCardTemp[sortIndex] = handCard[threeOfaKindIndex + i];
hasFilled[sortIndex] = 1;
handCard[threeOfaKindIndex + i].id = sortedIdIndex;
sortedIdIndex = sortedIdIndex - 1;
sortIndex = sortIndex - 1;
}
currentSize = currentSize - 3;
sortIndex = sortIndex - 2; //先空兩格
continue;
}
//順位7: 兩對
if (hasPair == 1 && hasSecondPair == 1)
{
for (i = 0; i < 2; i++)
{
handCardTemp[sortIndex] = handCard[pairIndex + i];
hasFilled[sortIndex] = 1;
handCard[pairIndex + i].id = sortedIdIndex;
sortedIdIndex = sortedIdIndex - 1;
sortIndex = sortIndex - 1;
}
for (i = 0; i < 2; i++)
{
handCardTemp[sortIndex] = handCard[secondPairIndex + i];
hasFilled[sortIndex] = 1;
handCard[secondPairIndex + i].id = sortedIdIndex;
sortedIdIndex = sortedIdIndex - 1;
sortIndex = sortIndex - 1; //先空一格
}
currentSize = currentSize - 4;
sortIndex = sortIndex - 1;
continue;
}
//順位8: 對子
if (hasPair == 1)
{
if (hasSecondPair == 1)
{
pairIndex = secondPairIndex;
}
for (i = 0; i < 2; i++)
{
handCardTemp[sortIndex] = handCard[pairIndex + i];
hasFilled[sortIndex] = 1;
handCard[pairIndex + i].id = sortedIdIndex;
sortedIdIndex = sortedIdIndex - 1;
sortIndex = sortIndex - 1;
}
currentSize = currentSize - 2;
sortIndex = sortIndex - 3; //先空三格
continue;
}
//順位9: 散牌
handCardTemp[sortIndex] = handCard[currentSize - 1];
hasFilled[sortIndex] = 1;
handCard[currentSize - 1].id = sortedIdIndex;
sortIndex = sortIndex - 1;
sortedIdIndex = sortedIdIndex - 1;
currentSize = currentSize - 1;
sortIndex = sortIndex - 4; //先空四格
}
//把還沒填入的牌填進TEMP的空位裡
for (i = 0; i < 13; i++)
{
for (j = 0; j < 13; j++)
{
if (hasFilled[i] == 0 && handCard[j].id < 100)
{
handCardTemp[i] = handCard[j];
hasFilled[i] = 1;
handCard[j].id = sortedIdIndex;
sortedIdIndex = sortedIdIndex - 1;
}
}
}
//把TEMP的複製回手牌
for (i = 0; i < 13; i++)
{
handCard[i] = handCardTemp[i];
}
}
|
[
"chouguting@gmail.com"
] |
chouguting@gmail.com
|
2a3c57192b3c099c76cb0dfdf1ad2a60dbeb7d43
|
485496646d476cab4106c74ded51ae82f2be3613
|
/JunQi_Zmr/JunQia/webthing.h
|
0fb2aa22601c7b12404034b281ffdda94b3a822c
|
[] |
no_license
|
DrustZ/JunQi
|
3e240c3c45e5f1ddeabd3c791ddc7fef3dc00539
|
7b2a0214e141f352652c920fa1144deb67f5717b
|
refs/heads/master
| 2020-05-26T18:00:00.346031
| 2014-09-14T15:47:03
| 2014-09-14T15:47:03
| 24,024,686
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,394
|
h
|
#ifndef WEBTHING_H
#define WEBTHING_H
#include <QObject>
#include <QVector>
#include "structs.h"
#include "windows.h"
#include "receivethread.h"
#include "sendthread.h"
class Webthing:public QObject
{
Q_OBJECT
public:
Webthing(QObject *parent = 0);
~Webthing();
void startserver(QWidget*);
void startclient(QWidget*);
void vtos();
void stov();
void swapnum(int&a, int&b);
bool sendprofile(int mode);
Receivethread *rthread;
signals:
void updateinfo(QVector<qizi>);//更新信息
void updateinitinfo(QVector<qizi>);
void kaishi();
void displayPhoto();
void displayName(QString );
void shouldrestart();
void connect_succeeded();
public slots:
void sendinfo(int mode, QVector<qizi> fangkuai);//发送信息
void getinfo(char*);
void getinitinfo(char*);
void shula();
void ye();
void yinglehaha();
void renjiaqiuhele();
void renjiatongyile();
void renjiabutongyi();
void renshulea();
void setSocket(SOCKET so);
void closed();
void started();
void shezhitouxiang(QString);
void shezhinicheng(QString);
void getupian(char* tupian);
void getname(char* name);
private:
QVector<qizi> gezi;
qizi gezizu[60];
SOCKET CSocket,Ssocket;
bool server,QH;
QWidget *qipanwidget;
QString myphotofiledir,myName,duifangname;
};
#endif // WEBTHING_H
|
[
"z1m6r3@gmail.com"
] |
z1m6r3@gmail.com
|
09c3f37221e9d71cc33c2034c9262fb74644e986
|
adb3e601acc0d6fc88eb43c5d38f37c323cca764
|
/Dynamic-Programming/0_1_knapsack_dynamic.cpp
|
0620db4626bd787c394eb447829674a75a8b3099
|
[] |
no_license
|
HEDAETUL-ISLAM/Algorithms
|
a7d6ed969765fae1051e70b102e6b80f3906a921
|
c46b07b058a36231cc4d5ef55c0a4e1723a25eea
|
refs/heads/master
| 2020-04-18T18:50:57.972252
| 2019-01-26T14:19:35
| 2019-01-26T14:19:35
| 122,783,176
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 788
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
struct item{
int value, weight;
};
int max(int a, int b){
return (a>b)?a:b ;
}
int knapsack(int w, item arr[], int n){
int result[n+1][w+1];
for(int i=0;i<=n;i++){
for(int j=0;j<=w;j++){
if(i==0 || j==0){
result[i][j] = 0;
}
else if(arr[i-1].weight<=j){
result[i][j]=max(arr[i-1].value + result[i-1][j-arr[i-1].weight], result[i-1][j]);
}
else{
result[i][j]=result[i-1][j];
}
}
}
return result[n][w];
}
int main()
{
int w,n;
cout<<"enter the size of ur entered data: ";
cin>>n;
cout<<"enter the weitht: ";
cin>>w;
item arr[100];
cout<<"enter ur value first and then weight: ";
for(int i=0;i<n;i++){
cin>>arr[i].value;
cin>>arr[i].weight;
}
cout<<"max val is: "<<knapsack(w,arr,n);
}
|
[
"bulbulhedaytul@gmail.com"
] |
bulbulhedaytul@gmail.com
|
0c471b5bea43d20be884bfa7d26f93b43054861d
|
269e4554569f5b6cbba877102f6b5b21e721a46f
|
/level A/A. Helpful Maths/main.cpp
|
9520e1618d0389117c45b734207ac7194787f4bb
|
[] |
no_license
|
KhaledAbdelgalil/sheet-mostafa-saad-problem-solving-
|
f1b289a8115579417b8f075ca4f792768e0c7e5d
|
4e2a72caeb3b3752b7170723a7190b1745d2f5e2
|
refs/heads/master
| 2022-04-02T08:48:52.967835
| 2020-02-01T03:47:27
| 2020-02-01T03:47:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 572
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
string in,out="";
int sum1=0,sum2=0,sum3=0;
cin>>in;
for(int i=0;i<in.size();i++)
{
if(in[i]=='+') continue;
if(in[i]=='1') sum1++;
else if(in[i]=='2') sum2++;
else sum3++;
}
if(sum1>0){out+='1';sum1--;}
else if(sum2>0){out+='2';sum2--;}
else if(sum3>0){out+='3';sum3--;}
for(int i=0;i<sum1;i++)
out+="+1";
for(int i=0;i<sum2;i++)
out+="+2";
for(int i=0;i<sum3;i++)
out+="+3";
cout<<out;
return 0;
}
|
[
"khaled@github.com"
] |
khaled@github.com
|
7567fb6d2881e66096918ba8b28985e2616d369c
|
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
|
/main/source/src/protocols/carbohydrates/GlycanSampler.hh
|
a7f4d76ff26f3e905a0cccbeacaa31ed8e015342
|
[] |
no_license
|
MedicaicloudLink/Rosetta
|
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
|
01affdf77abb773ed375b83cdbbf58439edd8719
|
refs/heads/master
| 2020-12-07T17:52:01.350906
| 2020-01-10T08:24:09
| 2020-01-10T08:24:09
| 232,757,729
| 2
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,162
|
hh
|
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file protocols/carbohydrates/GlycanSampler.hh
/// @brief Main mover for Glycan Relax, which optimizes glycans in a pose.
/// @author Jared Adolf-Bryfogle (jadolfbr@gmail.com) and Jason W. Labonte (JWLabonte@jhu.edu)
#ifndef INCLUDED_protocols_carbohydrates_GlycanSampler_hh
#define INCLUDED_protocols_carbohydrates_GlycanSampler_hh
// Unit headers
#include <protocols/carbohydrates/GlycanSampler.fwd.hh>
#include <protocols/carbohydrates/LinkageConformerMover.hh>
#include <protocols/moves/Mover.hh>
#include <core/pose/Pose.fwd.hh>
#include <core/kinematics/MoveMap.fwd.hh>
#include <core/scoring/ScoreFunction.fwd.hh>
#include <core/pack/task/TaskFactory.fwd.hh>
#include <core/select/residue_selector/ResidueSelector.fwd.hh>
#include <protocols/filters/Filter.fwd.hh>
#include <protocols/moves/MonteCarlo.fwd.hh>
#include <protocols/moves/MoverContainer.fwd.hh>
#include <protocols/moves/MonteCarlo.fwd.hh>
#include <protocols/simple_moves/BackboneMover.fwd.hh>
#include <protocols/minimization_packing/MinMover.fwd.hh>
#include <protocols/minimization_packing/PackRotamersMover.fwd.hh>
#include <basic/datacache/DataMap.fwd.hh>
namespace protocols {
namespace carbohydrates {
///@brief Main mover for Glycan Relax, which optimizes glycans in a pose.
/// Each round optimizes either one residue for BB sampling, linkage, or multiple for minimization.
/// Currently uses a random sampler with a set of weights to each mover for sampling.
///
/// Weights are currently as follows:
/// .40 Phi/Psi Sugar BB Sampling
/// .20 Linkage Conformer Sampling
/// .30 Small BB Sampling - equal weight to phi, psi, or omega
/// -> .17 +/- 15 degrees
/// -> .086 +/- 45 degrees
/// -> .044 +/- 90 degrees
/// .05 GlycanTreeMinMover
/// .05 PackRotamersMover
///
/// Supports Symmetry
///
class GlycanSampler : public protocols::moves::Mover {
public:
GlycanSampler();
//@brief constructor with arguments
GlycanSampler( core::select::residue_selector::ResidueSelectorCOP selector,
core::scoring::ScoreFunctionCOP scorefxn,
core::Size rounds = 75);
// copy constructor
GlycanSampler( GlycanSampler const & src );
// destructor (important for properly forward-declaring smart-pointer members)
~GlycanSampler() override;
void
apply( core::pose::Pose & pose ) override;
public:
///@brief Set the Movemap
void
set_residue_selector(core::select::residue_selector::ResidueSelectorCOP selector );
///@brief Set a ResidueSelector for glycan residue selection, instead of the typical movemap.
void
set_selector(core::select::residue_selector::ResidueSelectorCOP selector);
///@brief Set the TaskFactory to control side-chain packing of surrounding amino acids and the OH groups of the glycans.
void
set_taskfactory(core::pack::task::TaskFactoryCOP tf);
///@brief Set the ScoreFunction
void
set_scorefunction( core::scoring::ScoreFunctionCOP scorefxn);
///@brief Each round applys a random mover to pose.
/// This setting is multiplied by the number of glycan residues in the movemap for the total number of rounds
void
set_rounds( core::Size rounds);
///@brief Set how our Conformer mover samples. Default is to do uniform sampling on the conformers instead of using the population as probabilities.
void
set_population_based_conformer_sampling(bool pop_based_sampling);
///@brief Set whether if we are sampling torsions uniformly within an SD for the LinkageConformerMover (false)
/// or sampling the gaussian (true).
/// Default false
void
set_use_gaussian_sampling(bool use_gaussian_sampling);
void
set_kt( core::Real kt);
void
set_defaults();
///@brief Use Cartesian minimization instead of Dihedral minimization.
/// Default (for now) is dihedral.
void
use_cartmin( bool use_cartmin );
///@brief Set refinement mode instead of denovo modeling mode.
void
set_refine( bool refine );
///@brief set to minimize ring torsions during minimzation. Default false.
void
set_min_rings( bool min_rings);
///@brief Set the protocol to use the refactored Shear Mover for glycan torsions at 10 % probability.
/// Default false.
void
set_use_shear( bool use_shear);
///@brief Set the protocol to randomize torsions before beginning.
/// This actually helps get to lower energy models.
/// Default True. If doing refinement, this is automatically turned off.
void
set_randomize_first( bool randomize_first );
///@brief Set the number of inner cycles for BB sampling through small/sugarBB.
/// This is multiplied by the number of glycan residues
/// Default 1
void
set_inner_bb_cycles( core::Size inner_bb_cycles );
public:
void
show( std::ostream & output=std::cout ) const override;
/// @brief parse XML tag (to use this Mover in Rosetta Scripts)
void parse_my_tag(
utility::tag::TagCOP tag,
basic::datacache::DataMap & data,
protocols::filters::Filters_map const & filters,
protocols::moves::Movers_map const & movers,
core::pose::Pose const & pose ) override;
//GlycanSampler & operator=( GlycanSampler const & src );
/// @brief required in the context of the parser/scripting scheme
moves::MoverOP
fresh_instance() const override;
/// @brief required in the context of the parser/scripting scheme
protocols::moves::MoverOP
clone() const override;
bool
reinitialize_for_each_job() const override {
return true;
}
std::string
get_name() const override;
static
std::string
mover_name();
static
void
provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd );
///@brief Randomize all torsions of the subset. Used to start the protocol.
void
randomize_glycan_torsions( core::pose::Pose & pose, utility::vector1< bool > const & subset ) const;
///@brief Attempt to idealize all residues in of a set of trees. Experimental!
void
idealize_glycan_residues( core::pose::Pose & pose, utility::vector1< core::Size > const & tree_subset ) const;
public:
///@brief Get the number of glycan sampler rounds this class is set to run.
core::Size
get_glycan_sampler_rounds();
///@brief This allows us to force a number of rounds instead of doing rounds*glycan residues
void
force_total_rounds( core::Size total_rounds );
private:
void
init_objects( core::pose::Pose & pose );
void
set_cmd_line_defaults();
void
apply_to_res(
core::pose::Pose & pose,
core::Size resnum,
core::kinematics::MoveMapOP mm,
core::scoring::ScoreFunctionOP score,
core::Size round);
void
setup_default_task_factory(utility::vector1< bool > const & glycan_residues, core::pose::Pose const & pose );
void
setup_score_function();
void
setup_cartmin(core::scoring::ScoreFunctionOP scorefxn) const;
//Setup the final WeightedMover from our subsets and movemap.
void
setup_movers(
core::pose::Pose & pose,
utility::vector1< bool > const & dihedral_subset,
utility::vector1< bool > const & sugar_bb_subset,
utility::vector1< bool > const & subset);
void
setup_packer(
core::pose::Pose & pose,
utility::vector1< bool > const & full_subset );
private:
core::pack::task::TaskFactoryCOP tf_ = nullptr;
moves::MonteCarloOP mc_ = nullptr;
core::scoring::ScoreFunctionCOP scorefxn_ = nullptr;
LinkageConformerMoverOP linkage_mover_ = nullptr;
moves::RandomMoverOP weighted_random_mover_ = nullptr;
minimization_packing::MinMoverOP min_mover_ = nullptr;
minimization_packing::PackRotamersMoverOP packer_ = nullptr;
simple_moves::ShearMoverOP shear_ = nullptr;
core::Size rounds_ = 25; // cmdline
core::Real kt_ = 2.0; // cmdline
utility::vector1<std::string> accept_log_;
bool test_ = false; // cmdline
bool final_min_ = true; // cmdline
bool refine_ = false; // cmdline
core::Size total_glycan_residues_ = 0;
bool pymol_movie_ = false; // cmdline
utility::vector1< std::string > parsed_positions_;
core::Real pack_distance_ = 6.0;
bool cartmin_ = false; // cmdline
bool tree_based_min_pack_ = true; // cmdline
core::select::residue_selector::ResidueSelectorCOP selector_;
bool population_based_conformer_sampling_ = false;
bool use_gaussian_sampling_ = false;
bool min_rings_ = false;
core::Size forced_total_rounds_ = 0;
bool use_shear_ = false;
bool randomize_first_ = true;
core::Size inner_ncycles_ = 0; //For individual bb movements, multiply this by n glycans.
bool match_sampling_of_modeler_ = false; //For benchmarking
utility::vector1< bool > final_residue_subset_;
};
std::ostream &operator<< (std::ostream &os, GlycanSampler const &mover);
} //protocols
} //carbohydrates
#endif //protocols/carbohydrates_GlycanSampler_hh
|
[
"36790013+MedicaicloudLink@users.noreply.github.com"
] |
36790013+MedicaicloudLink@users.noreply.github.com
|
f27e68ee794293174119bd210f103d4bf5a6227a
|
cda0d5938517306105c9acbe33c4024849d65841
|
/main.cpp
|
54ddaa9dda6aeb3065e0b14e2220e2bf1b779d68
|
[] |
no_license
|
Jalal14/Baket-ball
|
dec9a65baf5a8fa25f0dd3e3192434adecc0787a
|
d2cab8b4b985f0ca21ba8f7ace2b4979033a261f
|
refs/heads/master
| 2020-03-15T18:26:09.672523
| 2018-05-05T20:51:06
| 2018-05-05T20:51:06
| 132,283,483
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,463
|
cpp
|
/**
ballX => ball's X coordinate
ballY => ball's Y coordinate
ballR => ball's Radius
meterA => throwing angle
meterAX => throwing angle meter X coordinate
meterAY => throwing angle meter Y coordinate
meterAR => throwing angle meter radius
meterBX => speed meter X coordinate
meterBY => speed meter Y coordinate
basketX => basket X coordinate
**/
#include <windows.h>
#include <GL/glut.h>
#include <bits/stdc++.h>
#include <unistd.h>
using namespace std;
int restart = 0;
float ballX = 230,ballY = 160,ballR = 10;
int meterA = 72, speed = 60;
int meterAX = 50, meterAY = 50, meterAR = 30;
int meterBX = 100, meterBY = 50;
float basketX = 600, basketY = 300;
clock_t timeStart;
bool startGame = false;
bool success = false, crossX = false, crossY = false, crossDisplay = false;
float successX = 0;
float currentX= 0, currentState = 0;
float degree = 0;
int bestScore = 0;
int life = 5, score = 0;
void drawBall(float x, float y, float r);
void moveBall(float x, float y, float r);
void drawBasket(int basket);
void drawAngleMeter(int degree);
void drawSpeedMeter(int height);
void drawBackground();
void myInit (void);
void myDisplay(void);
void keyListener(int key,int, int);
void draw_object();
void draw_circle(float x, float y, float w, float h);
void drawFilledCircle(GLfloat x, GLfloat y, GLfloat radius){
int i;
int triangleAmount = 20; //# of triangles used to draw circle
//GLfloat radius = 0.8f; //radius
GLfloat twicePi = 2.0f * 3.1416;
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x, y); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
x + (radius * cos(i * twicePi / triangleAmount)),
y + (radius * sin(i * twicePi / triangleAmount))
);
}
glEnd();
}
void draw_object()
{
//sky
glColor3f(0.0,0.9,0.9);
glBegin(GL_POLYGON);
glVertex2f(0,250);
glVertex2f(0,700);
glVertex2f(1100,700);
glVertex2f(1100,250);
glEnd();
//grass
glColor3f(0.0,0.9,0.0);
glBegin(GL_POLYGON);
glVertex2f(0,0);
glVertex2f(0,250);
glVertex2f(1200,250);
glVertex2f(1100,0);
glEnd();
//compound
glColor3f(0.7,0.7,0.7);
glBegin(GL_POLYGON);
glVertex2f(basketX-15,basketY-145);
glVertex2f(basketX-15,basketY-160);
glVertex2f(basketX+15,basketY-160);
glVertex2f(basketX+15,basketY-145);
glEnd();
glColor3f(1.0,1.0,1.0);
//cloud1
drawFilledCircle(50.0,400.0,20.0);
drawFilledCircle(70.0,420.0,20.5);
drawFilledCircle(80.0,390.0,21.5);
drawFilledCircle(100.0,400.0,20.0);
drawFilledCircle(120.0,420.0,20.5);
drawFilledCircle(125.0,390.0,21.5);
//cloud2
drawFilledCircle(200.0,400.0,20.0);
drawFilledCircle(220.0,420.0,20.5);
drawFilledCircle(230.0,390.0,21.5);
drawFilledCircle(250.0,400.0,20.0);
drawFilledCircle(270.0,420.0,20.5);
drawFilledCircle(280.0,390.0,21.5);
//cloud3
drawFilledCircle(400.0,400.0,20.0);
drawFilledCircle(420.0,420.0,20.5);
drawFilledCircle(430.0,390.0,21.5);
drawFilledCircle(450.0,400.0,20.0);
drawFilledCircle(470.0,420.0,20.5);
drawFilledCircle(480.0,390.0,21.5);
}
void draw_circle(float x, float y, float w, float h){
glBegin(GL_TRIANGLE_FAN);
for(int i=0; i<360; i++){
float degree = i * 3.1416 / 180.0;
glVertex2f(w*cos(degree)+x, h*sin(degree)+y);
}
glEnd();
}
void drawBackground(){
draw_object();
}
void drawBall(float x, float y, float r){
if((x > basketX-50 && x< basketX - 25) && (y> basketY-2 && y < basketY+2)){
if(success == false){
life++;
score++;
if(score>bestScore){
bestScore = score;
}
system("cls");
cout<<"score->"<<score<<"\n";
cout<<"Best score->"<<bestScore<<"\n";
}
successX = x;
success = true;
}
if(success){
x = successX;
glColor3f (1.0, 0.0, 0.0);
}
else{
glColor3f (1.0, 0.65, 0.0);
}
glBegin(GL_TRIANGLE_FAN);
for(int i=0; i<360; i++){
degree = i * 3.1416 / 180.0;
glVertex2f(r*cos(degree)+x, r*sin(degree)+y);
}
glEnd();
}
void moveBall(float x, float y, float r){
if(life<=0){
return;
}
if(!startGame){
float angle = 0;
glBegin(GL_TRIANGLE_FAN);
glColor3f (1.0, 0.65, 0.0);
if(!startGame){
for(int i=0; i<360; i++){
angle = i * 3.1416 / 180.0;
glVertex2f(ballR*cos(angle)+ballX, ballR*sin(angle)+ballY);
}
}
glEnd();
return;
}
float duration = (clock() - timeStart) / (float) CLOCKS_PER_SEC * 5;
float prX = (speed+20) * cos(meterA * 3.1416 / 180.0) * duration;
float prY = (speed+20) * sin(meterA * 3.1416 / 180.0) * duration - (0.5 * 9.8 * duration * duration);
float backX = (ballX+prX) - (basketX - 20);
if(!crossX && !crossY){
drawBall(ballX+prX, ballY+prY, r);
}else if(crossX && !crossY){
drawBall( basketX - backX, ballY+prY, r);
}else if(!crossX && crossY){
if(ballY+prY < basketY-145){
meterA = 0;
speed =0;
life--;
startGame = false;
}
else{
drawBall(currentState, basketY-145, r);
}
}else{
life--;
startGame = false;
drawBall(currentX, basketY-145, r);
meterA = 0;
speed =0;
}
if((ballX+prX < basketX - 8) && (ballX+prX > basketX - 13) && (ballY+prY < basketY + 51)){
crossX = true;
}
if(ballY+prY < basketY-145){
crossY = true;
timeStart = clock();
currentState = ballX + prX;
currentX= basketX - backX;
}
if(ballX+prX < basketX+20 && ballY+prY < basketY-145){
life--;
startGame = false;
meterA = 0;
speed =0;
}
if(ballX+prX > basketX+25 && !crossX){
life--;
startGame = false;
meterA = 0;
speed =0;
}
}
void drawLifeBar(){
int l = life;
glColor3f(1,0,0);
glBegin(GL_LINE_LOOP);
glVertex2i(50, 450);
glVertex2i(200, 450);
glVertex2i(200, 460);
glVertex2i(50, 460);
glEnd();
glBegin(GL_POLYGON);
if(life>5){
l = 5;
}
glVertex2i(50, 450);
glVertex2i(50+l*30, 450);
glVertex2i(50+l*30, 460);
glVertex2i(50, 460);
glEnd();
glColor3f(1,1,1);
glBegin(GL_LINES);
for(int i=1; i<5; i++){
glVertex2i(50+i*30, 460);
glVertex2i(50+i*30, 450);
}
glEnd();
}
void drawBasket(){
glColor3f (0.3333, 0.3333, 0.3333);
glBegin(GL_POLYGON);
glVertex2i(basketX, basketY+3);
glVertex2i(basketX-20, basketY+3);
glVertex2i(basketX-20, basketY-2);
glVertex2i(basketX, basketY-2);
glVertex2i(basketX, basketY-150);
glVertex2i(basketX+5, basketY-150);
glVertex2i(basketX+5, basketY+50);
glVertex2i(basketX, basketY+50);
glEnd();
float degree = 0;
glBegin(GL_POINTS);
for(int i=0; i<360; i++){
degree = i * 3.1416 / 180.0;
glVertex2f(20*cos(degree)+basketX-39, 7*sin(degree)+basketY);
}
glEnd();
}
void drawAngleMeter(int degree){
glColor3f (1.0, 0.0, 0.0);
float angle = 0;
glBegin(GL_POINTS);
for(int i=0; i<180; i++){
angle = i * 3.1416 / 180.0;
glVertex2f(meterAR*cos(angle)+meterAX, meterAR*sin(angle)+meterAY);
}
glEnd();
float rad = degree * 3.1416 / 180.0;
float x = meterAR*cos(rad) + meterAX;
float y = meterAR*sin(rad) + meterAY;
glBegin(GL_LINES);
glVertex2f(meterAX,meterAY);
glVertex2f(x, y);
glEnd();
}
void drawSpeedMeter(int height){
glColor3f (1.0, 0.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(meterBX ,meterBY);
glVertex2f(meterBX + 10,meterBY);
glVertex2f(meterBX + 10,meterBY + 100);
glVertex2f(meterBX ,meterBY + 100);
glEnd();
glBegin(GL_POLYGON);
glVertex2f(meterBX ,meterBY );
glVertex2f(meterBX + 10,meterBY);
glVertex2f(meterBX + 10,meterBY + height);
glVertex2f(meterBX , meterBY + height);
//glVertex2f(meterBX , meterBY);
glEnd();
}
void myInit (void)
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glColor3f(0.0f, 0.0f, 0.0f);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
void myDisplay(void)
{
glClear (GL_COLOR_BUFFER_BIT);
drawBackground();
drawBasket();
moveBall(ballX,ballY,ballR);
drawAngleMeter(meterA);
drawSpeedMeter(speed);
drawLifeBar();
glFlush();
glutPostRedisplay();
}
void restartGame(unsigned char key, int ,int){
switch(key){
case 'r':{
if(!life){
life = 5;
score = 0;
startGame = false;
crossX = crossY = success = false;
}
break;
}
case ' ' : {
if(!startGame){
startGame = true;
timeStart = clock();
crossX = crossY = success = false;
break;
}
}
}
}
void keyListener(int key,int, int){
switch(key){
case GLUT_KEY_LEFT: {
if(!startGame){
meterA++;
if(meterA > 90){
meterA=90;
}
}
break;
}
case GLUT_KEY_RIGHT:{
if(!startGame){
meterA--;
if(meterA < 0){
meterA=0;
}
}
break;
}
case GLUT_KEY_UP: {
if(!startGame){
speed++;
if(speed>100){
speed = 100;
}
}
break;
}
case GLUT_KEY_DOWN: {
if(!startGame){
speed--;
if(speed<0){
speed = 0;
}
} break;
}
case GLUT_KEY_END: {
if(life<=0){
exit(0);
}
}
}
}
int main(int argc, char** argv)
{
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (1080, 810);
glutInitWindowPosition (200, 200);
glutCreateWindow ("Basketball");
myInit();
glutDisplayFunc(myDisplay);
glutSpecialFunc(keyListener);
glutKeyboardFunc(restartGame);
glutMainLoop();
}
|
[
"jalaluddin_csse14@yahoo.com"
] |
jalaluddin_csse14@yahoo.com
|
a6049440b285bea6100c834f1cf2b149a455e9cb
|
c85657463ea896571f28aaead3825b52baf199bd
|
/devices/vortex6000/src/vortex6000Main.cpp
|
7683f3138e560974554c4926fc46083ed7e6fbad
|
[] |
no_license
|
jasonhogan/sti
|
ffc9469557bf1480aae4004321d261bb5473e237
|
928428767b8c4131fa342dbbc2bf2e5cbea7340a
|
refs/heads/master
| 2021-07-12T17:55:26.696064
| 2020-08-10T20:56:56
| 2020-08-10T20:56:56
| 19,015,405
| 1
| 1
| null | 2018-04-04T03:14:44
| 2014-04-22T03:09:49
|
C++
|
UTF-8
|
C++
| false
| false
| 1,541
|
cpp
|
/*! \file gpib_hub_main.cpp
* \author David M.S. Johnson
* \brief main()
* \section license License
*
* Copyright (C) 2009 David Johnson <david.m.johnson@stanford.edu>\n
* This file is part of the Stanford Timing Interface (STI).
*
* The STI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The STI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the STI. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <iostream>
#include <ORBManager.h>
#include "vortex6000Device.h"
using namespace std;
ORBManager* orbManager;
int main(int argc, char **argv)
{
orbManager = new ORBManager(argc, argv);
unsigned short gpibAddressMaster = 1;
unsigned short gpibAddressSlave = 2;
//unsigned short module = gpibAddress;
vortex6000Device scanningVortex(orbManager, "Scanning Vortex", "eplittletable.stanford.edu", gpibAddressSlave, gpibAddressSlave, false);
vortex6000Device masterVortex(orbManager, "Vortex6000", "eplittletable.stanford.edu", gpibAddressMaster, gpibAddressMaster, true);
orbManager->run();
return 0;
}
|
[
"EP@8bcac300-4d60-4aec-84ba-b7489f70e69b"
] |
EP@8bcac300-4d60-4aec-84ba-b7489f70e69b
|
a88bce9d67b83a99fc6eaabd299cf32b3f1ed2bb
|
af5bd30d59fec67fcb32930896615272c453f379
|
/255.cpp
|
21ec3518ba416cad9a29b0de67ca3216be186011
|
[] |
no_license
|
FuHongbao/OJ_Code
|
e656e970855661f0b0d4e5ea719eed5b020903c5
|
bf54e32ceb4468dc15e8251e83317c03e16b8888
|
refs/heads/master
| 2020-08-04T23:56:12.680917
| 2019-10-02T11:28:17
| 2019-10-02T11:28:17
| 212,321,572
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,147
|
cpp
|
/*************************************************************************
> File Name: 255.cpp
> Author: victoria
> Mail: 1105847344@qq.com
> Created Time: 2019年06月29日 星期六 19时56分56秒
************************************************************************/
#include <iostream>
#include <algorithm>
#include <string.h>
#include <cmath>
using namespace std;
#define MAX_N 1000
struct Range {
double l, r;
}arr[MAX_N + 5];
bool cmp(struct Range a, struct Range b) {
if (a.r != b.r) return a.r < b.r;
return a.l > b.l;
}
int main() {
int n;
double d;
cin >> n >> d;
double flag = 0;
for (int i = 0; i < n ; i++) {
double x, y;
cin >> x >> y;
if (y > d) flag = 1;
arr[i].l = x - sqrt(d*d - y*y);
arr[i].r = x + sqrt(d*d - y*y);
}
if (flag) {
cout << "-1" <<endl;
return 0;
}
sort(arr, arr + n, cmp);
int ans = 1;
double index = arr[0].r;
for(int i = 1; i < n; i++) {
if (arr[i].l > index) {
index = arr[i].r;
ans += 1;
}
}
cout << ans << endl;
return 0;
}
|
[
"FuHongbao@FuHongbao.com"
] |
FuHongbao@FuHongbao.com
|
e4e3ea29491d4c59cc27cfd64909e23ac8a19be2
|
75860ed58e19ee7b724428a6e99419213d3e3906
|
/src/Lists/PersistedObjectListController.hpp
|
4dec2ca1933b846662e0b8a5f3e3e62cb6cce9ab
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
nobrick/mymonero-libapp-cpp
|
2d5279dc32b0d17c190144be8c0cee6361acdc66
|
c85b24d99e07e893c98d1af83ce24f0057269c2c
|
refs/heads/master
| 2020-05-31T23:06:38.879877
| 2019-05-20T21:37:03
| 2019-05-20T21:37:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,906
|
hpp
|
//
// PersistedObjectListController.hpp
// MyMonero
//
// Copyright (c) 2014-2019, MyMonero.com
//
// 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.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
#ifndef PersistedObjectListController_hpp
#define PersistedObjectListController_hpp
#include <string>
#include <boost/optional/optional.hpp>
#include <boost/signals2.hpp>
#include <boost/uuid/uuid.hpp> // uuid class
#include <boost/uuid/uuid_generators.hpp> // generators
#include <memory>
#include "../Persistence/document_persister.hpp"
#include "../Persistence/PersistableObject.hpp"
#include "../Dispatch/Dispatch_Interface.hpp"
#include "../Passwords/PasswordController.hpp"
namespace Lists
{
using namespace std;
using namespace boost;
using namespace document_persister;
//
// Comparators
static inline bool comparePersistableObjectSharedPtrBy_insertedAt_asc(
std::shared_ptr<Persistable::Object> l,
std::shared_ptr<Persistable::Object> r
) {
if (l->insertedAt_sSinceEpoch == none) {
return false;
}
if (r->insertedAt_sSinceEpoch == none) {
return true;
}
return *(l->insertedAt_sSinceEpoch) <= *(r->insertedAt_sSinceEpoch);
}
//
// Controllers
class Controller:
public Passwords::DeleteEverythingRegistrant,
public Passwords::ChangePasswordRegistrant
{
public:
//
// Lifecycle - Init
Controller(const CollectionName &collectionName):
_listedObjectTypeCollectionName(collectionName) // copy
{
// set dependencies then call setup()
}
Controller(const Controller&) = delete; // disable copy constructor to prevent inadvertent temporary in pointer
Controller& operator=(const Controller&) = delete;
virtual ~Controller()
{
cout << "Destructing a ListController" << endl;
tearDown();
}
//
// Dependencies
std::shared_ptr<string> documentsPath;
std::shared_ptr<Dispatch::Dispatch> dispatch_ptr;
std::shared_ptr<Passwords::Controller> passwordController;
// Then call:
void setup();
//
virtual std::shared_ptr<Lists::Controller> get_shared_ptr_from_this() = 0; // Child classes must override and implement this with shared_from_this() and by inheriting std::enabled_shared_from_this<Child>
//
virtual void overridable_deferBootUntil( // overridable
std::function<void(optional<string> err_str)> fn
) {
fn(boost::none); // make sure to call this
}
//
// Signals
boost::signals2::signal<void()> boot__did_signal;
boost::signals2::signal<void()> boot__failed_signal;
boost::signals2::signal<void()> list__updated_signal;
boost::signals2::signal<void()> record__deleted_signal;
//
// Protocols - PasswordControllerEventParticipant
std::string identifier() const
{
return uuid_string;
}
//
// Accessors
std::vector<std::shared_ptr<Persistable::Object>> records()
{ // accessing within the mutex and returning a copy so as to resolve possible mutability and consistency issues
// TODO: is this too expensive? are the pointers themselves being copied?
_records_mutex.lock();
auto r_copy = _records;
_records_mutex.unlock();
return r_copy;
}
bool hasBooted() const { return _hasBooted; }
//
// Accessors - Override
virtual std::shared_ptr<Persistable::Object> new_record(
std::shared_ptr<std::string> documentsPath,
std::shared_ptr<Passwords::PasswordProvider> passwordProvider,
const document_persister::DocumentJSON &plaintext_documentJSON
) = 0;
//
// Accessors - Overridable
virtual bool overridable_shouldSortOnEveryRecordAdditionAtRuntime()
{
return false; // default
}
virtual bool overridable_wantsRecordsAppendedNotPrepended()
{
return false; // default
}
//
// Imperatives - Execution Deferment
void onceBooted(std::function<void()> fn);
//
// Imperatives - CRUD
optional<string> givenBooted_delete(Persistable::Object &object);
optional<string> givenBooted_delete_noListUpdatedNotify(Persistable::Object &object);
//
// Imperatives - Overridable
virtual void overridable_finalizeAndSortRecords() {}
//
// Delegation - Overridable
virtual void overridable_booting_didReconstitute(std::shared_ptr<Persistable::Object> listedObjectInstance) {} // somewhat intentionally ignores errors and values which would be returned asynchronously, e.g. by way of a callback/block
//
// Delegation - Updates
void _atRuntime__record_wasSuccessfullySetUp(std::shared_ptr<Persistable::Object> listedObject); // this is to be called by subclasses
void _atRuntime__lockMutexAnd_record_wasSuccessfullySetUp_noSortNoListUpdated(std::shared_ptr<Persistable::Object> listedObject);
//
protected:
bool _hasBooted = false;
std::vector<std::shared_ptr<Persistable::Object>> _records;
std::mutex _records_mutex;
//
// Lifecycle
void setup_startObserving();
void tearDown();
void stopObserving();
//
// Delegation
void _listUpdated_records();
void __dispatchAsync_listUpdated_records();
//
private:
//
// Properties - Instance members
std::string uuid_string = boost::uuids::to_string((boost::uuids::random_generator())()); // cached
const CollectionName _listedObjectTypeCollectionName;
//
boost::signals2::connection connection__PasswordController_willDeconstructBootedStateAndClearPassword;
boost::signals2::connection connection__PasswordController_didDeconstructBootedStateAndClearPassword;
//
// Lifecycle
void setup_tryToBoot();
void startObserving_passwordController();
void setup_fetchAndReconstituteExistingRecords();
void _setup_didBoot();
void _setup_didFailToBoot(const string &err_str);
//
void _stopObserving_passwordController();
//
// Accessors
errOr_documentIds _new_idsOfPersistedRecords();
//
// Execution deferment
void _callAndFlushAllBlocksWaitingForBootToExecute();
optional<vector<std::function<void()>>> __blocksWaitingForBootToExecute = none;
//
// CRUD
void _removeFromList(Persistable::Object &object);
void _removeFromList_noListUpdatedNotify(Persistable::Object &object);
//
// Protocols - DeleteEverythingRegistrant
optional<string> passwordController_DeleteEverything();
// Protocols - ChangePasswordRegistrant
optional<Passwords::EnterPW_Fn_ValidationErr_Code> passwordController_ChangePassword();
//
// Delegation - Notifications
void PasswordController_willDeconstructBootedStateAndClearPassword();
void PasswordController_didDeconstructBootedStateAndClearPassword();
};
}
#endif /* PersistedObjectListController_hpp */
|
[
"paulshapiro@users.noreply.github.com"
] |
paulshapiro@users.noreply.github.com
|
f34d7e2116c7eb7994519a3c2df83117a47ee80b
|
304dcc859ff1bad63ae881a096e687f7dc3de04b
|
/Test_PC_Poker/framework_externals/ExternalLib/Camel.Base/include/Camel/Base/System/SharedPtr.h
|
2b0b2a9e67d15ce784bbd8afe7ecbfa39ca5958c
|
[] |
no_license
|
idh37/testrepo
|
03e416b115563cf62a4436f7a278eda2cd05d115
|
b07cdd22bd42356522a599963f031a6294e14065
|
refs/heads/master
| 2020-07-11T00:57:34.526556
| 2019-09-10T07:22:35
| 2019-09-10T07:22:35
| 204,413,346
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,652
|
h
|
#ifndef __Camel_Base_System_TPL_SharedPtr__
#define __Camel_Base_System_TPL_SharedPtr__
#include "SystemBase.h"
#include "MPHeap.h"
#include "Interlocked.h"
#include <algorithm>
#include <cassert>
_DECLARE_NAMESPACE_CAMEL_BASE_SYSTEM_
namespace TPL
{
template<typename T>
class SharedPtr
{
private:
T *p_;
unsigned int *count_;
private:
template<typename U> friend class SharedPtr;
public:
SharedPtr(void)
: p_(NULL),
count_(static_cast<unsigned int *>(MPHeap::Alloc(NULL, sizeof(unsigned int))))
{
if (count_ == NULL)
{
throw std::bad_alloc();
}
*count_ = 1;
}
explicit SharedPtr(T *p)
: p_(p),
count_(static_cast<unsigned int *>(MPHeap::Alloc(NULL, sizeof(unsigned int))))
{
if (count_ == NULL)
{
throw std::bad_alloc();
}
*count_ = 1;
}
SharedPtr(const SharedPtr &rhs)
: p_(rhs.p_),
count_(rhs.count_)
{
Threading::Interlocked::Increment(rhs.count_);
}
template<typename U>
SharedPtr(const SharedPtr<U> &rhs)
: p_(rhs.p_),
count_(rhs.count_)
{
Threading::Interlocked::Increment(rhs.count_);
}
~SharedPtr(void)
{
if (Threading::Interlocked::Decrement(count_) == 0)
{
MPHeap::Free(NULL, count_);
count_ = NULL;
delete p_;
p_ = NULL;
}
}
void Reset(void)
{
SharedPtr().Swap(*this);
}
template<typename U>
void Reset(U *p)
{
assert(p == 0 || p != p_); // catch self-reset errors
SharedPtr(p).Swap(*this);
}
void Swap(SharedPtr &rhs)
{
std::swap(p_, rhs.p_);
std::swap(count_, rhs.count_);
}
T *GetRawPtr(void) const
{
return p_;
}
T *operator->() const
{
return p_;
}
T &operator*() const
{
return *p_;
}
friend bool operator==(const SharedPtr<T>& rhs, const SharedPtr<T>& lhs)
{
return (rhs.GetRawPtr() == lhs.GetRawPtr());
}
bool operator!() const // Enables "if (!sp) ..."
{
return p_ == NULL;
}
SharedPtr &operator=(const SharedPtr &rhs)
{
SharedPtr(rhs).Swap(*this);
return *this;
}
template<typename U>
SharedPtr &operator=(const SharedPtr<U> &rhs)
{
SharedPtr(rhs).Swap(*this);
return *this;
}
SharedPtr<T> lock() const
{
SharedPtr<T> result;
if (p_ != NULL)
{
int old_count;
do
{
old_count = *count_;
if (old_count == 0)
{
break;
}
}
while (old_count != Threading::Interlocked::CompareExchange(count_, old_count + 1, old_count));
if (old_count > 0)
{
result.p_ = p_;
result.count_ = count_;
}
}
return result;
}
};
}
_UNDECLARE_NAMESPACE_CAMEL_BASE_SYSTEM_
#endif // __Camel_Base_System_TPL_SharedPtr__
|
[
"idh37@nm-4ones.com"
] |
idh37@nm-4ones.com
|
a4b8f935525aae61c4667c606f99c420655aae27
|
304fc20348614ff58f8ec11a012b4a464a5ddf35
|
/include/processor.h
|
f4b43a9d4e6bd182192cc87db084581897063cb4
|
[
"MIT"
] |
permissive
|
Abdo-1992/system-monitor
|
b431b2ac0e8c2cbc7e33ad8e5fb1b643681cc82c
|
e9f18f38e8e3e535fbfc7ab405bbc5c40c339d10
|
refs/heads/main
| 2023-02-04T14:06:06.279075
| 2020-12-20T20:19:56
| 2020-12-20T20:19:56
| 322,738,406
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 572
|
h
|
#ifndef PROCESSOR_H
#define PROCESSOR_H
#include <unistd.h>
#include <cctype>
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
#include "linux_parser.h"
#include "process.h"
class Processor {
public:
float Utilization(); // TODO: See src/processor.cpp
void Utilization(float) ;
void calculateUtil() ;
// TODO: Declare any necessary private members
private:
float UtilizationValue ;
long long int prevuser{0}, prevnice{0}, prevsystem{0}, previrq{0}, prevsoftirq{0}, prevsteal{0}, previdle{0} , previowait{0};
};
#endif
|
[
"abdulrahman.tharwat.92@gmail.com"
] |
abdulrahman.tharwat.92@gmail.com
|
8f2b69d618ed9a213c980a75ab8d10cf8803bfcd
|
6d0386587c23b9a9374813f30fef10cac55aa4d8
|
/gunhound/src/gunhound/vii_src/Enemy/HoundsEnemy/CEneH0008BloodSocker.h
|
8ad9b8ec9316dbc266510ecfeac8b3e2f2e6cb83
|
[] |
no_license
|
t-mat/gunhound-easybuild
|
5b3c136205917a53a5d438b0498c7ead992e2416
|
e5c6d8fc792ea0aebf86c1743375b9356c2087bb
|
refs/heads/master
| 2020-04-06T07:09:37.246153
| 2016-09-10T19:00:32
| 2016-09-10T19:00:32
| 65,155,314
| 3
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 3,035
|
h
|
//--------------------------------------------------------------------------------
//
// Stage00:ボルゾイ(ブラッドサッカー)
//
//--------------------------------------------------------------------------------
class CAtkH0001Thunder;
class CEneH0008BloodSocker : public CEnemyBase , public CHoundEnemyBase
{
public:
CEneH0008BloodSocker( Sint32 x, Sint32 y );
~CEneH0008BloodSocker();
void SeqInit();
void SeqMain();
void SeqCrash();
void Draw();
//ボルゾイのカスタマイズ
void SetCustomIndex(Sint32 n);
private:
enum
{
enWeaponMax = 8,
};
//初期化
void SetInitialize();
void SetCustomize( Sint32 sBody ,Sint32 sArm , Sint32 sLeg);
void SetArms();
void WeaponReset();
//攻撃
void Atack( Sint32 sAtk );
//毎フレームの処理
void ActionMain();
//腕角度補正
void AdjustArmAngle( Sint32 ax , Sint32 ay ,Sint32 sOffset=0);
//武器チェンジ可能か?
gxBool IsWeaponChangeChance();
//-----------------------------
//攻撃
//-----------------------------
void AtackShortBurrel(); //クラッシャーを乱射
void AtackLongBurrel(); //実弾を狙い撃ちしてくる
void AtackSolidShooter(); //狙い撃ちバズーカ
void AtackShoulderMissilePod(); //追尾式ミサイル
void AtackLogGun(); //溜め打ち極太レーザー
void AtackLegPod(); //2連式巡航ミニミサイル
void AtackBodyCrasher(); //2連式巡航ミニミサイル
//-----------------------------
//ロジック制御関連
//-----------------------------
void LogicAI();
void PadControl(Sint32 n);
//-----------------------------
//パーツ番号管理用
//-----------------------------
Sint32 m_sBody;
Sint32 m_sLegs;
Sint32 m_sArms;
//-----------------------------
//攻撃制御関連
//-----------------------------
Sint32 m_sWeapon[enWeaponMax]; //武器番号保存用
Sint32 m_sWeaponNum; //手持ちの武器の数
Sint32 m_sMainWeapon; //現在選択中の武器
Sint32 m_sBackWait; //ノックバック時間
Sint32 m_sReboundWait; //バズーカ腕のリバウンド処理
Sint32 m_sTargetSeq; //ターゲット方向補正制御
Sint32 m_sArmRotation; //ターゲット方向補正用アーム角度
Sint32 m_sCrashTimer; //破壊されるまでのタイムラグ
gxBool m_bGuard; //ガード属性判定
gxBool m_bArmCrash; //アームクラッシュ
//CEffAtkLaser *m_pLaser; //レーザー制御用
CAtkH0001Thunder *m_pLaser;
gxBool m_bLaser;
//-----------------------------
//ロジック制御関連
//-----------------------------
Sint32 m_sPushControl;
Sint32 m_sTrigControl;
Sint32 m_sAtackLag; //射撃間のタイムラグ
Sint32 m_sAtackCnt; //攻撃回数
//-----------------------------
//その他
//-----------------------------
OBJ_POS_T m_Src; //初期位置
OBJ_POS_T m_Grd; //初期位置
CHitCollision m_HitKurai;
CHitCollision m_HitGuard; //ガード用
CEasyLeynos m_Leynos;
gxBool m_bSpecialVersion;
gxBool m_bEscaped;
};
|
[
"takayuki.matsuoka@gmail.com"
] |
takayuki.matsuoka@gmail.com
|
204345df446013c891d2cb0e9d0c583c2ea4aa4b
|
331140b484a3d91ed11b6aa70160e926ef249c38
|
/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfspp/lib/bindings/c/hdfs.cc
|
9a7c8b4ddba7e7931c3158389224919579ede39a
|
[
"LicenseRef-scancode-unknown",
"GPL-2.0-only",
"Apache-2.0",
"BSD-2-Clause",
"BSD-2-Clause-Views",
"LGPL-2.1-only",
"MPL-2.0",
"MPL-2.0-no-copyleft-exception",
"AGPL-3.0-only",
"BSD-3-Clause",
"LicenseRef-scancode-jdom",
"CDDL-1.1",
"LicenseRef-scancode-proprietary-license",
"CDDL-1.0",
"LicenseRef-scancode-protobuf",
"EPL-1.0",
"CC-BY-3.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-2.5",
"Classpath-exception-2.0",
"LicenseRef-scancode-other-permissive",
"GCC-exception-3.1",
"LicenseRef-scancode-public-domain",
"CC-PDDC",
"CC0-1.0"
] |
permissive
|
bazaarvoice/hadoop
|
2d7bf98b77bfc8b0197d82cc51953d5740deb8e0
|
8ab776d61e569c12ec62024415ff68e5d3b10141
|
refs/heads/trunk
| 2023-08-02T04:11:26.273318
| 2018-04-10T18:42:54
| 2018-04-10T18:42:54
| 128,986,787
| 0
| 1
|
Apache-2.0
| 2022-07-05T09:37:27
| 2018-04-10T19:46:27
|
Java
|
UTF-8
|
C++
| false
| false
| 51,539
|
cc
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hdfspp/hdfspp.h"
#include "fs/filesystem.h"
#include "common/hdfs_configuration.h"
#include "common/configuration_loader.h"
#include "common/logging.h"
#include <hdfs/hdfs.h>
#include <hdfspp/hdfs_ext.h>
#include <libgen.h>
#include "limits.h"
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace hdfs;
using std::experimental::nullopt;
using namespace std::placeholders;
static constexpr tPort kDefaultPort = 8020;
/** Annotate what parts of the code below are implementatons of API functions
* and if they are normal vs. extended API.
*/
#define LIBHDFS_C_API
#define LIBHDFSPP_EXT_API
/* Separate the handles used by the C api from the C++ API*/
struct hdfs_internal {
hdfs_internal(FileSystem *p) : filesystem_(p), working_directory_("/") {}
hdfs_internal(std::unique_ptr<FileSystem> p)
: filesystem_(std::move(p)), working_directory_("/") {}
virtual ~hdfs_internal(){};
FileSystem *get_impl() { return filesystem_.get(); }
const FileSystem *get_impl() const { return filesystem_.get(); }
std::string get_working_directory() {
std::lock_guard<std::mutex> read_guard(wd_lock_);
return working_directory_;
}
void set_working_directory(std::string new_directory) {
std::lock_guard<std::mutex> write_guard(wd_lock_);
working_directory_ = new_directory;
}
private:
std::unique_ptr<FileSystem> filesystem_;
std::string working_directory_; //has to always start and end with '/'
std::mutex wd_lock_; //synchronize access to the working directory
};
struct hdfsFile_internal {
hdfsFile_internal(FileHandle *p) : file_(p) {}
hdfsFile_internal(std::unique_ptr<FileHandle> p) : file_(std::move(p)) {}
virtual ~hdfsFile_internal(){};
FileHandle *get_impl() { return file_.get(); }
const FileHandle *get_impl() const { return file_.get(); }
private:
std::unique_ptr<FileHandle> file_;
};
/* Keep thread local copy of last error string */
thread_local std::string errstr;
/* Fetch last error that happened in this thread */
LIBHDFSPP_EXT_API
int hdfsGetLastError(char *buf, int len) {
//No error message
if(errstr.empty()){
return -1;
}
//There is an error, but no room for the error message to be copied to
if(nullptr == buf || len < 1) {
return -1;
}
/* leave space for a trailing null */
size_t copylen = std::min((size_t)errstr.size(), (size_t)len);
if(copylen == (size_t)len) {
copylen--;
}
strncpy(buf, errstr.c_str(), copylen);
/* stick in null */
buf[copylen] = 0;
return 0;
}
/* Event callbacks for next open calls */
thread_local std::experimental::optional<fs_event_callback> fsEventCallback;
thread_local std::experimental::optional<file_event_callback> fileEventCallback;
struct hdfsBuilder {
hdfsBuilder();
hdfsBuilder(const char * directory);
virtual ~hdfsBuilder() {}
ConfigurationLoader loader;
HdfsConfiguration config;
optional<std::string> overrideHost;
optional<tPort> overridePort;
optional<std::string> user;
static constexpr tPort kUseDefaultPort = 0;
};
/* Error handling with optional debug to stderr */
static void ReportError(int errnum, const std::string & msg) {
errno = errnum;
errstr = msg;
#ifdef LIBHDFSPP_C_API_ENABLE_DEBUG
std::cerr << "Error: errno=" << strerror(errnum) << " message=\"" << msg
<< "\"" << std::endl;
#else
(void)msg;
#endif
}
/* Convert Status wrapped error into appropriate errno and return code */
static int Error(const Status &stat) {
const char * default_message;
int errnum;
int code = stat.code();
switch (code) {
case Status::Code::kOk:
return 0;
case Status::Code::kInvalidArgument:
errnum = EINVAL;
default_message = "Invalid argument";
break;
case Status::Code::kResourceUnavailable:
errnum = EAGAIN;
default_message = "Resource temporarily unavailable";
break;
case Status::Code::kUnimplemented:
errnum = ENOSYS;
default_message = "Function not implemented";
break;
case Status::Code::kException:
errnum = EINTR;
default_message = "Exception raised";
break;
case Status::Code::kOperationCanceled:
errnum = EINTR;
default_message = "Operation canceled";
break;
case Status::Code::kPermissionDenied:
errnum = EACCES;
default_message = "Permission denied";
break;
case Status::Code::kPathNotFound:
errnum = ENOENT;
default_message = "No such file or directory";
break;
case Status::Code::kNotADirectory:
errnum = ENOTDIR;
default_message = "Not a directory";
break;
case Status::Code::kFileAlreadyExists:
errnum = EEXIST;
default_message = "File already exists";
break;
case Status::Code::kPathIsNotEmptyDirectory:
errnum = ENOTEMPTY;
default_message = "Directory is not empty";
break;
case Status::Code::kInvalidOffset:
errnum = Status::Code::kInvalidOffset;
default_message = "Trying to begin a read past the EOF";
break;
default:
errnum = ENOSYS;
default_message = "Error: unrecognised code";
}
if (stat.ToString().empty())
ReportError(errnum, default_message);
else
ReportError(errnum, stat.ToString());
return -1;
}
static int ReportException(const std::exception & e)
{
return Error(Status::Exception("Uncaught exception", e.what()));
}
static int ReportCaughtNonException()
{
return Error(Status::Exception("Uncaught value not derived from std::exception", ""));
}
/* return false on failure */
bool CheckSystem(hdfsFS fs) {
if (!fs) {
ReportError(ENODEV, "Cannot perform FS operations with null FS handle.");
return false;
}
return true;
}
/* return false on failure */
bool CheckHandle(hdfsFile file) {
if (!file) {
ReportError(EBADF, "Cannot perform FS operations with null File handle.");
return false;
}
return true;
}
/* return false on failure */
bool CheckSystemAndHandle(hdfsFS fs, hdfsFile file) {
if (!CheckSystem(fs))
return false;
if (!CheckHandle(file))
return false;
return true;
}
optional<std::string> getAbsolutePath(hdfsFS fs, const char* path) {
//Does not support . (dot) and .. (double dot) semantics
if (!path || path[0] == '\0') {
Error(Status::InvalidArgument("getAbsolutePath: argument 'path' cannot be NULL or empty"));
return optional<std::string>();
}
if (path[0] != '/') {
//we know that working directory always ends with '/'
return fs->get_working_directory().append(path);
}
return optional<std::string>(path);
}
/**
* C API implementations
**/
LIBHDFS_C_API
int hdfsFileIsOpenForRead(hdfsFile file) {
/* files can only be open for reads at the moment, do a quick check */
if (!CheckHandle(file)){
return 0;
}
return 1; // Update implementation when we get file writing
}
LIBHDFS_C_API
int hdfsFileIsOpenForWrite(hdfsFile file) {
/* files can only be open for reads at the moment, so return false */
CheckHandle(file);
return -1; // Update implementation when we get file writing
}
int hdfsConfGetLong(const char *key, int64_t *val)
{
try
{
errno = 0;
hdfsBuilder builder;
return hdfsBuilderConfGetLong(&builder, key, val);
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
hdfsFS doHdfsConnect(optional<std::string> nn, optional<tPort> port, optional<std::string> user, const Options & options) {
try
{
errno = 0;
IoService * io_service = IoService::New();
FileSystem *fs = FileSystem::New(io_service, user.value_or(""), options);
if (!fs) {
ReportError(ENODEV, "Could not create FileSystem object");
return nullptr;
}
if (fsEventCallback) {
fs->SetFsEventCallback(fsEventCallback.value());
}
Status status;
if (nn || port) {
if (!port) {
port = kDefaultPort;
}
std::string port_as_string = std::to_string(*port);
status = fs->Connect(nn.value_or(""), port_as_string);
} else {
status = fs->ConnectToDefaultFs();
}
if (!status.ok()) {
Error(status);
// FileSystem's ctor might take ownership of the io_service; if it does,
// it will null out the pointer
if (io_service)
delete io_service;
delete fs;
return nullptr;
}
return new hdfs_internal(fs);
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFSPP_EXT_API
hdfsFS hdfsAllocateFileSystem(struct hdfsBuilder *bld) {
// Same idea as the first half of doHdfsConnect, but return the wrapped FS before
// connecting.
try {
errno = 0;
std::shared_ptr<IoService> io_service = IoService::MakeShared();
int io_thread_count = bld->config.GetOptions().io_threads_;
if(io_thread_count < 1) {
io_service->InitDefaultWorkers();
} else {
io_service->InitWorkers(io_thread_count);
}
FileSystem *fs = FileSystem::New(io_service, bld->user.value_or(""), bld->config.GetOptions());
if (!fs) {
ReportError(ENODEV, "Could not create FileSystem object");
return nullptr;
}
if (fsEventCallback) {
fs->SetFsEventCallback(fsEventCallback.value());
}
return new hdfs_internal(fs);
} catch (const std::exception &e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
return nullptr;
}
LIBHDFSPP_EXT_API
int hdfsConnectAllocated(hdfsFS fs, struct hdfsBuilder *bld) {
if(!CheckSystem(fs)) {
return ENODEV;
}
if(!bld) {
ReportError(ENODEV, "No hdfsBuilder object supplied");
return ENODEV;
}
// Get C++ FS to do connect
FileSystem *fsImpl = fs->get_impl();
if(!fsImpl) {
ReportError(ENODEV, "Null FileSystem implementation");
return ENODEV;
}
// Unpack the required bits of the hdfsBuilder
optional<std::string> nn = bld->overrideHost;
optional<tPort> port = bld->overridePort;
optional<std::string> user = bld->user;
// try-catch in case some of the third-party stuff throws
try {
Status status;
if (nn || port) {
if (!port) {
port = kDefaultPort;
}
std::string port_as_string = std::to_string(*port);
status = fsImpl->Connect(nn.value_or(""), port_as_string);
} else {
status = fsImpl->ConnectToDefaultFs();
}
if (!status.ok()) {
Error(status);
return ENODEV;
}
// 0 to indicate a good connection
return 0;
} catch (const std::exception & e) {
ReportException(e);
return ENODEV;
} catch (...) {
ReportCaughtNonException();
return ENODEV;
}
return 0;
}
LIBHDFS_C_API
hdfsFS hdfsConnect(const char *nn, tPort port) {
return hdfsConnectAsUser(nn, port, "");
}
LIBHDFS_C_API
hdfsFS hdfsConnectAsUser(const char* nn, tPort port, const char *user) {
return doHdfsConnect(std::string(nn), port, std::string(user), Options());
}
LIBHDFS_C_API
hdfsFS hdfsConnectAsUserNewInstance(const char* nn, tPort port, const char *user ) {
//libhdfspp always returns a new instance
return doHdfsConnect(std::string(nn), port, std::string(user), Options());
}
LIBHDFS_C_API
hdfsFS hdfsConnectNewInstance(const char* nn, tPort port) {
//libhdfspp always returns a new instance
return hdfsConnectAsUser(nn, port, "");
}
LIBHDFSPP_EXT_API
int hdfsCancelPendingConnection(hdfsFS fs) {
// todo: stick an enum in hdfs_internal to check the connect state
if(!CheckSystem(fs)) {
return ENODEV;
}
FileSystem *fsImpl = fs->get_impl();
if(!fsImpl) {
ReportError(ENODEV, "Null FileSystem implementation");
return ENODEV;
}
bool canceled = fsImpl->CancelPendingConnect();
if(canceled) {
return 0;
} else {
return EINTR;
}
}
LIBHDFS_C_API
int hdfsDisconnect(hdfsFS fs) {
try
{
errno = 0;
if (!fs) {
ReportError(ENODEV, "Cannot disconnect null FS handle.");
return -1;
}
delete fs;
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
hdfsFile hdfsOpenFile(hdfsFS fs, const char *path, int flags, int bufferSize,
short replication, tSize blocksize) {
try
{
errno = 0;
(void)flags;
(void)bufferSize;
(void)replication;
(void)blocksize;
if (!fs) {
ReportError(ENODEV, "Cannot perform FS operations with null FS handle.");
return nullptr;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return nullptr;
}
FileHandle *f = nullptr;
Status stat = fs->get_impl()->Open(*abs_path, &f);
if (!stat.ok()) {
Error(stat);
return nullptr;
}
if (f && fileEventCallback) {
f->SetFileEventCallback(fileEventCallback.value());
}
return new hdfsFile_internal(f);
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFS_C_API
int hdfsCloseFile(hdfsFS fs, hdfsFile file) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
delete file;
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
char* hdfsGetWorkingDirectory(hdfsFS fs, char *buffer, size_t bufferSize) {
try
{
errno = 0;
if (!CheckSystem(fs)) {
return nullptr;
}
std::string wd = fs->get_working_directory();
size_t size = wd.size();
if (size + 1 > bufferSize) {
std::stringstream ss;
ss << "hdfsGetWorkingDirectory: bufferSize is " << bufferSize <<
", which is not enough to fit working directory of size " << (size + 1);
Error(Status::InvalidArgument(ss.str().c_str()));
return nullptr;
}
wd.copy(buffer, size);
buffer[size] = '\0';
return buffer;
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFS_C_API
int hdfsSetWorkingDirectory(hdfsFS fs, const char* path) {
try
{
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
//Enforce last character to be '/'
std::string withSlash = *abs_path;
char last = withSlash.back();
if (last != '/'){
withSlash += '/';
}
fs->set_working_directory(withSlash);
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsAvailable(hdfsFS fs, hdfsFile file) {
//Since we do not have read ahead implemented, return 0 if fs and file are good;
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
return 0;
}
LIBHDFS_C_API
tOffset hdfsGetDefaultBlockSize(hdfsFS fs) {
try {
errno = 0;
return fs->get_impl()->get_options().block_size;
} catch (const std::exception & e) {
ReportException(e);
return -1;
} catch (...) {
ReportCaughtNonException();
return -1;
}
}
LIBHDFS_C_API
tOffset hdfsGetDefaultBlockSizeAtPath(hdfsFS fs, const char *path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
uint64_t block_size;
Status stat = fs->get_impl()->GetPreferredBlockSize(*abs_path, block_size);
if (!stat.ok()) {
if (stat.pathNotFound()){
return fs->get_impl()->get_options().block_size;
} else {
return Error(stat);
}
}
return block_size;
} catch (const std::exception & e) {
ReportException(e);
return -1;
} catch (...) {
ReportCaughtNonException();
return -1;
}
}
LIBHDFS_C_API
int hdfsSetReplication(hdfsFS fs, const char* path, int16_t replication) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
if(replication < 1){
return Error(Status::InvalidArgument("SetReplication: argument 'replication' cannot be less than 1"));
}
Status stat;
stat = fs->get_impl()->SetReplication(*abs_path, replication);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsUtime(hdfsFS fs, const char* path, tTime mtime, tTime atime) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
stat = fs->get_impl()->SetTimes(*abs_path, mtime, atime);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
tOffset hdfsGetCapacity(hdfsFS fs) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
hdfs::FsInfo fs_info;
Status stat = fs->get_impl()->GetFsStats(fs_info);
if (!stat.ok()) {
Error(stat);
return -1;
}
return fs_info.capacity;
} catch (const std::exception & e) {
ReportException(e);
return -1;
} catch (...) {
ReportCaughtNonException();
return -1;
}
}
LIBHDFS_C_API
tOffset hdfsGetUsed(hdfsFS fs) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
hdfs::FsInfo fs_info;
Status stat = fs->get_impl()->GetFsStats(fs_info);
if (!stat.ok()) {
Error(stat);
return -1;
}
return fs_info.used;
} catch (const std::exception & e) {
ReportException(e);
return -1;
} catch (...) {
ReportCaughtNonException();
return -1;
}
}
void StatInfoToHdfsFileInfo(hdfsFileInfo * file_info,
const hdfs::StatInfo & stat_info) {
/* file or directory */
if (stat_info.file_type == StatInfo::IS_DIR) {
file_info->mKind = kObjectKindDirectory;
} else if (stat_info.file_type == StatInfo::IS_FILE) {
file_info->mKind = kObjectKindFile;
} else {
file_info->mKind = kObjectKindFile;
LOG_WARN(kFileSystem, << "Symlink is not supported! Reporting as a file: ");
}
/* the name of the file */
char copyOfPath[PATH_MAX];
strncpy(copyOfPath, stat_info.path.c_str(), PATH_MAX);
copyOfPath[PATH_MAX - 1] = '\0'; // in case strncpy ran out of space
char * mName = basename(copyOfPath);
size_t mName_size = strlen(mName);
file_info->mName = new char[mName_size+1];
strncpy(file_info->mName, basename(copyOfPath), mName_size + 1);
/* the last modification time for the file in seconds */
file_info->mLastMod = (tTime) stat_info.modification_time;
/* the size of the file in bytes */
file_info->mSize = (tOffset) stat_info.length;
/* the count of replicas */
file_info->mReplication = (short) stat_info.block_replication;
/* the block size for the file */
file_info->mBlockSize = (tOffset) stat_info.blocksize;
/* the owner of the file */
file_info->mOwner = new char[stat_info.owner.size() + 1];
strncpy(file_info->mOwner, stat_info.owner.c_str(), stat_info.owner.size() + 1);
/* the group associated with the file */
file_info->mGroup = new char[stat_info.group.size() + 1];
strncpy(file_info->mGroup, stat_info.group.c_str(), stat_info.group.size() + 1);
/* the permissions associated with the file encoded as an octal number (0777)*/
file_info->mPermissions = (short) stat_info.permissions;
/* the last access time for the file in seconds since the epoch*/
file_info->mLastAccess = stat_info.access_time;
}
LIBHDFS_C_API
int hdfsExists(hdfsFS fs, const char *path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
hdfs::StatInfo stat_info;
Status stat = fs->get_impl()->GetFileInfo(*abs_path, stat_info);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
hdfsFileInfo *hdfsGetPathInfo(hdfsFS fs, const char* path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return nullptr;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return nullptr;
}
hdfs::StatInfo stat_info;
Status stat = fs->get_impl()->GetFileInfo(*abs_path, stat_info);
if (!stat.ok()) {
Error(stat);
return nullptr;
}
hdfsFileInfo *file_info = new hdfsFileInfo[1];
StatInfoToHdfsFileInfo(file_info, stat_info);
return file_info;
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFS_C_API
hdfsFileInfo *hdfsListDirectory(hdfsFS fs, const char* path, int *numEntries) {
try {
errno = 0;
if (!CheckSystem(fs)) {
*numEntries = 0;
return nullptr;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return nullptr;
}
std::vector<StatInfo> stat_infos;
Status stat = fs->get_impl()->GetListing(*abs_path, &stat_infos);
if (!stat.ok()) {
Error(stat);
*numEntries = 0;
return nullptr;
}
if(stat_infos.empty()){
*numEntries = 0;
return nullptr;
}
*numEntries = stat_infos.size();
hdfsFileInfo *file_infos = new hdfsFileInfo[stat_infos.size()];
for(std::vector<StatInfo>::size_type i = 0; i < stat_infos.size(); i++) {
StatInfoToHdfsFileInfo(&file_infos[i], stat_infos.at(i));
}
return file_infos;
} catch (const std::exception & e) {
ReportException(e);
*numEntries = 0;
return nullptr;
} catch (...) {
ReportCaughtNonException();
*numEntries = 0;
return nullptr;
}
}
LIBHDFS_C_API
void hdfsFreeFileInfo(hdfsFileInfo *hdfsFileInfo, int numEntries)
{
errno = 0;
int i;
for (i = 0; i < numEntries; ++i) {
delete[] hdfsFileInfo[i].mName;
delete[] hdfsFileInfo[i].mOwner;
delete[] hdfsFileInfo[i].mGroup;
}
delete[] hdfsFileInfo;
}
LIBHDFS_C_API
int hdfsCreateDirectory(hdfsFS fs, const char* path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
//Use default permissions and set true for creating all non-existant parent directories
stat = fs->get_impl()->Mkdirs(*abs_path, FileSystem::GetDefaultPermissionMask(), true);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsDelete(hdfsFS fs, const char* path, int recursive) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
stat = fs->get_impl()->Delete(*abs_path, recursive);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsRename(hdfsFS fs, const char* oldPath, const char* newPath) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> old_abs_path = getAbsolutePath(fs, oldPath);
const optional<std::string> new_abs_path = getAbsolutePath(fs, newPath);
if(!old_abs_path || !new_abs_path) {
return -1;
}
Status stat;
stat = fs->get_impl()->Rename(*old_abs_path, *new_abs_path);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsChmod(hdfsFS fs, const char* path, short mode){
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat = FileSystem::CheckValidPermissionMask(mode);
if (!stat.ok()) {
return Error(stat);
}
stat = fs->get_impl()->SetPermission(*abs_path, mode);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsChown(hdfsFS fs, const char* path, const char *owner, const char *group){
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
std::string own = (owner) ? owner : "";
std::string grp = (group) ? group : "";
Status stat;
stat = fs->get_impl()->SetOwner(*abs_path, own, grp);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
hdfsFileInfo * hdfsFind(hdfsFS fs, const char* path, const char* name, uint32_t * numEntries){
try {
errno = 0;
if (!CheckSystem(fs)) {
*numEntries = 0;
return nullptr;
}
std::vector<StatInfo> stat_infos;
Status stat = fs->get_impl()->Find(path, name, hdfs::FileSystem::GetDefaultFindMaxDepth(), &stat_infos);
if (!stat.ok()) {
Error(stat);
*numEntries = 0;
return nullptr;
}
//Existing API expects nullptr if size is 0
if(stat_infos.empty()){
*numEntries = 0;
return nullptr;
}
*numEntries = stat_infos.size();
hdfsFileInfo *file_infos = new hdfsFileInfo[stat_infos.size()];
for(std::vector<StatInfo>::size_type i = 0; i < stat_infos.size(); i++) {
StatInfoToHdfsFileInfo(&file_infos[i], stat_infos.at(i));
}
return file_infos;
} catch (const std::exception & e) {
ReportException(e);
*numEntries = 0;
return nullptr;
} catch (...) {
ReportCaughtNonException();
*numEntries = 0;
return nullptr;
}
}
LIBHDFSPP_EXT_API
int hdfsCreateSnapshot(hdfsFS fs, const char* path, const char* name) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
if(!name){
stat = fs->get_impl()->CreateSnapshot(*abs_path, "");
} else {
stat = fs->get_impl()->CreateSnapshot(*abs_path, name);
}
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsDeleteSnapshot(hdfsFS fs, const char* path, const char* name) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
if (!name) {
return Error(Status::InvalidArgument("hdfsDeleteSnapshot: argument 'name' cannot be NULL"));
}
Status stat;
stat = fs->get_impl()->DeleteSnapshot(*abs_path, name);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
int hdfsRenameSnapshot(hdfsFS fs, const char* path, const char* old_name, const char* new_name) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
if (!old_name) {
return Error(Status::InvalidArgument("hdfsRenameSnapshot: argument 'old_name' cannot be NULL"));
}
if (!new_name) {
return Error(Status::InvalidArgument("hdfsRenameSnapshot: argument 'new_name' cannot be NULL"));
}
Status stat;
stat = fs->get_impl()->RenameSnapshot(*abs_path, old_name, new_name);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsAllowSnapshot(hdfsFS fs, const char* path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
stat = fs->get_impl()->AllowSnapshot(*abs_path);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsDisallowSnapshot(hdfsFS fs, const char* path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
stat = fs->get_impl()->DisallowSnapshot(*abs_path);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
tSize hdfsPread(hdfsFS fs, hdfsFile file, tOffset position, void *buffer,
tSize length) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
size_t len = 0;
Status stat = file->get_impl()->PositionRead(buffer, length, position, &len);
if(!stat.ok()) {
return Error(stat);
}
return (tSize)len;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
tSize hdfsRead(hdfsFS fs, hdfsFile file, void *buffer, tSize length) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
size_t len = 0;
Status stat = file->get_impl()->Read(buffer, length, &len);
if (!stat.ok()) {
return Error(stat);
}
return (tSize)len;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsUnbufferFile(hdfsFile file) {
//Currently we are not doing any buffering
CheckHandle(file);
return -1;
}
LIBHDFS_C_API
int hdfsFileGetReadStatistics(hdfsFile file, struct hdfsReadStatistics **stats) {
try
{
errno = 0;
if (!CheckHandle(file)) {
return -1;
}
*stats = new hdfsReadStatistics;
memset(*stats, 0, sizeof(hdfsReadStatistics));
(*stats)->totalBytesRead = file->get_impl()->get_bytes_read();
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsFileClearReadStatistics(hdfsFile file) {
try
{
errno = 0;
if (!CheckHandle(file)) {
return -1;
}
file->get_impl()->clear_bytes_read();
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int64_t hdfsReadStatisticsGetRemoteBytesRead(const struct hdfsReadStatistics *stats) {
return stats->totalBytesRead - stats->totalLocalBytesRead;
}
LIBHDFS_C_API
void hdfsFileFreeReadStatistics(struct hdfsReadStatistics *stats) {
errno = 0;
delete stats;
}
/* 0 on success, -1 on error*/
LIBHDFS_C_API
int hdfsSeek(hdfsFS fs, hdfsFile file, tOffset desiredPos) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
off_t desired = desiredPos;
Status stat = file->get_impl()->Seek(&desired, std::ios_base::beg);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
tOffset hdfsTell(hdfsFS fs, hdfsFile file) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
off_t offset = 0;
Status stat = file->get_impl()->Seek(&offset, std::ios_base::cur);
if (!stat.ok()) {
return Error(stat);
}
return (tOffset)offset;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
/* extended API */
int hdfsCancel(hdfsFS fs, hdfsFile file) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
static_cast<FileHandleImpl*>(file->get_impl())->CancelOperations();
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsGetBlockLocations(hdfsFS fs, const char *path, struct hdfsBlockLocations ** locations_out)
{
try
{
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
if (locations_out == nullptr) {
ReportError(EINVAL, "Null pointer passed to hdfsGetBlockLocations");
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
std::shared_ptr<FileBlockLocation> ppLocations;
Status stat = fs->get_impl()->GetBlockLocations(*abs_path, 0, std::numeric_limits<int64_t>::max(), &ppLocations);
if (!stat.ok()) {
return Error(stat);
}
hdfsBlockLocations *locations = new struct hdfsBlockLocations();
(*locations_out) = locations;
bzero(locations, sizeof(*locations));
locations->fileLength = ppLocations->getFileLength();
locations->isLastBlockComplete = ppLocations->isLastBlockComplete();
locations->isUnderConstruction = ppLocations->isUnderConstruction();
const std::vector<BlockLocation> & ppBlockLocations = ppLocations->getBlockLocations();
locations->num_blocks = ppBlockLocations.size();
locations->blocks = new struct hdfsBlockInfo[locations->num_blocks];
for (size_t i=0; i < ppBlockLocations.size(); i++) {
auto ppBlockLocation = ppBlockLocations[i];
auto block = &locations->blocks[i];
block->num_bytes = ppBlockLocation.getLength();
block->start_offset = ppBlockLocation.getOffset();
const std::vector<DNInfo> & ppDNInfos = ppBlockLocation.getDataNodes();
block->num_locations = ppDNInfos.size();
block->locations = new hdfsDNInfo[block->num_locations];
for (size_t j=0; j < block->num_locations; j++) {
auto ppDNInfo = ppDNInfos[j];
auto dn_info = &block->locations[j];
dn_info->xfer_port = ppDNInfo.getXferPort();
dn_info->info_port = ppDNInfo.getInfoPort();
dn_info->IPC_port = ppDNInfo.getIPCPort();
dn_info->info_secure_port = ppDNInfo.getInfoSecurePort();
char * buf;
buf = new char[ppDNInfo.getHostname().size() + 1];
strncpy(buf, ppDNInfo.getHostname().c_str(), ppDNInfo.getHostname().size() + 1);
dn_info->hostname = buf;
buf = new char[ppDNInfo.getIPAddr().size() + 1];
strncpy(buf, ppDNInfo.getIPAddr().c_str(), ppDNInfo.getIPAddr().size() + 1);
dn_info->ip_address = buf;
buf = new char[ppDNInfo.getNetworkLocation().size() + 1];
strncpy(buf, ppDNInfo.getNetworkLocation().c_str(), ppDNInfo.getNetworkLocation().size() + 1);
dn_info->network_location = buf;
}
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsFreeBlockLocations(struct hdfsBlockLocations * blockLocations) {
errno = 0;
if (blockLocations == nullptr)
return 0;
for (size_t i=0; i < blockLocations->num_blocks; i++) {
auto block = &blockLocations->blocks[i];
for (size_t j=0; j < block->num_locations; j++) {
auto location = &block->locations[j];
delete[] location->hostname;
delete[] location->ip_address;
delete[] location->network_location;
}
}
delete[] blockLocations->blocks;
delete blockLocations;
return 0;
}
LIBHDFS_C_API
char*** hdfsGetHosts(hdfsFS fs, const char* path, tOffset start, tOffset length) {
try
{
errno = 0;
if (!CheckSystem(fs)) {
return nullptr;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return nullptr;
}
std::shared_ptr<FileBlockLocation> ppLocations;
Status stat = fs->get_impl()->GetBlockLocations(*abs_path, start, length, &ppLocations);
if (!stat.ok()) {
Error(stat);
return nullptr;
}
const std::vector<BlockLocation> & ppBlockLocations = ppLocations->getBlockLocations();
char ***hosts = new char**[ppBlockLocations.size() + 1];
for (size_t i=0; i < ppBlockLocations.size(); i++) {
const std::vector<DNInfo> & ppDNInfos = ppBlockLocations[i].getDataNodes();
hosts[i] = new char*[ppDNInfos.size() + 1];
for (size_t j=0; j < ppDNInfos.size(); j++) {
auto ppDNInfo = ppDNInfos[j];
hosts[i][j] = new char[ppDNInfo.getHostname().size() + 1];
strncpy(hosts[i][j], ppDNInfo.getHostname().c_str(), ppDNInfo.getHostname().size() + 1);
}
hosts[i][ppDNInfos.size()] = nullptr;
}
hosts[ppBlockLocations.size()] = nullptr;
return hosts;
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFS_C_API
void hdfsFreeHosts(char ***blockHosts) {
errno = 0;
if (blockHosts == nullptr)
return;
for (size_t i = 0; blockHosts[i]; i++) {
for (size_t j = 0; blockHosts[i][j]; j++) {
delete[] blockHosts[i][j];
}
delete[] blockHosts[i];
}
delete blockHosts;
}
/*******************************************************************
* EVENT CALLBACKS
*******************************************************************/
const char * FS_NN_CONNECT_EVENT = hdfs::FS_NN_CONNECT_EVENT;
const char * FS_NN_READ_EVENT = hdfs::FS_NN_READ_EVENT;
const char * FS_NN_WRITE_EVENT = hdfs::FS_NN_WRITE_EVENT;
const char * FILE_DN_CONNECT_EVENT = hdfs::FILE_DN_CONNECT_EVENT;
const char * FILE_DN_READ_EVENT = hdfs::FILE_DN_READ_EVENT;
const char * FILE_DN_WRITE_EVENT = hdfs::FILE_DN_WRITE_EVENT;
event_response fs_callback_glue(libhdfspp_fs_event_callback handler,
int64_t cookie,
const char * event,
const char * cluster,
int64_t value) {
int result = handler(event, cluster, value, cookie);
if (result == LIBHDFSPP_EVENT_OK) {
return event_response::make_ok();
}
#ifndef LIBHDFSPP_SIMULATE_ERROR_DISABLED
if (result == DEBUG_SIMULATE_ERROR) {
return event_response::test_err(Status::Error("Simulated error"));
}
#endif
return event_response::make_ok();
}
event_response file_callback_glue(libhdfspp_file_event_callback handler,
int64_t cookie,
const char * event,
const char * cluster,
const char * file,
int64_t value) {
int result = handler(event, cluster, file, value, cookie);
if (result == LIBHDFSPP_EVENT_OK) {
return event_response::make_ok();
}
#ifndef LIBHDFSPP_SIMULATE_ERROR_DISABLED
if (result == DEBUG_SIMULATE_ERROR) {
return event_response::test_err(Status::Error("Simulated error"));
}
#endif
return event_response::make_ok();
}
LIBHDFSPP_EXT_API
int hdfsPreAttachFSMonitor(libhdfspp_fs_event_callback handler, int64_t cookie)
{
fs_event_callback callback = std::bind(fs_callback_glue, handler, cookie, _1, _2, _3);
fsEventCallback = callback;
return 0;
}
LIBHDFSPP_EXT_API
int hdfsPreAttachFileMonitor(libhdfspp_file_event_callback handler, int64_t cookie)
{
file_event_callback callback = std::bind(file_callback_glue, handler, cookie, _1, _2, _3, _4);
fileEventCallback = callback;
return 0;
}
/*******************************************************************
* BUILDER INTERFACE
*******************************************************************/
HdfsConfiguration LoadDefault(ConfigurationLoader & loader)
{
optional<HdfsConfiguration> result = loader.LoadDefaultResources<HdfsConfiguration>();
if (result)
{
return result.value();
}
else
{
return loader.NewConfig<HdfsConfiguration>();
}
}
hdfsBuilder::hdfsBuilder() : config(loader.NewConfig<HdfsConfiguration>())
{
errno = 0;
config = LoadDefault(loader);
}
hdfsBuilder::hdfsBuilder(const char * directory) :
config(loader.NewConfig<HdfsConfiguration>())
{
errno = 0;
loader.SetSearchPath(directory);
config = LoadDefault(loader);
}
LIBHDFS_C_API
struct hdfsBuilder *hdfsNewBuilder(void)
{
try
{
errno = 0;
return new struct hdfsBuilder();
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFS_C_API
void hdfsBuilderSetNameNode(struct hdfsBuilder *bld, const char *nn)
{
errno = 0;
bld->overrideHost = std::string(nn);
}
LIBHDFS_C_API
void hdfsBuilderSetNameNodePort(struct hdfsBuilder *bld, tPort port)
{
errno = 0;
bld->overridePort = port;
}
LIBHDFS_C_API
void hdfsBuilderSetUserName(struct hdfsBuilder *bld, const char *userName)
{
errno = 0;
if (userName && *userName) {
bld->user = std::string(userName);
}
}
LIBHDFS_C_API
void hdfsBuilderSetForceNewInstance(struct hdfsBuilder *bld) {
//libhdfspp always returns a new instance, so nothing to do
(void)bld;
errno = 0;
}
LIBHDFS_C_API
void hdfsFreeBuilder(struct hdfsBuilder *bld)
{
try
{
errno = 0;
delete bld;
} catch (const std::exception & e) {
ReportException(e);
} catch (...) {
ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsBuilderConfSetStr(struct hdfsBuilder *bld, const char *key,
const char *val)
{
try
{
errno = 0;
optional<HdfsConfiguration> newConfig = bld->loader.OverlayValue(bld->config, key, val);
if (newConfig)
{
bld->config = newConfig.value();
return 0;
}
else
{
ReportError(EINVAL, "Could not change Builder value");
return -1;
}
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
void hdfsConfStrFree(char *val)
{
errno = 0;
free(val);
}
LIBHDFS_C_API
hdfsFS hdfsBuilderConnect(struct hdfsBuilder *bld) {
hdfsFS fs = doHdfsConnect(bld->overrideHost, bld->overridePort, bld->user, bld->config.GetOptions());
// Always free the builder
hdfsFreeBuilder(bld);
return fs;
}
LIBHDFS_C_API
int hdfsConfGetStr(const char *key, char **val)
{
try
{
errno = 0;
hdfsBuilder builder;
return hdfsBuilderConfGetStr(&builder, key, val);
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsConfGetInt(const char *key, int32_t *val)
{
try
{
errno = 0;
hdfsBuilder builder;
return hdfsBuilderConfGetInt(&builder, key, val);
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
//
// Extended builder interface
//
struct hdfsBuilder *hdfsNewBuilderFromDirectory(const char * configDirectory)
{
try
{
errno = 0;
return new struct hdfsBuilder(configDirectory);
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFSPP_EXT_API
int hdfsBuilderConfGetStr(struct hdfsBuilder *bld, const char *key,
char **val)
{
try
{
errno = 0;
optional<std::string> value = bld->config.Get(key);
if (value)
{
size_t len = value->length() + 1;
*val = static_cast<char *>(malloc(len));
strncpy(*val, value->c_str(), len);
}
else
{
*val = nullptr;
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
// If we're running on a 32-bit platform, we might get 64-bit values that
// don't fit in an int, and int is specified by the java hdfs.h interface
bool isValidInt(int64_t value)
{
return (value >= std::numeric_limits<int>::min() &&
value <= std::numeric_limits<int>::max());
}
LIBHDFSPP_EXT_API
int hdfsBuilderConfGetInt(struct hdfsBuilder *bld, const char *key, int32_t *val)
{
try
{
errno = 0;
// Pull from default configuration
optional<int64_t> value = bld->config.GetInt(key);
if (value)
{
if (!isValidInt(*value)){
ReportError(EINVAL, "Builder value is not valid");
return -1;
}
*val = *value;
return 0;
}
// If not found, don't change val
ReportError(EINVAL, "Could not get Builder value");
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsBuilderConfGetLong(struct hdfsBuilder *bld, const char *key, int64_t *val)
{
try
{
errno = 0;
// Pull from default configuration
optional<int64_t> value = bld->config.GetInt(key);
if (value)
{
*val = *value;
return 0;
}
// If not found, don't change val
ReportError(EINVAL, "Could not get Builder value");
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
/**
* Logging functions
**/
class CForwardingLogger : public LoggerInterface {
public:
CForwardingLogger() : callback_(nullptr) {};
// Converts LogMessage into LogData, a POD type,
// and invokes callback_ if it's not null.
void Write(const LogMessage& msg);
// pass in NULL to clear the hook
void SetCallback(void (*callback)(LogData*));
//return a copy, or null on failure.
static LogData *CopyLogData(const LogData*);
//free LogData allocated with CopyLogData
static void FreeLogData(LogData*);
private:
void (*callback_)(LogData*);
};
/**
* Plugin to forward message to a C function pointer
**/
void CForwardingLogger::Write(const LogMessage& msg) {
if(!callback_)
return;
const std::string text = msg.MsgString();
LogData data;
data.level = msg.level();
data.component = msg.component();
data.msg = text.c_str();
data.file_name = msg.file_name();
data.file_line = msg.file_line();
callback_(&data);
}
void CForwardingLogger::SetCallback(void (*callback)(LogData*)) {
callback_ = callback;
}
LogData *CForwardingLogger::CopyLogData(const LogData *orig) {
if(!orig)
return nullptr;
LogData *copy = (LogData*)malloc(sizeof(LogData));
if(!copy)
return nullptr;
copy->level = orig->level;
copy->component = orig->component;
if(orig->msg)
copy->msg = strdup(orig->msg);
copy->file_name = orig->file_name;
copy->file_line = orig->file_line;
return copy;
}
void CForwardingLogger::FreeLogData(LogData *data) {
if(!data)
return;
if(data->msg)
free((void*)data->msg);
// Inexpensive way to help catch use-after-free
memset(data, 0, sizeof(LogData));
free(data);
}
LIBHDFSPP_EXT_API
LogData *hdfsCopyLogData(LogData *data) {
return CForwardingLogger::CopyLogData(data);
}
LIBHDFSPP_EXT_API
void hdfsFreeLogData(LogData *data) {
CForwardingLogger::FreeLogData(data);
}
LIBHDFSPP_EXT_API
void hdfsSetLogFunction(void (*callback)(LogData*)) {
CForwardingLogger *logger = new CForwardingLogger();
logger->SetCallback(callback);
LogManager::SetLoggerImplementation(std::unique_ptr<LoggerInterface>(logger));
}
static bool IsLevelValid(int component) {
if(component < HDFSPP_LOG_LEVEL_TRACE || component > HDFSPP_LOG_LEVEL_ERROR)
return false;
return true;
}
// should use __builtin_popcnt as optimization on some platforms
static int popcnt(int val) {
int bits = sizeof(val) * 8;
int count = 0;
for(int i=0; i<bits; i++) {
if((val >> i) & 0x1)
count++;
}
return count;
}
static bool IsComponentValid(int component) {
if(component < HDFSPP_LOG_COMPONENT_UNKNOWN || component > HDFSPP_LOG_COMPONENT_FILESYSTEM)
return false;
if(popcnt(component) != 1)
return false;
return true;
}
LIBHDFSPP_EXT_API
int hdfsEnableLoggingForComponent(int component) {
errno = 0;
if(!IsComponentValid(component))
return -1;
LogManager::EnableLogForComponent(static_cast<LogSourceComponent>(component));
return 0;
}
LIBHDFSPP_EXT_API
int hdfsDisableLoggingForComponent(int component) {
errno = 0;
if(!IsComponentValid(component))
return -1;
LogManager::DisableLogForComponent(static_cast<LogSourceComponent>(component));
return 0;
}
LIBHDFSPP_EXT_API
int hdfsSetLoggingLevel(int level) {
errno = 0;
if(!IsLevelValid(level))
return -1;
LogManager::SetLogLevel(static_cast<LogLevel>(level));
return 0;
}
#undef LIBHDFS_C_API
#undef LIBHDFSPP_EXT_API
|
[
"james.clampffer@hp.com"
] |
james.clampffer@hp.com
|
b7142cc82c58bbf5d5f2913185946f0a5a480058
|
0ce585a428b1d1f3774a58781f99614b1bfac278
|
/libevent_http_frame/frame/libevent_http_frame.cpp
|
d88d3794dfcd3e1a2968c77a97a553b43d676d87
|
[] |
no_license
|
CaseZheng/SimpleServerFramework
|
659728d5e41f57e654873b27ab93189bf41d6ea5
|
f2c7f0019b406385a76f2e3b193a84568d0c59e5
|
refs/heads/master
| 2021-07-03T19:06:58.725622
| 2019-03-11T16:07:16
| 2019-03-11T16:07:16
| 124,250,589
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 648
|
cpp
|
#include <boost/shared_ptr.hpp>
#include "libevent_http_frame.h"
#include "log.h"
bool CLibeventHttpFrame::Init(const string &strServerName, const string &strConfPath)
{
if(!CLibeventFrame::Init(strServerName, strConfPath))
{
ERROR("Function failure CLibeventFrame::Init");
return false;
}
m_pHttpServer.reset(new CHttpServer(m_pEventBase));
if(NULL == m_pHttpServer)
{
ERROR("CHttpServer new failure");
return false;
}
if(!m_pHttpServer->Init())
{
ERROR("HttpServer Init failure");
return false;
}
DEBUG("HttpServer Init success");
return true;
}
|
[
"764307915@qq.com"
] |
764307915@qq.com
|
f20de33998f9b69aa794a04fee8eaafd58e96148
|
e649acb68fc5134a3843ef2330e5c2d4070363a8
|
/H.weak_memory.cpp
|
b6be5b44195efc485fc6495577cfeef31ec18b53
|
[] |
no_license
|
jesuswr/cp-codes-and-problems
|
6483949ce896e59c471f0e0640f5c8b47f482ec3
|
770f3bf004f90015f078d5699d26cde5c33d9a28
|
refs/heads/master
| 2023-08-08T03:37:36.626572
| 2023-07-24T16:54:02
| 2023-07-24T16:54:02
| 196,292,128
| 1
| 1
| null | 2019-10-09T23:23:43
| 2019-07-11T00:26:10
|
C++
|
UTF-8
|
C++
| false
| false
| 3,028
|
cpp
|
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <math.h>
#include <string>
#include <cstring>
#include <set>
#include <map>
#include <unordered_map>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<int, pair<int, int>> piii;
typedef vector<int> vi;
typedef vector<pii> vii;
#define ri(a) scanf("%d", &a)
#define rii(a,b) scanf("%d %d", &a, &b)
#define riii(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define rl(a) scanf("%lld", &a)
#define rll(a,b) scanf("%lld %lld", &a, &b)
#define FOR(i,n,m) for(int i=n; i<m; i++)
#define ROF(i,n,m) for(int i=n; i>m; i--)
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define F first
#define S second
const int INF = 0x3f3f3f3f;
const ll LLINF = 1e18;
const int maxN = 1e5 + 10; // CAMBIAR ESTE
// GJNM
int v, e, k;
vi G[maxN];
int START, END;
bool SPECIAL[maxN];
int father[maxN], siz[maxN];
// n es el primer elemento y m el ultimo, por ejemplo los nodos de un grafo desde el 1 al 10
void makeSet(int n, int m) {
for (int i = n; i <= m; ++i) {
father[i] = -1;
siz[i] = 0;
}
}
int find(int x) {
if (father[x] == -1) // -1 significa que es el representante del set
return x;
return father[x] = find(father[x]);
}
void unio(int x, int y) { // x y y tienen que ser los representantes
if (siz[x] > siz[y])
father[y] = x;
else {
father[x] = y;
if ( siz[x] == siz[y] ) siz[y]++;
}
}
int C[maxN];
bool check(int q) {
makeSet(0, v);
queue<int> curr;
set<int> active;
FOR(i, 0, v) {
if ( SPECIAL[i] ) {
active.insert(i);
curr.push(i);
}
}
curr.push(END), active.insert(END);
FOR(i, 0, q / 2) {
int n = curr.size();
if ( find(START) == find(END) )
return true;
FOR(j, 0, n) {
int x = curr.front(); curr.pop();
for (auto &y : G[x]) {
if ( find(x) != find(y) )
unio(find(x), find(y));
if ( !active.count(y) ) {
active.insert(y);
curr.push(y);
}
}
}
}
if ( q & 1 ) {
for (auto &i : active) {
for (auto &y : G[i]) {
if ( find(i) != find(y) && (active.count(y) > 0) )
unio(find(i), find(y));
}
}
}
return find(START) == find(END);
}
int DIST[maxN];
bool vis[maxN];
int AYUDA = INF;
void bfs(int e) {
vis[e] = true;
DIST[e] = 0;
queue<int> q;
q.push(e);
while (!q.empty()) {
int x = q.front(); q.pop();
if ( x == START )
return;
if ( SPECIAL[x] )
AYUDA = min(AYUDA, DIST[x]);
for (auto y : G[x]) {
if (!vis[y]) {
DIST[y] = DIST[x] + 1;
vis[y] = true;
q.push(y);
}
}
}
printf("-1\n");
exit(0);
}
int main() {
riii(v, e, k);
FOR(i, 0, k) {
int aux;
ri(aux);
SPECIAL[aux - 1] = true;
}
FOR(i, 0, e) {
int a, b;
rii(a, b);
a--, b--;
G[a].pb(b);
G[b].pb(a);
}
rii(START, END);
START--, END--;
bfs(END);
int lo = AYUDA, hi = DIST[START];
while ( lo < hi ) {
FOR(i, 0, v)
C[i] = -1;
int mid = lo + (hi - lo) / 2;
if ( check(mid) )
hi = mid;
else
lo = mid + 1;
}
printf("%d\n", hi);
return 0;
}
|
[
"jesuswahrman@gmail.com"
] |
jesuswahrman@gmail.com
|
f0653d554da8b95e36fd8bc2614b6524ea32bf7d
|
86d85900756de7245e9a06546fcd7bb02d7aa844
|
/deformationGraph.cpp
|
0ebb2877e51c7622d52591d48a2e0b38880b0691
|
[] |
no_license
|
shizsun0609tw/Embedded-Deforamtion-for-Shape-Manipulation
|
0d39a192a62c0ebf15892af42899d74bfad718ca
|
bfb644e3bcc7c5eb871b11374879a822aeb9bf1a
|
refs/heads/master
| 2023-08-27T15:02:13.789777
| 2021-11-10T09:53:45
| 2021-11-10T09:53:45
| 318,131,877
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 21,916
|
cpp
|
#include "deformationGraph.h"
DeformationGraph::DeformationGraph()
{
}
void DeformationGraph::Init(_GLMmodel* originMesh, _GLMmodel* samplingMesh)
{
this->originMesh = originMesh;
this->samplingMesh = samplingMesh;
k_nearest = 8;
w_rot = 1.0f;
w_reg = 10.0f;
w_con = 100.0f;
sample_controls = 0;
sample_nodes = samplingMesh->numvertices;
InitRotAndTrans();
CalConnectedMap();
CalSamplingVertices();
CalEmbeddedWeights();
CalDeformationGraphWeights();
default_sampling_vertices = vector<Vector3f>(sample_nodes);
for (int i = 0; i < sample_nodes; ++i)
{
default_sampling_vertices[i] = Vector3f(
samplingMesh->vertices[(i + 1) * 3 + 0],
samplingMesh->vertices[(i + 1) * 3 + 1],
samplingMesh->vertices[(i + 1) * 3 + 2]);
}
default_origin_vertices = vector<Vector3f>(originMesh->numvertices);
for (int i = 0; i < originMesh->numvertices; ++i)
{
default_origin_vertices[i] = Vector3f(
originMesh->vertices[(i + 1) * 3 + 0],
originMesh->vertices[(i + 1) * 3 + 1],
originMesh->vertices[(i + 1) * 3 + 2]);
}
for (auto iter = connectedMap.begin(); iter != connectedMap.end(); ++iter)
{
sample_edges += (*iter).second.size();
}
sample_edges /= 2;
}
void DeformationGraph::InitRotAndTrans()
{
rot.resize(sample_nodes);
trans.resize(sample_nodes);
Matrix3f temp_r = Matrix3f::Zero();
Vector3f temp_t = Vector3f::Zero();
temp_r(0, 0) = temp_r(1, 1) = temp_r(2, 2) = 1.0f;
for (int i = 0; i < sample_nodes; ++i)
{
rot[i] = temp_r;
trans[i] = temp_t;
}
}
void DeformationGraph::CalSamplingVertices()
{
for (int i = 1; i <= samplingMesh->numvertices; ++i)
{
float min = INT_MAX;
int idx = 0;
for (int j = 1; j <= originMesh->numvertices; ++j)
{
float temp = fabs(samplingMesh->vertices[i * 3 + 0] - originMesh->vertices[j * 3 + 0])
+ fabs(samplingMesh->vertices[i * 3 + 1] - originMesh->vertices[j * 3 + 1])
+ fabs(samplingMesh->vertices[i * 3 + 2] - originMesh->vertices[j * 3 + 2]);
if (temp < min)
{
min = temp;
idx = j;
}
}
sample_idices.push_back(idx);
samplingMesh->vertices[i * 3 + 0] = originMesh->vertices[idx * 3 + 0];
samplingMesh->vertices[i * 3 + 1] = originMesh->vertices[idx * 3 + 1];
samplingMesh->vertices[i * 3 + 2] = originMesh->vertices[idx * 3 + 2];
}
cout << "Fit Sample Vertices:" << sample_idices.size() << endl;
}
void DeformationGraph::CalConnectedMap()
{
for (int i = 0; i < samplingMesh->numtriangles; ++i)
{
for (int j = 0; j < 3; ++j)
{
connectedMap.insert(pair<int, set<int>>(samplingMesh->triangles[i].vindices[j], set<int>()));
connectedMap[samplingMesh->triangles[i].vindices[j]].insert(samplingMesh->triangles[i].vindices[(j + 1) % 3]);
connectedMap[samplingMesh->triangles[i].vindices[j]].insert(samplingMesh->triangles[i].vindices[(j + 2) % 3]);
}
}
}
void DeformationGraph::Run()
{
UpdateSampleVertices();
GaussainNewton();
}
void DeformationGraph::UpdateDeformationGraph()
{
for (int i = 0; i < sample_nodes; ++i)
{
samplingMesh->vertices[(i + 1) * 3 + 0] += trans[i][0];
samplingMesh->vertices[(i + 1) * 3 + 1] += trans[i][1];
samplingMesh->vertices[(i + 1) * 3 + 2] += trans[i][2];
}
}
void DeformationGraph::UpdateSampleVertices()
{
for (int i = 0; i < sample_nodes; ++i)
{
samplingMesh->vertices[(i + 1) * 3 + 0] = default_sampling_vertices[i][0];
samplingMesh->vertices[(i + 1) * 3 + 1] = default_sampling_vertices[i][1];
samplingMesh->vertices[(i + 1) * 3 + 2] = default_sampling_vertices[i][2];
}
for (int i = 0; i < originMesh->numvertices; ++i)
{
originMesh->vertices[(i + 1) * 3 + 0] = default_origin_vertices[i][0];
originMesh->vertices[(i + 1) * 3 + 1] = default_origin_vertices[i][1];
originMesh->vertices[(i + 1) * 3 + 2] = default_origin_vertices[i][2];
}
}
void DeformationGraph::UpdateOriginMesh()
{
int nodes = originMesh->numvertices;
vector<Vector3f> results(nodes);
for (int i = 0; i < nodes; ++i)
{
Vector3f result(0, 0, 0);
Vector3f vi = Vector3f(
originMesh->vertices[(i + 1) * 3 + 0],
originMesh->vertices[(i + 1) * 3 + 1],
originMesh->vertices[(i + 1) * 3 + 2]);
for (int j = 0; j < k_nearest; ++j)
{
Vector3f gj = Vector3f(
samplingMesh->vertices[(embeddedWeights[i][j].first) * 3 + 0],
samplingMesh->vertices[(embeddedWeights[i][j].first) * 3 + 1],
samplingMesh->vertices[(embeddedWeights[i][j].first) * 3 + 2]);
result += (embeddedWeights[i][j].second) * (rot[embeddedWeights[i][j].first - 1] * (vi - gj) + gj + trans[embeddedWeights[i][j].first - 1]);
}
results[i] = result;
}
for (int i = 0; i < nodes; ++i)
{
originMesh->vertices[(i + 1) * 3 + 0] = results[i][0];
originMesh->vertices[(i + 1) * 3 + 1] = results[i][1];
originMesh->vertices[(i + 1) * 3 + 2] = results[i][2];
}
}
void DeformationGraph::GaussainNewton()
{
const float epsilon = 1e-3;
const int iter_max = 5;
float err_current = 1, err_past = 2;
SparseMatrix<float> J(6 * sample_nodes + 6 * sample_edges + 3 * sample_controls, 12 * sample_nodes);
MatrixXf f, h, x(12 * sample_nodes, 1);
InitRotAndTrans();
for (int i = 0; i < sample_nodes; ++i)
{
for (int j = 0; j < 9; ++j) x(i * 12 + j, 0) = rot[i](j / 3, j % 3);
for (int j = 0; j < 3; ++j) x(i * 12 + 9 + j, 0) = trans[i](j);
}
cout << "------------------- Start -------------------" << endl;
err_current = F(x);
for (int i = 0; i < iter_max && fabs(err_past - err_current) > epsilon && err_current > epsilon; ++i)
{
err_past = err_current;
Calf(f);
CalJ(J);
SparseMatrix<float> Jt = J.transpose();
SparseMatrix<float> JtJ = J.transpose() * J;
SimplicialCholesky<SparseMatrix<float>> solver(Jt * J);
MatrixXf h = solver.solve(Jt * f);
x = h;
cout << "---------------------------------------\n";
cout << "Iteration: " << i + 1<< endl;
err_current = F(x);
cout << "Error: " << err_current << endl;
}
cout << "------------------- Finished -------------------\n" << endl;
}
void DeformationGraph::Calf(MatrixXf &f)
{
int idx = 0;
MatrixXf fx = MatrixXf::Zero(6 * sample_nodes + (3 * sample_edges) * 2 + 3 * sample_controls, 1);
// Erot
for (int i = 0; i < sample_nodes; ++i)
{
fx(idx++, 0) = rot[i].col(0).dot(rot[i].col(1)) * sqrt(w_rot);
fx(idx++, 0) = rot[i].col(0).dot(rot[i].col(2)) * sqrt(w_rot);
fx(idx++, 0) = rot[i].col(1).dot(rot[i].col(2)) * sqrt(w_rot);
fx(idx++, 0) = sqrt(w_rot);
fx(idx++, 0) = sqrt(w_rot);
fx(idx++, 0) = sqrt(w_rot);
}
// Ereg
for (int j = 0; j < sample_nodes; ++j)
{
Vector3f gj = Vector3f(
samplingMesh->vertices[(j + 1) * 3 + 0],
samplingMesh->vertices[(j + 1) * 3 + 1],
samplingMesh->vertices[(j + 1) * 3 + 2]);
for (auto iter = connectedMap[j + 1].begin(); iter != connectedMap[j + 1].end(); ++iter)
{
int k = *iter - 1;
Vector3f gk = Vector3f(
samplingMesh->vertices[(k + 1) * 3 + 0],
samplingMesh->vertices[(k + 1) * 3 + 1],
samplingMesh->vertices[(k + 1) * 3 + 2]);
Vector3f temp = (gk - gj) * sqrt(w_reg);
fx(idx++, 0) = temp(0);
fx(idx++, 0) = temp(1);
fx(idx++, 0) = temp(2);
}
}
// Econ
for (int i = 0; i < control_points_data.size(); ++i)
{
for (int j = 0; j < control_points_data[i].size(); ++j)
{
Vector3f temp = Vector3f(
control_points_data[i][j][0] - samplingMesh->vertices[control_points_id[i][j] * 3 + 0],
control_points_data[i][j][1] - samplingMesh->vertices[control_points_id[i][j] * 3 + 1],
control_points_data[i][j][2] - samplingMesh->vertices[control_points_id[i][j] * 3 + 2]) * sqrt(w_con);
fx(idx++, 0) = temp(0);
fx(idx++, 0) = temp(1);
fx(idx++, 0) = temp(2);
}
}
f = fx;
}
void DeformationGraph::CalJ(SparseMatrix<float>& J)
{
int idx = 0;
vector<Triplet<float>> Jacobi;
// Erot
for (int i = 0; i < sample_nodes; ++i)
{
Jacobi.push_back(Triplet<float>(idx, 0 + 12 * i, rot[i](0, 1)));
Jacobi.push_back(Triplet<float>(idx, 1 + 12 * i, rot[i](1, 1)));
Jacobi.push_back(Triplet<float>(idx, 2 + 12 * i, rot[i](2, 1)));
Jacobi.push_back(Triplet<float>(idx, 3 + 12 * i, rot[i](0, 0)));
Jacobi.push_back(Triplet<float>(idx, 4 + 12 * i, rot[i](1, 0)));
Jacobi.push_back(Triplet<float>(idx, 5 + 12 * i, rot[i](2, 0)));
idx++;
Jacobi.push_back(Triplet<float>(idx, 0 + 12 * i, rot[i](0, 2)));
Jacobi.push_back(Triplet<float>(idx, 1 + 12 * i, rot[i](1, 2)));
Jacobi.push_back(Triplet<float>(idx, 2 + 12 * i, rot[i](2, 2)));
Jacobi.push_back(Triplet<float>(idx, 6 + 12 * i, rot[i](0, 0)));
Jacobi.push_back(Triplet<float>(idx, 7 + 12 * i, rot[i](1, 0)));
Jacobi.push_back(Triplet<float>(idx, 8 + 12 * i, rot[i](2, 0)));
idx++;
Jacobi.push_back(Triplet<float>(idx, 3 + 12 * i, rot[i](0, 2)));
Jacobi.push_back(Triplet<float>(idx, 4 + 12 * i, rot[i](1, 2)));
Jacobi.push_back(Triplet<float>(idx, 5 + 12 * i, rot[i](2, 2)));
Jacobi.push_back(Triplet<float>(idx, 6 + 12 * i, rot[i](0, 1)));
Jacobi.push_back(Triplet<float>(idx, 7 + 12 * i, rot[i](1, 1)));
Jacobi.push_back(Triplet<float>(idx, 8 + 12 * i, rot[i](2, 1)));
idx++;
for (int j = 0; j < 9; ++j)
{
if (j == 3 || j == 6) ++idx;
Jacobi.push_back(Triplet<float>(idx, 12 * i + j, rot[i](j / 3, j % 3)));
}
idx++;
}
// Ereg
for (int j = 0; j < sample_nodes; ++j)
{
for (auto iter = connectedMap[j + 1].begin(); iter != connectedMap[j + 1].end(); ++iter)
{
int k = *iter - 1;
vector3 ekj = vector3(
samplingMesh->vertices[(k + 1) * 3 + 0] - samplingMesh->vertices[(j + 1) * 3 + 0],
samplingMesh->vertices[(k + 1) * 3 + 1] - samplingMesh->vertices[(j + 1) * 3 + 1],
samplingMesh->vertices[(k + 1) * 3 + 2] - samplingMesh->vertices[(j + 1) * 3 + 2]) * sqrt(w_reg);
for (int p = 0; p < 3; ++p)
{
for (int q = 0; q < 3; ++q)
{
Jacobi.push_back(Triplet<float>(idx, 12 * j + p * 3 + q, ekj[q]));
}
Jacobi.push_back(Triplet<float>(idx, 12 * j + 9 + p, sqrt(w_reg)));
Jacobi.push_back(Triplet<float>(idx, 12 * k + 9 + p, -sqrt(w_reg)));
idx++;
}
}
}
// Econ
for (int i = 0; i < control_points_id.size(); ++i)
{
for (int j = 0; j < control_points_id[i].size(); ++j)
{
Jacobi.push_back(Triplet<float>(idx++, 9 + 12 * (control_points_id[i][j] - 1) + 0, sqrt(w_con)));
Jacobi.push_back(Triplet<float>(idx++, 9 + 12 * (control_points_id[i][j] - 1) + 1, sqrt(w_con)));
Jacobi.push_back(Triplet<float>(idx++, 9 + 12 * (control_points_id[i][j] - 1) + 2, sqrt(w_con)));
}
}
J.setFromTriplets(Jacobi.begin(), Jacobi.end());
}
float DeformationGraph::F(MatrixXf &x)
{
float err = 0;
for (int i = 0; i < sample_nodes; ++i)
{
for (int j = 0; j < 9; ++j) rot[i](j / 3, j % 3) = x(12 * i + j, 0);
for (int j = 0; j < 3; ++j) trans[i][j] = x(12 * i + 9 + j, 0);
}
UpdateOriginMesh();
UpdateDeformationGraph();
float Erot = CalErot(), Ereg = CalEreg(), Econ = CalEcon();
cout << "Erot: " << Erot << ", Ereg: " << Ereg << ", Econ: " << Econ << endl;
err = w_rot * Erot + w_reg * Ereg + w_con * Econ;
return err;
}
float DeformationGraph::CalEreg()
{
float Ereg = 0;
for (int j = 0; j < sample_nodes; ++j)
{
Vector3f gj = Vector3f(
samplingMesh->vertices[(j + 1) * 3 + 0],
samplingMesh->vertices[(j + 1) * 3 + 1],
samplingMesh->vertices[(j + 1) * 3 + 2]);
for (auto iter = connectedMap[j + 1].begin(); iter != connectedMap[j + 1].end(); ++iter)
{
int k = *iter - 1;
Vector3f gk = Vector3f(
samplingMesh->vertices[(k + 1) * 3 + 0],
samplingMesh->vertices[(k + 1) * 3 + 1],
samplingMesh->vertices[(k + 1) * 3 + 2]);
Ereg += pow((rot[j] * (gk - gj) + gj + trans[j] - (gk + trans[k])).norm(), 2);
}
}
return Ereg;
}
float DeformationGraph::CalErot()
{
float Erot = 0;
for (int i = 0; i < sample_nodes; ++i)
{
Erot += pow(rot[i].col(0).dot(rot[i].col(1)), 2);
Erot += pow(rot[i].col(0).dot(rot[i].col(2)), 2);
Erot += pow(rot[i].col(1).dot(rot[i].col(2)), 2);
Erot += pow(rot[i].col(0).dot(rot[i].col(0)) - 1, 2);
Erot += pow(rot[i].col(1).dot(rot[i].col(1)) - 1, 2);
Erot += pow(rot[i].col(2).dot(rot[i].col(2)) - 1, 2);
}
return Erot;
}
float DeformationGraph::CalEcon()
{
float Econ = 0;
for (int i = 0; i < control_points_id.size(); ++i)
{
for (int j = 0; j < control_points_id[i].size(); ++j)
{
int idx = control_points_id[i][j];
Econ += pow(fabs(samplingMesh->vertices[idx * 3 + 0] - control_points_data[i][j][0]), 2);
Econ += pow(fabs(samplingMesh->vertices[idx * 3 + 1] - control_points_data[i][j][1]), 2);
Econ += pow(fabs(samplingMesh->vertices[idx * 3 + 2] - control_points_data[i][j][2]), 2);
}
}
return Econ;
}
void DeformationGraph::CalDeformationGraphWeights()
{
vector<vector<float>> distance(sample_nodes);
vector<vector<int>> index(sample_nodes);
for (int i = 0; i < sample_nodes; ++i)
{
vector<float> temp_d(sample_nodes);
vector<int> temp_i(sample_nodes);
vector3 temp_v;
for (int j = 0; j < sample_nodes; ++j)
{
temp_v = vector3(
samplingMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[(j + 1) * 3 + 0],
samplingMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[(j + 1) * 3 + 1],
samplingMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[(j + 1) * 3 + 2]);
temp_d[j] = sqrt(temp_v[0] * temp_v[0] + temp_v[1] * temp_v[1] + temp_v[2] * temp_v[2]);
temp_i[j] = j;
}
distance[i] = temp_d;
index[i] = temp_i;
}
deformationGraphWeights = vector<vector<pair<int, float>>>(sample_nodes);
for (int i = 0; i < sample_nodes; ++i)
{
vector<pair<int, float>> temp_p(k_nearest + 1);
for (int j = 0; j < k_nearest + 1; ++j)
{
int idx_min = j;
for (int k = j + 1; k < sample_nodes; ++k)
{
if (distance[i][k] < distance[i][idx_min]) idx_min = k;
}
float temp = distance[i][j];
distance[i][j] = distance[i][idx_min];
distance[i][idx_min] = temp;
int temp_i = index[i][j];
index[i][j] = index[i][idx_min];
index[i][idx_min] = temp_i;
temp_p[j] = pair<int, float>(index[i][j] + 1, distance[i][j]);
}
deformationGraphWeights[i] = temp_p;
}
for (int i = 0; i < sample_nodes; ++i)
{
vector3 temp = vector3(
samplingMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[deformationGraphWeights[i][k_nearest].first * 3 + 0],
samplingMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[deformationGraphWeights[i][k_nearest].first * 3 + 1],
samplingMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[deformationGraphWeights[i][k_nearest].first * 3 + 2]);
float d_max = sqrt(temp[0] * temp[0] + temp[1] * temp[1] + temp[2] * temp[2]);
float sum = 0;
for (int j = 0; j < k_nearest; ++j)
{
temp = vector3(
samplingMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[deformationGraphWeights[i][j].first * 3 + 0],
samplingMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[deformationGraphWeights[i][j].first * 3 + 1],
samplingMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[deformationGraphWeights[i][j].first * 3 + 2]);
float d = sqrt(temp[0] * temp[0] + temp[1] * temp[1] + temp[2] * temp[2]);
deformationGraphWeights[i][j].second = pow(1 - d / d_max, 2);
sum += deformationGraphWeights[i][j].second;
}
for (int j = 0; j < k_nearest; ++j)
{
deformationGraphWeights[i][j].second /= sum;
if (k_nearest == 1) deformationGraphWeights[i][j].second = 1;
}
}
}
void DeformationGraph::CalEmbeddedWeights()
{
int nodes = originMesh->numvertices;
vector<vector<float>> distance(nodes);
vector<vector<int>> index(nodes);
for (int i = 0; i < nodes; ++i)
{
vector<float> temp_d(sample_nodes);
vector<int> temp_i(sample_nodes);
vector3 temp_v;
for (int j = 0; j < sample_nodes; ++j)
{
temp_v = vector3(
originMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[(j + 1) * 3 + 0],
originMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[(j + 1) * 3 + 1],
originMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[(j + 1) * 3 + 2]);
temp_d[j] = sqrt(temp_v[0] * temp_v[0] + temp_v[1] * temp_v[1] + temp_v[2] * temp_v[2]);
temp_i[j] = j;
}
distance[i] = temp_d;
index[i] = temp_i;
}
embeddedWeights = vector<vector<pair<int, float>>>(nodes);
for (int i = 0; i < nodes; ++i)
{
vector<pair<int, float>> temp_p(k_nearest + 1);
for (int j = 0; j < k_nearest + 1; ++j)
{
int idx_min = j;
for (int k = j + 1; k < sample_nodes; ++k)
{
if (distance[i][k] < distance[i][idx_min]) idx_min = k;
}
float temp = distance[i][j];
distance[i][j] = distance[i][idx_min];
distance[i][idx_min] = temp;
int temp_i = index[i][j];
index[i][j] = index[i][idx_min];
index[i][idx_min] = temp_i;
temp_p[j] = pair<int, float>(index[i][j] + 1, distance[i][j]);
}
embeddedWeights[i] = temp_p;
}
for (int i = 0; i < nodes; ++i)
{
vector3 temp = vector3(
originMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[embeddedWeights[i][k_nearest].first * 3 + 0],
originMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[embeddedWeights[i][k_nearest].first * 3 + 1],
originMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[embeddedWeights[i][k_nearest].first * 3 + 2]);
float d_max = sqrt(temp[0] * temp[0] + temp[1] * temp[1] + temp[2] * temp[2]);
float sum = 0;
for (int j = 0; j < k_nearest; ++j)
{
temp = vector3(
originMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[embeddedWeights[i][j].first * 3 + 0],
originMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[embeddedWeights[i][j].first * 3 + 1],
originMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[embeddedWeights[i][j].first * 3 + 2]);
float d = sqrt(temp[0] * temp[0] + temp[1] * temp[1] + temp[2] * temp[2]);
embeddedWeights[i][j].second = pow(1 - d / d_max, 2);
sum += embeddedWeights[i][j].second;
}
for (int j = 0; j < k_nearest; ++j)
{
embeddedWeights[i][j].second /= sum;
if (k_nearest == 1) embeddedWeights[i][j].second = 1;
}
}
}
void DeformationGraph::SetControlPoints(vector<vector<int>> controlPoints)
{
control_points_id = controlPoints;
for (int i = control_points_data.size(); i < control_points_id.size(); ++i)
{
vector<vector3> temp_p;
vector3 temp_v;
for (int j = 0; j < control_points_id[i].size(); ++j)
{
temp_v = vector3(
samplingMesh->vertices[control_points_id[i][j] * 3 + 0],
samplingMesh->vertices[control_points_id[i][j] * 3 + 1],
samplingMesh->vertices[control_points_id[i][j] * 3 + 2]);
temp_p.push_back(temp_v);
}
control_points_data.push_back(temp_p);
}
sample_controls = 0;
for (int i = 0; i < controlPoints.size(); ++i)
{
sample_controls += controlPoints[i].size();
}
}
void DeformationGraph::SetControlPointsTranslate(int selectedId, vector3 vec)
{
for (int i = 0; i < control_points_id[selectedId].size(); i++)
{
int idx = control_points_id[selectedId][i];
control_points_data[selectedId][i] += vec;
}
}
vector<int> DeformationGraph::GetSamplingIndices()
{
return sample_idices;
}
|
[
"shizsun0609tw@gmail.com"
] |
shizsun0609tw@gmail.com
|
c1c188e308ae0fe7e7a71b0f1dcc8afaa0c42540
|
fd240741384ec0d304b3591bc6edc8548db81c54
|
/src/search-skeleton/Model/Edge/Edge_V2/EdgeV2.hpp
|
3a1f91ee315dbdfa580343fdec2fa61ab90c99bd
|
[
"MIT"
] |
permissive
|
timoninas/diploma-2020
|
686023bca4eb1703ed17f8acfc0ad3400ccefa63
|
f111ed8b5eb46627921360f1d73f27094f1031c5
|
refs/heads/master
| 2023-05-06T10:43:29.925024
| 2021-06-02T19:47:06
| 2021-06-02T19:47:06
| 330,481,173
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,375
|
hpp
|
//
// EdgeV2.hpp
// search-skeleton
//
// Created by Антон Тимонин on 05.04.2021.
//
#ifndef EdgeV2_hpp
#define EdgeV2_hpp
#include "../../GraphLabel/GraphLabel.hpp"
#include "../../Point/Point_V1/Point.hpp"
#include <stdio.h>
#include <utility>
typedef struct edge_v2 {
int numberEdge;
std::pair<int, int> numberVertices;
GraphLabels label;
edge_v2() = delete;
edge_v2(int number, int numberVertex1, int numberVertex2):
numberEdge(number),
numberVertices(std::make_pair(numberVertex1, numberVertex2)),
label(GraphLabels::notvisited) { }
bool isNotvisited() {
return label == GraphLabels::notvisited;
}
bool isVisited() {
return label == GraphLabels::visited;
}
bool isInskeleton() {
return label == GraphLabels::inskeleton;
}
void swipeVertices() {
auto tmp = numberVertices.first;
numberVertices.first = numberVertices.second;
numberVertices.second = tmp;
}
} edge_v2_t;
struct cmp_v2 {
bool operator() (const edge_v2_t &a, const edge_v2_t &b) {
return a.numberVertices.first < b.numberVertices.first || a.numberVertices.second < b.numberVertices.second;
}
};
#endif /* EdgeV2_hpp */
|
[
"dotruger.37@gmail.com"
] |
dotruger.37@gmail.com
|
c7e21c79ce487e3bac74a8bd5a338c49635898f6
|
9df55ed98688ff13caec3061237a2a0895914577
|
/main.cpp
|
bd29e05649bceeeba97307229ac0bcc781176516
|
[] |
no_license
|
tiashaun/sdl_tetris
|
f625ee0f06e642411f7a04b18b470aa0df61c1ca
|
4799cfa4b28cd21b8431f8b6a00bacfb89e794f0
|
refs/heads/master
| 2020-11-30T23:32:43.812813
| 2009-12-06T20:33:43
| 2009-12-06T20:33:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 165
|
cpp
|
#include <iostream>
#include <SDL/SDL.h>
#include "Game.h"
int main(int argc, char* argv[]) {
Game *game = new Game();
game->startGame();
return 0;
}
|
[
"jarod.luebbert@gmail.com"
] |
jarod.luebbert@gmail.com
|
7138122f020c522047ea09bee87629eccc35d3a6
|
18904ac4e30a87b7c9d5ae569502b60589ed47b0
|
/source/audio/audioBuffers.hpp
|
ac64c7e30e81d7087285bab4055174eb91867d07
|
[
"MIT",
"Zlib",
"Apache-2.0",
"BSD-2-Clause",
"CC0-1.0"
] |
permissive
|
JoaoBaptMG/gba-modern
|
a51bce4464e3347cbea216808bafb440347f8e0d
|
dfb5757d25cbfa7ee795fa8be521f010661b2293
|
refs/heads/master
| 2023-07-19T18:32:12.849729
| 2023-06-26T14:17:27
| 2023-06-26T14:41:45
| 201,576,240
| 83
| 5
|
MIT
| 2020-12-01T11:07:13
| 2019-08-10T03:52:52
|
C++
|
UTF-8
|
C++
| false
| false
| 667
|
hpp
|
//--------------------------------------------------------------------------------
// audioBuffers.hpp
//--------------------------------------------------------------------------------
// Declare the audio mixer's private data
//--------------------------------------------------------------------------------
#pragma once
#include "data/audio-settings.hpp"
#include <tonc.h>
// Declare the mix buffers
extern s8 audioMixBuffersLeft[2][audio::BufferSize];
extern s8 audioMixBuffersRight[2][audio::BufferSize];
extern s8* curAudioMixBufferLeft;
extern s8* curAudioMixBufferRight;
extern u32 curFrame;
// The audio vblank is internal
void audioVblank() IWRAM_CODE;
|
[
"jbaptistapsilva@yahoo.com.br"
] |
jbaptistapsilva@yahoo.com.br
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.