hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
cf587ef4acde1693b48b94fe816d0f62da1c7c18
58,240
cc
C++
pmem-mariadb/sql/multi_range_read.cc
wc222/pmdk-examples
64aadc3a70471c469ac8e214eb1e04ff47cf18ff
[ "BSD-3-Clause" ]
1
2019-10-31T08:25:52.000Z
2019-10-31T08:25:52.000Z
pmem-mariadb/sql/multi_range_read.cc
WSCWDA/pmdk-examples
c3d079e52cd18b0e14836ef42bad9a995336bf90
[ "BSD-3-Clause" ]
1
2021-02-24T05:26:44.000Z
2021-02-24T05:26:44.000Z
pmem-mariadb/sql/multi_range_read.cc
isabella232/pmdk-examples
be7a5a18ba7bb8931e512f6d552eadf820fa2235
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2010, 2011 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ #include "mariadb.h" #include "sql_parse.h" #include <my_bit.h> #include "sql_select.h" #include "key.h" /**************************************************************************** * Default MRR implementation (MRR to non-MRR converter) ***************************************************************************/ /** Get cost and other information about MRR scan over a known list of ranges Calculate estimated cost and other information about an MRR scan for given sequence of ranges. @param keyno Index number @param seq Range sequence to be traversed @param seq_init_param First parameter for seq->init() @param n_ranges_arg Number of ranges in the sequence, or 0 if the caller can't efficiently determine it @param bufsz INOUT IN: Size of the buffer available for use OUT: Size of the buffer that is expected to be actually used, or 0 if buffer is not needed. @param flags INOUT A combination of HA_MRR_* flags @param cost OUT Estimated cost of MRR access @note This method (or an overriding one in a derived class) must check for thd->killed and return HA_POS_ERROR if it is not zero. This is required for a user to be able to interrupt the calculation by killing the connection/query. @retval HA_POS_ERROR Error or the engine is unable to perform the requested scan. Values of OUT parameters are undefined. @retval other OK, *cost contains cost of the scan, *bufsz and *flags contain scan parameters. */ ha_rows handler::multi_range_read_info_const(uint keyno, RANGE_SEQ_IF *seq, void *seq_init_param, uint n_ranges_arg, uint *bufsz, uint *flags, Cost_estimate *cost) { KEY_MULTI_RANGE range; range_seq_t seq_it; ha_rows rows, total_rows= 0; uint n_ranges=0; THD *thd= table->in_use; /* Default MRR implementation doesn't need buffer */ *bufsz= 0; seq_it= seq->init(seq_init_param, n_ranges, *flags); while (!seq->next(seq_it, &range)) { if (unlikely(thd->killed != 0)) return HA_POS_ERROR; n_ranges++; key_range *min_endp, *max_endp; if (range.range_flag & GEOM_FLAG) { /* In this case tmp_min_flag contains the handler-read-function */ range.start_key.flag= (ha_rkey_function) (range.range_flag ^ GEOM_FLAG); min_endp= &range.start_key; max_endp= NULL; } else { min_endp= range.start_key.length? &range.start_key : NULL; max_endp= range.end_key.length? &range.end_key : NULL; } if ((range.range_flag & UNIQUE_RANGE) && !(range.range_flag & NULL_RANGE)) rows= 1; /* there can be at most one row */ else { if (HA_POS_ERROR == (rows= this->records_in_range(keyno, min_endp, max_endp))) { /* Can't scan one range => can't do MRR scan at all */ total_rows= HA_POS_ERROR; break; } } total_rows += rows; } if (total_rows != HA_POS_ERROR) { /* The following calculation is the same as in multi_range_read_info(): */ *flags |= HA_MRR_USE_DEFAULT_IMPL; cost->reset(); cost->avg_io_cost= 1; /* assume random seeks */ if ((*flags & HA_MRR_INDEX_ONLY) && total_rows > 2) cost->io_count= keyread_time(keyno, n_ranges, (uint)total_rows); else cost->io_count= read_time(keyno, n_ranges, total_rows); cost->cpu_cost= (double) total_rows / TIME_FOR_COMPARE + 0.01; } return total_rows; } /** Get cost and other information about MRR scan over some sequence of ranges Calculate estimated cost and other information about an MRR scan for some sequence of ranges. The ranges themselves will be known only at execution phase. When this function is called we only know number of ranges and a (rough) E(#records) within those ranges. Currently this function is only called for "n-keypart singlepoint" ranges, i.e. each range is "keypart1=someconst1 AND ... AND keypartN=someconstN" The flags parameter is a combination of those flags: HA_MRR_SORTED, HA_MRR_INDEX_ONLY, HA_MRR_NO_ASSOCIATION, HA_MRR_LIMITS. @param keyno Index number @param n_ranges Estimated number of ranges (i.e. intervals) in the range sequence. @param n_rows Estimated total number of records contained within all of the ranges @param bufsz INOUT IN: Size of the buffer available for use OUT: Size of the buffer that will be actually used, or 0 if buffer is not needed. @param flags INOUT A combination of HA_MRR_* flags @param cost OUT Estimated cost of MRR access @retval 0 OK, *cost contains cost of the scan, *bufsz and *flags contain scan parameters. @retval other Error or can't perform the requested scan */ ha_rows handler::multi_range_read_info(uint keyno, uint n_ranges, uint n_rows, uint key_parts, uint *bufsz, uint *flags, Cost_estimate *cost) { /* Currently we expect this function to be called only in preparation of scan with HA_MRR_SINGLE_POINT property. */ DBUG_ASSERT(*flags | HA_MRR_SINGLE_POINT); *bufsz= 0; /* Default implementation doesn't need a buffer */ *flags |= HA_MRR_USE_DEFAULT_IMPL; cost->reset(); cost->avg_io_cost= 1; /* assume random seeks */ /* Produce the same cost as non-MRR code does */ if (*flags & HA_MRR_INDEX_ONLY) cost->io_count= keyread_time(keyno, n_ranges, n_rows); else cost->io_count= read_time(keyno, n_ranges, n_rows); return 0; } /** Initialize the MRR scan Initialize the MRR scan. This function may do heavyweight scan initialization like row prefetching/sorting/etc (NOTE: but better not do it here as we may not need it, e.g. if we never satisfy WHERE clause on previous tables. For many implementations it would be natural to do such initializations in the first multi_read_range_next() call) mode is a combination of the following flags: HA_MRR_SORTED, HA_MRR_INDEX_ONLY, HA_MRR_NO_ASSOCIATION @param seq Range sequence to be traversed @param seq_init_param First parameter for seq->init() @param n_ranges Number of ranges in the sequence @param mode Flags, see the description section for the details @param buf INOUT: memory buffer to be used @note One must have called index_init() before calling this function. Several multi_range_read_init() calls may be made in course of one query. Buffer memory management is done according to the following scenario: The caller allocates the buffer and provides it to the callee by filling the members of HANDLER_BUFFER structure. The callee consumes all or some fraction of the provided buffer space, and sets the HANDLER_BUFFER members accordingly. The callee may use the buffer memory until the next multi_range_read_init() call is made, all records have been read, or until index_end() call is made, whichever comes first. @retval 0 OK @retval 1 Error */ int handler::multi_range_read_init(RANGE_SEQ_IF *seq_funcs, void *seq_init_param, uint n_ranges, uint mode, HANDLER_BUFFER *buf) { DBUG_ENTER("handler::multi_range_read_init"); mrr_iter= seq_funcs->init(seq_init_param, n_ranges, mode); mrr_funcs= *seq_funcs; mrr_is_output_sorted= MY_TEST(mode & HA_MRR_SORTED); mrr_have_range= FALSE; DBUG_RETURN(0); } /** Get next record in MRR scan Default MRR implementation: read the next record @param range_info OUT Undefined if HA_MRR_NO_ASSOCIATION flag is in effect Otherwise, the opaque value associated with the range that contains the returned record. @retval 0 OK @retval other Error code */ int handler::multi_range_read_next(range_id_t *range_info) { int result= HA_ERR_END_OF_FILE; bool range_res; DBUG_ENTER("handler::multi_range_read_next"); if (!mrr_have_range) { mrr_have_range= TRUE; goto start; } do { /* Save a call if there can be only one row in range. */ if (mrr_cur_range.range_flag != (UNIQUE_RANGE | EQ_RANGE)) { result= read_range_next(); /* On success or non-EOF errors jump to the end. */ if (result != HA_ERR_END_OF_FILE) break; } else { if (ha_was_semi_consistent_read()) { /* The following assignment is redundant, but for extra safety and to remove the compiler warning: */ range_res= FALSE; goto scan_it_again; } /* We need to set this for the last range only, but checking this condition is more expensive than just setting the result code. */ result= HA_ERR_END_OF_FILE; } start: /* Try the next range(s) until one matches a record. */ while (!(range_res= mrr_funcs.next(mrr_iter, &mrr_cur_range))) { scan_it_again: result= read_range_first(mrr_cur_range.start_key.keypart_map ? &mrr_cur_range.start_key : 0, mrr_cur_range.end_key.keypart_map ? &mrr_cur_range.end_key : 0, MY_TEST(mrr_cur_range.range_flag & EQ_RANGE), mrr_is_output_sorted); if (result != HA_ERR_END_OF_FILE) break; } } while ((result == HA_ERR_END_OF_FILE) && !range_res); *range_info= mrr_cur_range.ptr; DBUG_PRINT("exit",("handler::multi_range_read_next result %d", result)); DBUG_RETURN(result); } /**************************************************************************** * Mrr_*_reader classes (building blocks for DS-MRR) ***************************************************************************/ int Mrr_simple_index_reader::init(handler *h_arg, RANGE_SEQ_IF *seq_funcs, void *seq_init_param, uint n_ranges, uint mode, Key_parameters *key_par_arg, Lifo_buffer *key_buffer_arg, Buffer_manager *buf_manager_arg) { HANDLER_BUFFER no_buffer = {NULL, NULL, NULL}; file= h_arg; return file->handler::multi_range_read_init(seq_funcs, seq_init_param, n_ranges, mode, &no_buffer); } int Mrr_simple_index_reader::get_next(range_id_t *range_info) { int res; while (!(res= file->handler::multi_range_read_next(range_info))) { KEY_MULTI_RANGE *curr_range= &file->handler::mrr_cur_range; if (!file->mrr_funcs.skip_index_tuple || !file->mrr_funcs.skip_index_tuple(file->mrr_iter, curr_range->ptr)) break; } if (res && res != HA_ERR_END_OF_FILE && res != HA_ERR_KEY_NOT_FOUND) file->print_error(res, MYF(0)); // Fatal error return res; } /** @brief Get next index record @param range_info OUT identifier of range that the returned record belongs to @note We actually iterate over nested sequences: - an ordered sequence of groups of identical keys - each key group has key value, which has multiple matching records - thus, each record matches all members of the key group @retval 0 OK, next record was successfully read @retval HA_ERR_END_OF_FILE End of records @retval Other Some other error; Error is printed */ int Mrr_ordered_index_reader::get_next(range_id_t *range_info) { int res; DBUG_ENTER("Mrr_ordered_index_reader::get_next"); for(;;) { if (!scanning_key_val_iter) { while ((res= kv_it.init(this))) { if ((res != HA_ERR_KEY_NOT_FOUND && res != HA_ERR_END_OF_FILE)) DBUG_RETURN(res); /* Some fatal error */ if (key_buffer->is_empty()) { DBUG_RETURN(HA_ERR_END_OF_FILE); } } scanning_key_val_iter= TRUE; } if ((res= kv_it.get_next(range_info))) { scanning_key_val_iter= FALSE; if ((res != HA_ERR_KEY_NOT_FOUND && res != HA_ERR_END_OF_FILE)) DBUG_RETURN(res); kv_it.move_to_next_key_value(); continue; } if (!skip_index_tuple(*range_info) && !skip_record(*range_info, NULL)) { break; } /* Go get another (record, range_id) combination */ } /* while */ DBUG_RETURN(0); } /* Supply index reader with the O(1)space it needs for scan interrupt/restore operation */ bool Mrr_ordered_index_reader::set_interruption_temp_buffer(uint rowid_length, uint key_len, uint saved_pk_len, uchar **space_start, uchar *space_end) { if (space_end - *space_start <= (ptrdiff_t)(rowid_length + key_len + saved_pk_len)) return TRUE; support_scan_interruptions= TRUE; saved_rowid= *space_start; *space_start += rowid_length; if (saved_pk_len) { saved_primary_key= *space_start; *space_start += saved_pk_len; } else saved_primary_key= NULL; saved_key_tuple= *space_start; *space_start += key_len; have_saved_rowid= FALSE; read_was_interrupted= FALSE; return FALSE; } void Mrr_ordered_index_reader::set_no_interruption_temp_buffer() { support_scan_interruptions= FALSE; saved_key_tuple= saved_rowid= saved_primary_key= NULL; /* safety */ have_saved_rowid= FALSE; read_was_interrupted= FALSE; } void Mrr_ordered_index_reader::interrupt_read() { DBUG_ASSERT(support_scan_interruptions); TABLE *table= file->get_table(); KEY *used_index= &table->key_info[file->active_index]; /* Save the current key value */ key_copy(saved_key_tuple, table->record[0], used_index, used_index->key_length); if (saved_primary_key) { key_copy(saved_primary_key, table->record[0], &table->key_info[table->s->primary_key], table->key_info[table->s->primary_key].key_length); } read_was_interrupted= TRUE; /* Save the last rowid */ memcpy(saved_rowid, file->ref, file->ref_length); have_saved_rowid= TRUE; } void Mrr_ordered_index_reader::position() { if (have_saved_rowid) memcpy(file->ref, saved_rowid, file->ref_length); else Mrr_index_reader::position(); } void Mrr_ordered_index_reader::resume_read() { TABLE *table= file->get_table(); if (!read_was_interrupted) return; KEY *used_index= &table->key_info[file->active_index]; key_restore(table->record[0], saved_key_tuple, used_index, used_index->key_length); if (saved_primary_key) { key_restore(table->record[0], saved_primary_key, &table->key_info[table->s->primary_key], table->key_info[table->s->primary_key].key_length); } } /** Fill the buffer with (lookup_tuple, range_id) pairs and sort @return 0 OK, the buffer is non-empty and sorted HA_ERR_END_OF_FILE Source exhausted, the buffer is empty. */ int Mrr_ordered_index_reader::refill_buffer(bool initial) { KEY_MULTI_RANGE cur_range; DBUG_ENTER("Mrr_ordered_index_reader::refill_buffer"); DBUG_ASSERT(key_buffer->is_empty()); if (source_exhausted) DBUG_RETURN(HA_ERR_END_OF_FILE); buf_manager->reset_buffer_sizes(buf_manager->arg); key_buffer->reset(); key_buffer->setup_writing(keypar.key_size_in_keybuf, is_mrr_assoc? sizeof(range_id_t) : 0); while (key_buffer->can_write() && !(source_exhausted= mrr_funcs.next(mrr_iter, &cur_range))) { DBUG_ASSERT(cur_range.range_flag & EQ_RANGE); /* Put key, or {key, range_id} pair into the buffer */ key_buffer->write_ptr1= keypar.use_key_pointers ? (uchar*)&cur_range.start_key.key : (uchar*)cur_range.start_key.key; key_buffer->write_ptr2= (uchar*)&cur_range.ptr; key_buffer->write(); } /* Force get_next() to start with kv_it.init() call: */ scanning_key_val_iter= FALSE; if (source_exhausted && key_buffer->is_empty()) DBUG_RETURN(HA_ERR_END_OF_FILE); if (!initial) { /* This is a non-initial buffer fill and we've got a non-empty buffer */ THD *thd= current_thd; status_var_increment(thd->status_var.ha_mrr_key_refills_count); } key_buffer->sort((key_buffer->type() == Lifo_buffer::FORWARD)? (qsort2_cmp)Mrr_ordered_index_reader::compare_keys_reverse : (qsort2_cmp)Mrr_ordered_index_reader::compare_keys, this); DBUG_RETURN(0); } int Mrr_ordered_index_reader::init(handler *h_arg, RANGE_SEQ_IF *seq_funcs, void *seq_init_param, uint n_ranges, uint mode, Key_parameters *key_par_arg, Lifo_buffer *key_buffer_arg, Buffer_manager *buf_manager_arg) { file= h_arg; key_buffer= key_buffer_arg; buf_manager= buf_manager_arg; keypar= *key_par_arg; KEY *key_info= &file->get_table()->key_info[file->active_index]; keypar.index_ranges_unique= MY_TEST(key_info->flags & HA_NOSAME && key_info->user_defined_key_parts == my_count_bits(keypar.key_tuple_map)); mrr_iter= seq_funcs->init(seq_init_param, n_ranges, mode); is_mrr_assoc= !MY_TEST(mode & HA_MRR_NO_ASSOCIATION); mrr_funcs= *seq_funcs; source_exhausted= FALSE; read_was_interrupted= false; have_saved_rowid= FALSE; return 0; } static int rowid_cmp_reverse(void *file, uchar *a, uchar *b) { return - ((handler*)file)->cmp_ref(a, b); } int Mrr_ordered_rndpos_reader::init(handler *h_arg, Mrr_index_reader *index_reader_arg, uint mode, Lifo_buffer *buf) { file= h_arg; index_reader= index_reader_arg; rowid_buffer= buf; is_mrr_assoc= !MY_TEST(mode & HA_MRR_NO_ASSOCIATION); index_reader_exhausted= FALSE; index_reader_needs_refill= TRUE; return 0; } /** DS-MRR: Fill and sort the rowid buffer Scan the MRR ranges and collect ROWIDs (or {ROWID, range_id} pairs) into buffer. When the buffer is full or scan is completed, sort the buffer by rowid and return. When this function returns, either rowid buffer is not empty, or the source of lookup keys (i.e. ranges) is exhaused. @retval 0 OK, the next portion of rowids is in the buffer, properly ordered @retval other Error */ int Mrr_ordered_rndpos_reader::refill_buffer(bool initial) { int res; bool first_call= initial; DBUG_ENTER("Mrr_ordered_rndpos_reader::refill_buffer"); if (index_reader_exhausted) DBUG_RETURN(HA_ERR_END_OF_FILE); while (initial || index_reader_needs_refill || (res= refill_from_index_reader()) == HA_ERR_END_OF_FILE) { if ((res= index_reader->refill_buffer(initial))) { if (res == HA_ERR_END_OF_FILE) index_reader_exhausted= TRUE; break; } initial= FALSE; index_reader_needs_refill= FALSE; } if (!first_call && !index_reader_exhausted) { /* Ok, this was a successful buffer refill operation */ THD *thd= current_thd; status_var_increment(thd->status_var.ha_mrr_rowid_refills_count); } DBUG_RETURN(res); } void Mrr_index_reader::position() { file->position(file->get_table()->record[0]); } /* @brief Try to refill the rowid buffer without calling index_reader->refill_buffer(). */ int Mrr_ordered_rndpos_reader::refill_from_index_reader() { range_id_t range_info; int res; DBUG_ENTER("Mrr_ordered_rndpos_reader::refill_from_index_reader"); DBUG_ASSERT(rowid_buffer->is_empty()); index_rowid= index_reader->get_rowid_ptr(); rowid_buffer->reset(); rowid_buffer->setup_writing(file->ref_length, is_mrr_assoc? sizeof(range_id_t) : 0); last_identical_rowid= NULL; index_reader->resume_read(); while (rowid_buffer->can_write()) { res= index_reader->get_next(&range_info); if (res) { if (res != HA_ERR_END_OF_FILE) DBUG_RETURN(res); index_reader_needs_refill=TRUE; break; } index_reader->position(); /* Put rowid, or {rowid, range_id} pair into the buffer */ rowid_buffer->write_ptr1= index_rowid; rowid_buffer->write_ptr2= (uchar*)&range_info; rowid_buffer->write(); } /* When index_reader_needs_refill=TRUE, this means we've got all of index tuples for lookups keys that index_reader had. We are not in the middle of an index read, so there is no need to call interrupt_read. Actually, we must not call interrupt_read(), because it could be that we haven't read a single row (because all index lookups returned HA_ERR_KEY_NOT_FOUND). In this case, interrupt_read() will cause [harmless] valgrind warnings when trying to save garbage from table->record[0]. */ if (!index_reader_needs_refill) index_reader->interrupt_read(); /* Sort the buffer contents by rowid */ rowid_buffer->sort((qsort2_cmp)rowid_cmp_reverse, (void*)file); rowid_buffer->setup_reading(file->ref_length, is_mrr_assoc ? sizeof(range_id_t) : 0); DBUG_RETURN(rowid_buffer->is_empty()? HA_ERR_END_OF_FILE : 0); } /* Get the next {record, range_id} using ordered array of rowid+range_id pairs @note Since we have sorted rowids, we try not to make multiple rnd_pos() calls with the same rowid value. */ int Mrr_ordered_rndpos_reader::get_next(range_id_t *range_info) { int res; /* First, check if rowid buffer has elements with the same rowid value as the previous. */ while (last_identical_rowid) { /* Current record (the one we've returned in previous call) was obtained from a rowid that matched multiple range_ids. Return this record again, with next matching range_id. */ (void)rowid_buffer->read(); if (rowid_buffer->read_ptr1 == last_identical_rowid) last_identical_rowid= NULL; /* reached the last of identical rowids */ if (!is_mrr_assoc) return 0; memcpy(range_info, rowid_buffer->read_ptr2, sizeof(range_id_t)); if (!index_reader->skip_record(*range_info, rowid_buffer->read_ptr1)) return 0; } /* Ok, last_identical_rowid==NULL, it's time to read next different rowid value and get record for it. */ for(;;) { /* Return eof if there are no rowids in the buffer after re-fill attempt */ if (rowid_buffer->read()) return HA_ERR_END_OF_FILE; if (is_mrr_assoc) { memcpy(range_info, rowid_buffer->read_ptr2, sizeof(range_id_t)); if (index_reader->skip_record(*range_info, rowid_buffer->read_ptr1)) continue; } res= file->ha_rnd_pos(file->get_table()->record[0], rowid_buffer->read_ptr1); if (res) return res; /* Some fatal error */ break; /* Got another record */ } /* Check if subsequent buffer elements have the same rowid value as this one. If yes, remember this fact so that we don't make any more rnd_pos() calls with this value. Note: this implies that SQL layer doesn't touch table->record[0] between calls. */ Lifo_buffer_iterator it; it.init(rowid_buffer); while (!it.read()) { if (file->cmp_ref(it.read_ptr1, rowid_buffer->read_ptr1)) break; last_identical_rowid= it.read_ptr1; } return 0; } /**************************************************************************** * Top-level DS-MRR implementation functions (the ones called by storage engine) ***************************************************************************/ /** DS-MRR: Initialize and start MRR scan Initialize and start the MRR scan. Depending on the mode parameter, this may use default or DS-MRR implementation. @param h_arg Table handler to be used @param key Index to be used @param seq_funcs Interval sequence enumeration functions @param seq_init_param Interval sequence enumeration parameter @param n_ranges Number of ranges in the sequence. @param mode HA_MRR_* modes to use @param buf INOUT Buffer to use @retval 0 Ok, Scan started. @retval other Error */ int DsMrr_impl::dsmrr_init(handler *h_arg, RANGE_SEQ_IF *seq_funcs, void *seq_init_param, uint n_ranges, uint mode, HANDLER_BUFFER *buf) { THD *thd= h_arg->get_table()->in_use; int res; Key_parameters keypar; uint UNINIT_VAR(key_buff_elem_size); /* set/used when do_sort_keys==TRUE */ handler *h_idx; Mrr_ordered_rndpos_reader *disk_strategy= NULL; bool do_sort_keys= FALSE; DBUG_ENTER("DsMrr_impl::dsmrr_init"); /* index_merge may invoke a scan on an object for which dsmrr_info[_const] has not been called, so set the owner handler here as well. */ primary_file= h_arg; is_mrr_assoc= !MY_TEST(mode & HA_MRR_NO_ASSOCIATION); strategy_exhausted= FALSE; /* By default, have do-nothing buffer manager */ buf_manager.arg= this; buf_manager.reset_buffer_sizes= do_nothing; buf_manager.redistribute_buffer_space= do_nothing; if (mode & (HA_MRR_USE_DEFAULT_IMPL | HA_MRR_SORTED)) goto use_default_impl; /* Determine whether we'll need to do key sorting and/or rnd_pos() scan */ index_strategy= NULL; if ((mode & HA_MRR_SINGLE_POINT) && optimizer_flag(thd, OPTIMIZER_SWITCH_MRR_SORT_KEYS)) { do_sort_keys= TRUE; index_strategy= &reader_factory.ordered_index_reader; } else index_strategy= &reader_factory.simple_index_reader; strategy= index_strategy; /* We don't need a rowid-to-rndpos step if - We're doing a scan on clustered primary key - [In the future] We're doing an index_only read */ DBUG_ASSERT(primary_file->inited == handler::INDEX || (primary_file->inited == handler::RND && secondary_file && secondary_file->inited == handler::INDEX)); h_idx= (primary_file->inited == handler::INDEX)? primary_file: secondary_file; keyno= h_idx->active_index; if (!(keyno == table->s->primary_key && h_idx->primary_key_is_clustered())) { strategy= disk_strategy= &reader_factory.ordered_rndpos_reader; } full_buf= buf->buffer; full_buf_end= buf->buffer_end; if (do_sort_keys) { /* Pre-calculate some parameters of key sorting */ keypar.use_key_pointers= MY_TEST(mode & HA_MRR_MATERIALIZED_KEYS); seq_funcs->get_key_info(seq_init_param, &keypar.key_tuple_length, &keypar.key_tuple_map); keypar.key_size_in_keybuf= keypar.use_key_pointers? sizeof(char*) : keypar.key_tuple_length; key_buff_elem_size= keypar.key_size_in_keybuf + (int)is_mrr_assoc * sizeof(void*); /* Ordered index reader needs some space to store an index tuple */ if (strategy != index_strategy) { uint saved_pk_length=0; if (h_idx->primary_key_is_clustered()) { uint pk= h_idx->get_table()->s->primary_key; if (pk != MAX_KEY) saved_pk_length= h_idx->get_table()->key_info[pk].key_length; } KEY *used_index= &h_idx->get_table()->key_info[h_idx->active_index]; if (reader_factory.ordered_index_reader. set_interruption_temp_buffer(primary_file->ref_length, used_index->key_length, saved_pk_length, &full_buf, full_buf_end)) goto use_default_impl; } else reader_factory.ordered_index_reader.set_no_interruption_temp_buffer(); } if (strategy == index_strategy) { /* Index strategy alone handles the record retrieval. Give all buffer space to it. Key buffer should have forward orientation so we can return the end of it. */ key_buffer= &forward_key_buf; key_buffer->set_buffer_space(full_buf, full_buf_end); /* Safety: specify that rowid buffer has zero size: */ rowid_buffer.set_buffer_space(full_buf_end, full_buf_end); if (do_sort_keys && !key_buffer->have_space_for(key_buff_elem_size)) goto use_default_impl; if ((res= index_strategy->init(primary_file, seq_funcs, seq_init_param, n_ranges, mode, &keypar, key_buffer, &buf_manager))) goto error; } else { /* We'll have both index and rndpos strategies working together */ if (do_sort_keys) { /* Both strategies will need buffer space, share the buffer */ if (setup_buffer_sharing(keypar.key_size_in_keybuf, keypar.key_tuple_map)) goto use_default_impl; buf_manager.reset_buffer_sizes= reset_buffer_sizes; buf_manager.redistribute_buffer_space= redistribute_buffer_space; } else { /* index strategy doesn't need buffer, give all space to rowids*/ rowid_buffer.set_buffer_space(full_buf, full_buf_end); if (!rowid_buffer.have_space_for(primary_file->ref_length + (int)is_mrr_assoc * sizeof(range_id_t))) goto use_default_impl; } if ((res= setup_two_handlers())) goto error; if ((res= index_strategy->init(secondary_file, seq_funcs, seq_init_param, n_ranges, mode, &keypar, key_buffer, &buf_manager)) || (res= disk_strategy->init(primary_file, index_strategy, mode, &rowid_buffer))) { goto error; } } /* At this point, we're sure that we're running a native MRR scan (i.e. we didnt fall back to default implementation for some reason). */ status_var_increment(thd->status_var.ha_mrr_init_count); res= strategy->refill_buffer(TRUE); if (res) { if (res != HA_ERR_END_OF_FILE) goto error; strategy_exhausted= TRUE; } /* If we have scanned through all intervals in *seq, then adjust *buf to indicate that the remaining buffer space will not be used. */ // if (dsmrr_eof) // buf->end_of_used_area= rowid_buffer.end_of_space(); DBUG_RETURN(0); error: close_second_handler(); /* Safety, not really needed but: */ strategy= NULL; DBUG_RETURN(res); use_default_impl: if (primary_file->inited != handler::INDEX) { /* We can get here when - we've previously successfully done a DS-MRR scan (and so have secondary_file!= NULL, secondary_file->inited= INDEX, primary_file->inited=RND) - for this invocation, we haven't got enough buffer space, and so we have to use the default MRR implementation. note: primary_file->ha_index_end() will call dsmrr_close() which will close/destroy the secondary_file, this is intentional. (Yes this is slow, but one can't expect performance with join buffer so small that it can accomodate one rowid and one index tuple) */ if ((res= primary_file->ha_rnd_end()) || (res= primary_file->ha_index_init(keyno, MY_TEST(mode & HA_MRR_SORTED)))) { DBUG_RETURN(res); } } /* Call correct init function and assign to top level object */ Mrr_simple_index_reader *s= &reader_factory.simple_index_reader; res= s->init(primary_file, seq_funcs, seq_init_param, n_ranges, mode, NULL, NULL, NULL); strategy= s; DBUG_RETURN(res); } /* Whatever the current state is, make it so that we have two handler objects: - primary_file - initialized for rnd_pos() scan - secondary_file - initialized for scanning the index specified in this->keyno RETURN 0 OK HA_XXX Error code */ int DsMrr_impl::setup_two_handlers() { int res; THD *thd= primary_file->get_table()->in_use; DBUG_ENTER("DsMrr_impl::setup_two_handlers"); if (!secondary_file) { handler *new_h2; Item *pushed_cond= NULL; DBUG_ASSERT(primary_file->inited == handler::INDEX); /* Create a separate handler object to do rnd_pos() calls. */ /* ::clone() takes up a lot of stack, especially on 64 bit platforms. The constant 5 is an empiric result. */ if (check_stack_overrun(thd, 5*STACK_MIN_SIZE, (uchar*) &new_h2)) DBUG_RETURN(1); /* Create a separate handler object to do rnd_pos() calls. */ if (!(new_h2= primary_file->clone(primary_file->get_table()->s-> normalized_path.str, thd->mem_root)) || new_h2->ha_external_lock(thd, F_RDLCK)) { delete new_h2; DBUG_RETURN(1); } if (keyno == primary_file->pushed_idx_cond_keyno) pushed_cond= primary_file->pushed_idx_cond; Mrr_reader *save_strategy= strategy; strategy= NULL; /* Caution: this call will invoke this->dsmrr_close(). Do not put the created secondary table handler new_h2 into this->secondary_file or it will delete it. Also, save the picked strategy */ res= primary_file->ha_index_end(); strategy= save_strategy; secondary_file= new_h2; if (res || (res= (primary_file->ha_rnd_init(FALSE)))) goto error; table->prepare_for_position(); secondary_file->extra(HA_EXTRA_KEYREAD); secondary_file->mrr_iter= primary_file->mrr_iter; if ((res= secondary_file->ha_index_init(keyno, FALSE))) goto error; if (pushed_cond) secondary_file->idx_cond_push(keyno, pushed_cond); } else { DBUG_ASSERT(secondary_file && secondary_file->inited==handler::INDEX); /* We get here when the access alternates betwen MRR scan(s) and non-MRR scans. Calling primary_file->index_end() will invoke dsmrr_close() for this object, which will delete secondary_file. We need to keep it, so put it away and dont let it be deleted: */ if (primary_file->inited == handler::INDEX) { handler *save_h2= secondary_file; Mrr_reader *save_strategy= strategy; secondary_file= NULL; strategy= NULL; res= primary_file->ha_index_end(); secondary_file= save_h2; strategy= save_strategy; if (res) goto error; } if ((primary_file->inited != handler::RND) && (res= primary_file->ha_rnd_init(FALSE))) goto error; } DBUG_RETURN(0); error: DBUG_RETURN(res); } void DsMrr_impl::close_second_handler() { if (secondary_file) { secondary_file->extra(HA_EXTRA_NO_KEYREAD); secondary_file->ha_index_or_rnd_end(); secondary_file->ha_external_lock(current_thd, F_UNLCK); secondary_file->ha_close(); delete secondary_file; secondary_file= NULL; } } void DsMrr_impl::dsmrr_close() { DBUG_ENTER("DsMrr_impl::dsmrr_close"); close_second_handler(); strategy= NULL; DBUG_VOID_RETURN; } /* my_qsort2-compatible static member function to compare key tuples */ int Mrr_ordered_index_reader::compare_keys(void* arg, uchar* key1_arg, uchar* key2_arg) { Mrr_ordered_index_reader *reader= (Mrr_ordered_index_reader*)arg; TABLE *table= reader->file->get_table(); KEY_PART_INFO *part= table->key_info[reader->file->active_index].key_part; uchar *key1, *key2; if (reader->keypar.use_key_pointers) { /* the buffer stores pointers to keys, get to the keys */ memcpy(&key1, key1_arg, sizeof(char*)); memcpy(&key2, key2_arg, sizeof(char*)); } else { key1= key1_arg; key2= key2_arg; } return key_tuple_cmp(part, key1, key2, reader->keypar.key_tuple_length); } int Mrr_ordered_index_reader::compare_keys_reverse(void* arg, uchar* key1, uchar* key2) { return -compare_keys(arg, key1, key2); } /** Set the buffer space to be shared between rowid and key buffer @return FALSE ok @return TRUE There is so little buffer space that we won't be able to use the strategy. This happens when we don't have enough space for one rowid element and one key element so this is mainly targeted at testing. */ bool DsMrr_impl::setup_buffer_sharing(uint key_size_in_keybuf, key_part_map key_tuple_map) { long key_buff_elem_size= key_size_in_keybuf + (int)is_mrr_assoc * sizeof(range_id_t); KEY *key_info= &primary_file->get_table()->key_info[keyno]; /* Ok if we got here we need to allocate one part of the buffer for keys and another part for rowids. */ ulonglong rowid_buf_elem_size= primary_file->ref_length + (int)is_mrr_assoc * sizeof(range_id_t); /* Use rec_per_key statistics as a basis to find out how many rowids we'll get for each key value. TODO: what should be the default value to use when there is no statistics? */ uint parts= my_count_bits(key_tuple_map); ha_rows rpc; ulonglong rowids_size= rowid_buf_elem_size; if ((rpc= (ha_rows) key_info->actual_rec_per_key(parts - 1))) rowids_size= rowid_buf_elem_size * rpc; double fraction_for_rowids= (ulonglong2double(rowids_size) / (ulonglong2double(rowids_size) + key_buff_elem_size)); ptrdiff_t bytes_for_rowids= (ptrdiff_t)floor(0.5 + fraction_for_rowids * (full_buf_end - full_buf)); ptrdiff_t bytes_for_keys= (full_buf_end - full_buf) - bytes_for_rowids; if (bytes_for_keys < key_buff_elem_size + 1 || bytes_for_rowids < (ptrdiff_t)rowid_buf_elem_size + 1) return TRUE; /* Failed to provide minimum space for one of the buffers */ rowid_buffer_end= full_buf + bytes_for_rowids; rowid_buffer.set_buffer_space(full_buf, rowid_buffer_end); key_buffer= &backward_key_buf; key_buffer->set_buffer_space(rowid_buffer_end, full_buf_end); /* The above code guarantees that the buffers are big enough */ DBUG_ASSERT(key_buffer->have_space_for(key_buff_elem_size) && rowid_buffer.have_space_for((size_t)rowid_buf_elem_size)); return FALSE; } void DsMrr_impl::do_nothing(void *dsmrr_arg) { /* Do nothing */ } void DsMrr_impl::reset_buffer_sizes(void *dsmrr_arg) { DsMrr_impl *dsmrr= (DsMrr_impl*)dsmrr_arg; dsmrr->rowid_buffer.set_buffer_space(dsmrr->full_buf, dsmrr->rowid_buffer_end); dsmrr->key_buffer->set_buffer_space(dsmrr->rowid_buffer_end, dsmrr->full_buf_end); } /* Take unused space from the key buffer and give it to the rowid buffer */ void DsMrr_impl::redistribute_buffer_space(void *dsmrr_arg) { DsMrr_impl *dsmrr= (DsMrr_impl*)dsmrr_arg; uchar *unused_start, *unused_end; dsmrr->key_buffer->remove_unused_space(&unused_start, &unused_end); dsmrr->rowid_buffer.grow(unused_start, unused_end); } /* @brief Initialize the iterator @note Initialize the iterator to produce matches for the key of the first element in owner_arg->key_buffer @retval 0 OK @retval HA_ERR_END_OF_FILE Either the owner->key_buffer is empty or no matches for the key we've tried (check key_buffer->is_empty() to tell these apart) @retval other code Fatal error */ int Key_value_records_iterator::init(Mrr_ordered_index_reader *owner_arg) { int res; owner= owner_arg; identical_key_it.init(owner->key_buffer); owner->key_buffer->setup_reading(owner->keypar.key_size_in_keybuf, owner->is_mrr_assoc ? sizeof(void*) : 0); if (identical_key_it.read()) return HA_ERR_END_OF_FILE; uchar *key_in_buf= last_identical_key_ptr= identical_key_it.read_ptr1; uchar *index_tuple= key_in_buf; if (owner->keypar.use_key_pointers) memcpy(&index_tuple, key_in_buf, sizeof(char*)); /* Check out how many more identical keys are following */ while (!identical_key_it.read()) { if (Mrr_ordered_index_reader::compare_keys(owner, key_in_buf, identical_key_it.read_ptr1)) break; last_identical_key_ptr= identical_key_it.read_ptr1; } identical_key_it.init(owner->key_buffer); res= owner->file->ha_index_read_map(owner->file->get_table()->record[0], index_tuple, owner->keypar.key_tuple_map, HA_READ_KEY_EXACT); if (res) { /* Failed to find any matching records */ move_to_next_key_value(); return res; } owner->have_saved_rowid= FALSE; get_next_row= FALSE; return 0; } int Key_value_records_iterator::get_next(range_id_t *range_info) { int res; if (get_next_row) { if (owner->keypar.index_ranges_unique) { /* We're using a full unique key, no point to call index_next_same */ return HA_ERR_END_OF_FILE; } handler *h= owner->file; uchar *lookup_key; if (owner->keypar.use_key_pointers) memcpy(&lookup_key, identical_key_it.read_ptr1, sizeof(void*)); else lookup_key= identical_key_it.read_ptr1; if ((res= h->ha_index_next_same(h->get_table()->record[0], lookup_key, owner->keypar.key_tuple_length))) { /* It's either HA_ERR_END_OF_FILE or some other error */ return res; } identical_key_it.init(owner->key_buffer); owner->have_saved_rowid= FALSE; get_next_row= FALSE; } identical_key_it.read(); /* This gets us next range_id */ memcpy(range_info, identical_key_it.read_ptr2, sizeof(range_id_t)); if (!last_identical_key_ptr || (identical_key_it.read_ptr1 == last_identical_key_ptr)) { /* We've reached the last of the identical keys that current record is a match for. Set get_next_row=TRUE so that we read the next index record on the next call to this function. */ get_next_row= TRUE; } return 0; } void Key_value_records_iterator::move_to_next_key_value() { while (!owner->key_buffer->read() && (owner->key_buffer->read_ptr1 != last_identical_key_ptr)) {} } /** DS-MRR implementation: multi_range_read_next() function. Calling convention is like multi_range_read_next() has. */ int DsMrr_impl::dsmrr_next(range_id_t *range_info) { int res; if (strategy_exhausted) return HA_ERR_END_OF_FILE; while ((res= strategy->get_next(range_info)) == HA_ERR_END_OF_FILE) { if ((res= strategy->refill_buffer(FALSE))) break; /* EOF or error */ } return res; } /** DS-MRR implementation: multi_range_read_info() function */ ha_rows DsMrr_impl::dsmrr_info(uint keyno, uint n_ranges, uint rows, uint key_parts, uint *bufsz, uint *flags, Cost_estimate *cost) { ha_rows res __attribute__((unused)); uint def_flags= *flags; uint def_bufsz= *bufsz; /* Get cost/flags/mem_usage of default MRR implementation */ res= primary_file->handler::multi_range_read_info(keyno, n_ranges, rows, key_parts, &def_bufsz, &def_flags, cost); DBUG_ASSERT(!res); if ((*flags & HA_MRR_USE_DEFAULT_IMPL) || choose_mrr_impl(keyno, rows, flags, bufsz, cost)) { /* Default implementation is choosen */ DBUG_PRINT("info", ("Default MRR implementation choosen")); *flags= def_flags; *bufsz= def_bufsz; } else { /* *flags and *bufsz were set by choose_mrr_impl */ DBUG_PRINT("info", ("DS-MRR implementation choosen")); } return 0; } /** DS-MRR Implementation: multi_range_read_info_const() function */ ha_rows DsMrr_impl::dsmrr_info_const(uint keyno, RANGE_SEQ_IF *seq, void *seq_init_param, uint n_ranges, uint *bufsz, uint *flags, Cost_estimate *cost) { ha_rows rows; uint def_flags= *flags; uint def_bufsz= *bufsz; /* Get cost/flags/mem_usage of default MRR implementation */ rows= primary_file->handler::multi_range_read_info_const(keyno, seq, seq_init_param, n_ranges, &def_bufsz, &def_flags, cost); if (rows == HA_POS_ERROR) { /* Default implementation can't perform MRR scan => we can't either */ return rows; } /* If HA_MRR_USE_DEFAULT_IMPL has been passed to us, that is an order to use the default MRR implementation (we need it for UPDATE/DELETE). Otherwise, make a choice based on cost and @@optimizer_switch settings */ if ((*flags & HA_MRR_USE_DEFAULT_IMPL) || choose_mrr_impl(keyno, rows, flags, bufsz, cost)) { DBUG_PRINT("info", ("Default MRR implementation choosen")); *flags= def_flags; *bufsz= def_bufsz; } else { /* *flags and *bufsz were set by choose_mrr_impl */ DBUG_PRINT("info", ("DS-MRR implementation choosen")); } return rows; } /** Check if key has partially-covered columns We can't use DS-MRR to perform range scans when the ranges are over partially-covered keys, because we'll not have full key part values (we'll have their prefixes from the index) and will not be able to check if we've reached the end the range. @param keyno Key to check @todo Allow use of DS-MRR in cases where the index has partially-covered components but they are not used for scanning. @retval TRUE Yes @retval FALSE No */ bool key_uses_partial_cols(TABLE_SHARE *share, uint keyno) { KEY_PART_INFO *kp= share->key_info[keyno].key_part; KEY_PART_INFO *kp_end= kp + share->key_info[keyno].user_defined_key_parts; for (; kp != kp_end; kp++) { if (!kp->field->part_of_key.is_set(keyno)) return TRUE; } return FALSE; } /* Check if key/flags allow DS-MRR/CPK strategy to be used @param thd @param keyno Index that will be used @param mrr_flags @retval TRUE DS-MRR/CPK should be used @retval FALSE Otherwise */ bool DsMrr_impl::check_cpk_scan(THD *thd, TABLE_SHARE *share, uint keyno, uint mrr_flags) { return MY_TEST((mrr_flags & HA_MRR_SINGLE_POINT) && keyno == share->primary_key && primary_file->primary_key_is_clustered() && optimizer_flag(thd, OPTIMIZER_SWITCH_MRR_SORT_KEYS)); } /* DS-MRR Internals: Choose between Default MRR implementation and DS-MRR Make the choice between using Default MRR implementation and DS-MRR. This function contains common functionality factored out of dsmrr_info() and dsmrr_info_const(). The function assumes that the default MRR implementation's applicability requirements are satisfied. @param keyno Index number @param rows E(full rows to be retrieved) @param flags IN MRR flags provided by the MRR user OUT If DS-MRR is choosen, flags of DS-MRR implementation else the value is not modified @param bufsz IN If DS-MRR is choosen, buffer use of DS-MRR implementation else the value is not modified @param cost IN Cost of default MRR implementation OUT If DS-MRR is choosen, cost of DS-MRR scan else the value is not modified @retval TRUE Default MRR implementation should be used @retval FALSE DS-MRR implementation should be used */ bool DsMrr_impl::choose_mrr_impl(uint keyno, ha_rows rows, uint *flags, uint *bufsz, Cost_estimate *cost) { Cost_estimate dsmrr_cost; bool res; THD *thd= primary_file->get_table()->in_use; TABLE_SHARE *share= primary_file->get_table_share(); bool doing_cpk_scan= check_cpk_scan(thd, share, keyno, *flags); bool using_cpk= MY_TEST(keyno == share->primary_key && primary_file->primary_key_is_clustered()); *flags &= ~HA_MRR_IMPLEMENTATION_FLAGS; if (!optimizer_flag(thd, OPTIMIZER_SWITCH_MRR) || *flags & HA_MRR_INDEX_ONLY || (using_cpk && !doing_cpk_scan) || key_uses_partial_cols(share, keyno)) { /* Use the default implementation */ *flags |= HA_MRR_USE_DEFAULT_IMPL; *flags &= ~HA_MRR_IMPLEMENTATION_FLAGS; return TRUE; } uint add_len= share->key_info[keyno].key_length + primary_file->ref_length; *bufsz -= add_len; if (get_disk_sweep_mrr_cost(keyno, rows, *flags, bufsz, &dsmrr_cost)) return TRUE; *bufsz += add_len; bool force_dsmrr; /* If mrr_cost_based flag is not set, then set cost of DS-MRR to be minimum of DS-MRR and Default implementations cost. This allows one to force use of DS-MRR whenever it is applicable without affecting other cost-based choices. */ if ((force_dsmrr= !optimizer_flag(thd, OPTIMIZER_SWITCH_MRR_COST_BASED)) && dsmrr_cost.total_cost() > cost->total_cost()) dsmrr_cost= *cost; if (force_dsmrr || dsmrr_cost.total_cost() <= cost->total_cost()) { *flags &= ~HA_MRR_USE_DEFAULT_IMPL; /* Use the DS-MRR implementation */ *flags &= ~HA_MRR_SORTED; /* We will return unordered output */ *cost= dsmrr_cost; res= FALSE; if ((using_cpk && doing_cpk_scan) || (optimizer_flag(thd, OPTIMIZER_SWITCH_MRR_SORT_KEYS) && *flags & HA_MRR_SINGLE_POINT)) { *flags |= DSMRR_IMPL_SORT_KEYS; } if (!(using_cpk && doing_cpk_scan) && !(*flags & HA_MRR_INDEX_ONLY)) { *flags |= DSMRR_IMPL_SORT_ROWIDS; } /* if ((*flags & HA_MRR_SINGLE_POINT) && optimizer_flag(thd, OPTIMIZER_SWITCH_MRR_SORT_KEYS)) *flags |= HA_MRR_MATERIALIZED_KEYS; */ } else { /* Use the default MRR implementation */ res= TRUE; } return res; } /* Take the flags we've returned previously and print one of - Key-ordered scan - Rowid-ordered scan - Key-ordered Rowid-ordered scan */ int DsMrr_impl::dsmrr_explain_info(uint mrr_mode, char *str, size_t size) { const char *key_ordered= "Key-ordered scan"; const char *rowid_ordered= "Rowid-ordered scan"; const char *both_ordered= "Key-ordered Rowid-ordered scan"; const char *used_str=""; const uint BOTH_FLAGS= (DSMRR_IMPL_SORT_KEYS | DSMRR_IMPL_SORT_ROWIDS); if (!(mrr_mode & HA_MRR_USE_DEFAULT_IMPL)) { if ((mrr_mode & BOTH_FLAGS) == BOTH_FLAGS) used_str= both_ordered; else if (mrr_mode & DSMRR_IMPL_SORT_KEYS) used_str= key_ordered; else if (mrr_mode & DSMRR_IMPL_SORT_ROWIDS) used_str= rowid_ordered; size_t used_str_len= strlen(used_str); size_t copy_len= MY_MIN(used_str_len, size); memcpy(str, used_str, copy_len); return (int)copy_len; } return 0; } static void get_sort_and_sweep_cost(TABLE *table, ha_rows nrows, Cost_estimate *cost); /** Get cost of DS-MRR scan @param keynr Index to be used @param rows E(Number of rows to be scanned) @param flags Scan parameters (HA_MRR_* flags) @param buffer_size INOUT Buffer size @param cost OUT The cost @retval FALSE OK @retval TRUE Error, DS-MRR cannot be used (the buffer is too small for even 1 rowid) */ bool DsMrr_impl::get_disk_sweep_mrr_cost(uint keynr, ha_rows rows, uint flags, uint *buffer_size, Cost_estimate *cost) { ulong max_buff_entries, elem_size; ha_rows rows_in_full_step; ha_rows rows_in_last_step; uint n_full_steps; double index_read_cost; elem_size= primary_file->ref_length + sizeof(void*) * (!MY_TEST(flags & HA_MRR_NO_ASSOCIATION)); max_buff_entries = *buffer_size / elem_size; if (!max_buff_entries) return TRUE; /* Buffer has not enough space for even 1 rowid */ /* Number of iterations we'll make with full buffer */ n_full_steps= (uint)floor(rows2double(rows) / max_buff_entries); /* Get numbers of rows we'll be processing in - non-last sweep, with full buffer - last iteration, with non-full buffer */ rows_in_full_step= max_buff_entries; rows_in_last_step= rows % max_buff_entries; /* Adjust buffer size if we expect to use only part of the buffer */ if (n_full_steps) { get_sort_and_sweep_cost(table, rows_in_full_step, cost); cost->multiply(n_full_steps); } else { cost->reset(); *buffer_size= (uint)MY_MAX(*buffer_size, (size_t)(1.2*rows_in_last_step) * elem_size + primary_file->ref_length + table->key_info[keynr].key_length); } Cost_estimate last_step_cost; get_sort_and_sweep_cost(table, rows_in_last_step, &last_step_cost); cost->add(&last_step_cost); if (n_full_steps != 0) cost->mem_cost= *buffer_size; else cost->mem_cost= (double)rows_in_last_step * elem_size; /* Total cost of all index accesses */ index_read_cost= primary_file->keyread_time(keynr, 1, rows); cost->add_io(index_read_cost, 1 /* Random seeks */); return FALSE; } /* Get cost of one sort-and-sweep step It consists of two parts: - sort an array of #nrows ROWIDs using qsort - read #nrows records from table in a sweep. @param table Table being accessed @param nrows Number of rows to be sorted and retrieved @param cost OUT The cost of scan */ static void get_sort_and_sweep_cost(TABLE *table, ha_rows nrows, Cost_estimate *cost) { if (nrows) { get_sweep_read_cost(table, nrows, FALSE, cost); /* Add cost of qsort call: n * log2(n) * cost(rowid_comparison) */ double cmp_op= rows2double(nrows) * (1.0 / TIME_FOR_COMPARE_ROWID); if (cmp_op < 3) cmp_op= 3; cost->cpu_cost += cmp_op * log2(cmp_op); } else cost->reset(); } /** Get cost of reading nrows table records in a "disk sweep" A disk sweep read is a sequence of handler->rnd_pos(rowid) calls that made for an ordered sequence of rowids. We assume hard disk IO. The read is performed as follows: 1. The disk head is moved to the needed cylinder 2. The controller waits for the plate to rotate 3. The data is transferred Time to do #3 is insignificant compared to #2+#1. Time to move the disk head is proportional to head travel distance. Time to wait for the plate to rotate depends on whether the disk head was moved or not. If disk head wasn't moved, the wait time is proportional to distance between the previous block and the block we're reading. If the head was moved, we don't know how much we'll need to wait for the plate to rotate. We assume the wait time to be a variate with a mean of 0.5 of full rotation time. Our cost units are "random disk seeks". The cost of random disk seek is actually not a constant, it depends one range of cylinders we're going to access. We make it constant by introducing a fuzzy concept of "typical datafile length" (it's fuzzy as it's hard to tell whether it should include index file, temp.tables etc). Then random seek cost is: 1 = half_rotation_cost + move_cost * 1/3 * typical_data_file_length We define half_rotation_cost as DISK_SEEK_BASE_COST=0.9. @param table Table to be accessed @param nrows Number of rows to retrieve @param interrupted TRUE <=> Assume that the disk sweep will be interrupted by other disk IO. FALSE - otherwise. @param cost OUT The cost. */ void get_sweep_read_cost(TABLE *table, ha_rows nrows, bool interrupted, Cost_estimate *cost) { DBUG_ENTER("get_sweep_read_cost"); cost->reset(); if (table->file->primary_key_is_clustered()) { cost->io_count= table->file->read_time(table->s->primary_key, (uint) nrows, nrows); } else { double n_blocks= ceil(ulonglong2double(table->file->stats.data_file_length) / IO_SIZE); double busy_blocks= n_blocks * (1.0 - pow(1.0 - 1.0/n_blocks, rows2double(nrows))); if (busy_blocks < 1.0) busy_blocks= 1.0; DBUG_PRINT("info",("sweep: nblocks=%g, busy_blocks=%g", n_blocks, busy_blocks)); cost->io_count= busy_blocks; if (!interrupted) { /* Assume reading is done in one 'sweep' */ cost->avg_io_cost= (DISK_SEEK_BASE_COST + DISK_SEEK_PROP_COST*n_blocks/busy_blocks); } } DBUG_PRINT("info",("returning cost=%g", cost->total_cost())); DBUG_VOID_RETURN; } /* ************************************************************************** * DS-MRR implementation ends ***************************************************************************/
31.498107
86
0.648644
[ "object" ]
cf60ef629b6a1654e9b882d23de18571116ba661
879
cc
C++
chrome/browser/ui/app_list/test/app_list_service_test_api_ash.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:51:34.000Z
2018-02-15T03:11:54.000Z
chrome/browser/ui/app_list/test/app_list_service_test_api_ash.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-13T19:44:12.000Z
2021-12-13T19:44:12.000Z
chrome/browser/ui/app_list/test/app_list_service_test_api_ash.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:52:03.000Z
2022-02-13T17:58:45.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/app_list/test/app_list_service_test_api_ash.h" #include "ash/shell.h" #include "ash/test/app_list_controller_test_api.h" #include "ui/app_list/views/app_list_view.h" namespace test { app_list::AppListModel* AppListServiceTestApiAsh::GetAppListModel() { return ash::test::AppListControllerTestApi(ash::Shell::GetInstance()) .view()->model(); } #if !defined(OS_WIN) // static scoped_ptr<AppListServiceTestApi> AppListServiceTestApi::Create( chrome::HostDesktopType desktop) { DCHECK_EQ(chrome::HOST_DESKTOP_TYPE_ASH, desktop); return scoped_ptr<AppListServiceTestApi>( new AppListServiceTestApiAsh()).Pass(); } #endif // !defined(OS_WIN) } // namespace test
30.310345
74
0.76223
[ "model" ]
cf61d14b3df537d4d484935c45d0c9d2c48326a4
48,249
cpp
C++
youbot_simulation/youbot_gazebo_control/src/steered_wheel_base_controller.cpp
Vvlad1slavV/robocup_pkg
f1bb3e7e63391d4207172d7cc0e35ecd0c65c360
[ "Apache-2.0" ]
null
null
null
youbot_simulation/youbot_gazebo_control/src/steered_wheel_base_controller.cpp
Vvlad1slavV/robocup_pkg
f1bb3e7e63391d4207172d7cc0e35ecd0c65c360
[ "Apache-2.0" ]
null
null
null
youbot_simulation/youbot_gazebo_control/src/steered_wheel_base_controller.cpp
Vvlad1slavV/robocup_pkg
f1bb3e7e63391d4207172d7cc0e35ecd0c65c360
[ "Apache-2.0" ]
1
2020-11-16T11:37:01.000Z
2020-11-16T11:37:01.000Z
/// \file steered_wheel_base_controller.cpp /// /// \brief Steered-wheel base controller /// /// Copyright (c) 2013-2014 Wunderkammer Laboratory /// /// This file contains the source code for SteeredWheelBaseController, /// a base controller for mobile robots. It works with bases that have two or /// more independently-steerable driven wheels and zero or more omnidirectional /// passive wheels (e.g. swivel casters). /// /// Subscribed Topics: /// cmd_vel (geometry_msgs/Twist) /// Velocity command, defined in the frame specified by the base_link /// parameter. The linear.x and linear.y fields specify the base's /// desired linear velocity, measured in meters per second. /// The angular.z field specifies the base's desired angular velocity, /// measured in radians per second. /// /// Published Topics: /// odom (nav_msgs/Odometry) /// Odometry. /// /// Parameters: /// ~robot_description_name (string, default: robot_description) /// Name of a parameter on the Parameter Server. The named parameter's /// value is URDF data that describes the robot. /// ~base_link (string, default: base_link) /// Link that specifies the frame in which cmd_vel is defined. /// The link specified by base_link must exist in the robot's URDF /// data. /// ~cmd_vel_timeout (float, default: 0.5) /// If cmd_vel_timeout is greater than zero and this controller does /// not receive a velocity command for more than cmd_vel_timeout /// seconds, wheel motion is paused until a command is received. /// If cmd_vel_timeout is less than or equal to zero, the command /// timeout is disabled. /// /// ~linear_speed_limit (float, default: 1.0) /// Linear speed limit. If linear_speed_limit is less than zero, the /// linear speed limit is disabled. Unit: m/s. /// ~linear_acceleration_limit (float, default: 1.0) /// Linear acceleration limit. If linear_acceleration_limit is less /// than zero, the linear acceleration limit is disabled. Unit: m/s**2. /// ~linear_deceleration_limit (float, default: -1.0) /// Linear deceleration limit. If linear_deceleration_limit is less /// than or equal to zero, the linear deceleration limit is disabled. /// Unit: m/s**2. /// /// ~yaw_speed_limit (float, default: 1.0) /// Yaw speed limit. If yaw_speed_limit is less than zero, the yaw /// speed limit is disabled. Unit: rad/s. /// ~yaw_acceleration_limit (float, default: 1.0) /// Yaw acceleration limit. If yaw_acceleration_limit is less than /// zero, the yaw acceleration limit is disabled. Unit: rad/s**2. /// ~yaw_deceleration_limit (float, default: -1.0) /// Yaw deceleration limit. If yaw_deceleration_limit is less than or /// equal to zero, the yaw deceleration limit is disabled. /// Unit: rad/s**2. /// /// ~full_axle_speed_angle (float, default: 0.7854) /// If the difference between a wheel's desired and measured steering /// angles is less than or equal to full_axle_speed_angle, the wheel's /// axle will rotate at the speed determined by the current velocity /// command, subject to the speed, acceleration, and deceleration /// limits. full_axle_speed_angle must be less than /// zero_axle_speed_angle. Range: [0, pi]. Unit: radian. /// ~zero_axle_speed_angle (float, default: 1.5708) /// If the difference between a wheel's desired and measured steering /// angles is greater than or equal to zero_axle_speed_angle, the /// wheel's axle will stop rotating, subject to the deceleration /// limits. zero_axle_speed_angle must be greater than /// full_axle_speed_angle. Range: [0, pi]. Unit: radian. /// /// ~wheels (sequence of mappings, default: empty) /// Two or more steered wheels. /// /// Key-Value Pairs: /// /// steering_joint (string) /// Steering joint. /// axle_joint (string) /// Axle joint. /// diameter (float) /// Wheel diameter. It must be greater than zero. Unit: meter. /// ~wheel_diameter_scale (float, default: 1.0) /// Scale applied to each wheel's diameter. It is used to correct for /// tire deformation. wheel_diameter_scale must be greater than zero. /// ~pid_gains/<joint name> (mapping, default: empty) /// PID controller gains for the specified joint. Needed only for /// effort-controlled joints and velocity-controlled steering joints. /// /// ~odometry_publishing_frequency (float, default: 30.0) /// Odometry publishing frequency. If it is less than or equal to zero, /// odometry computation is disabled. Unit: hertz. /// ~odometry_frame (string, default: odom) /// Odometry frame. /// ~base_frame (string, default: base_link) /// Base frame in the <odometry_frame>-to-<base_frame> transform /// provided by this controller. base_frame allows the controller to /// publish transforms from odometry_frame to a frame that is not a /// link in the robot's URDF data. For example, base_frame can be set /// to "base_footprint". /// ~initial_x (float, default: 0.0) /// X coordinate of the base frame's initial position in the odometry /// frame. Unit: meter. /// ~initial_y (float, default: 0.0) /// Y coordinate of the base frame's initial position in the odometry /// frame. Unit: meter. /// ~initial_yaw (float, default: 0.0) /// Initial orientation of the base frame in the odometry frame. /// Range: [-pi, pi]. Unit: radian. /// /// Provided tf Transforms: /// <odometry_frame> to <base_frame> /// Specifies the base frame's pose in the odometry frame. // // // 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. // // Modified by: Frederik Hegger (20.08.2015) #include <algorithm> #include <exception> #include <set> #include <stdexcept> #include <string> #include <vector> #include <angles/angles.h> #include <boost/foreach.hpp> #include <boost/math/special_functions/sign.hpp> #include <boost/shared_ptr.hpp> #include <control_toolbox/pid.h> #include <controller_interface/controller_base.h> #include <Eigen/Core> #include <Eigen/Geometry> #include <Eigen/SVD> #include <controller_interface/multi_interface_controller.h> #include <controller_interface/controller.h> #include <geometry_msgs/Twist.h> #include <hardware_interface/joint_command_interface.h> #include <kdl/chainfksolverpos_recursive.hpp> #include <kdl_parser/kdl_parser.hpp> #include <nav_msgs/Odometry.h> #include <pluginlib/class_list_macros.hpp> #include <realtime_tools/realtime_publisher.h> #include <tf/tfMessage.h> #include <tf/transform_datatypes.h> #include <urdf/model.h> using std::runtime_error; using std::set; using std::string; using boost::math::sign; using boost::shared_ptr; using controller_interface::ControllerBase; using Eigen::Affine2d; using Eigen::Matrix2d; using Eigen::Vector2d; using geometry_msgs::TwistConstPtr; using hardware_interface::JointHandle; using hardware_interface::RobotHW; using hardware_interface::EffortJointInterface; using hardware_interface::PositionJointInterface; using hardware_interface::VelocityJointInterface; using realtime_tools::RealtimeBuffer; using realtime_tools::RealtimePublisher; using ros::Duration; using ros::NodeHandle; using ros::Time; using XmlRpc::XmlRpcValue; namespace { void addClaimedResources(hardware_interface::HardwareInterface *const hw_iface, std::string hw_iface_name, controller_interface::ControllerBase::ClaimedResources& claimed_resources){ if (hw_iface == NULL) return; hardware_interface::InterfaceResources iface_res(hw_iface_name, hw_iface->getClaims()); if (!iface_res.resources.empty()) claimed_resources.push_back(iface_res); hw_iface->clearClaims(); } double clamp(const double val, const double min_val, const double max_val) { return std::min(std::max(val, min_val), max_val); } double hermite(const double t) { if (t <= 0) return 0; if (t >= 1) return 1; return (-2 * t + 3) * t * t; // -2t**3 + 3t**2 } class Joint { public: virtual ~Joint() {} virtual void init() = 0; virtual void stop() = 0; bool isValidPos(const double pos); double getPos() const { return handle_.getPosition(); } virtual void setPos(const double pos, const Duration& period) {} virtual void setVel(const double vel, const Duration& period) = 0; protected: Joint(const JointHandle& handle, const urdf::JointConstSharedPtr urdf_joint); JointHandle handle_; const double lower_limit_, upper_limit_; // Unit: radian bool check_joint_limit_; }; // Position-controlled joint class PosJoint : public Joint { public: PosJoint(const JointHandle& handle, const urdf::JointConstSharedPtr urdf_joint) : Joint(handle, urdf_joint) {} virtual void init(); virtual void stop(); virtual void setPos(const double pos, const Duration& period); virtual void setVel(const double vel, const Duration& period); private: double pos_; }; // Velocity-controlled joint. VelJoint is used for axles only. class VelJoint : public Joint { public: VelJoint(const JointHandle& handle, const urdf::JointConstSharedPtr urdf_joint) : Joint(handle, urdf_joint) {} virtual void init() { stop(); } virtual void stop(); virtual void setVel(const double vel, const Duration& period); }; // An object of class PIDJoint is a joint controlled by a PID controller. class PIDJoint : public Joint { public: PIDJoint(const JointHandle& handle, const urdf::JointConstSharedPtr urdf_joint, const NodeHandle& ctrlr_nh); virtual void init(); virtual void stop(); virtual void setPos(const double pos, const Duration& period); virtual void setVel(const double vel, const Duration& period); private: const int type_; // URDF joint type control_toolbox::Pid pid_ctrlr_; }; // An object of class Wheel is a steered wheel. class Wheel { public: Wheel(const KDL::Tree& tree, const string& base_link, const string& steer_link, const shared_ptr<Joint> steer_joint, const shared_ptr<Joint> axle_joint, const double circ); const Vector2d& pos() const { return pos_; } Vector2d getDeltaPos(); void initJoints(); void stop() const; double ctrlSteering(const Duration& period, const double hermite_scale, const double hermite_offset); double ctrlSteering(const double theta_desired, const Duration& period, const double hermite_scale, const double hermite_offset); void ctrlAxle(const double lin_speed, const Duration& period) const; private: void initPos(const KDL::Tree& tree, const string& base_link); string steer_link_; // Steering link Vector2d pos_; // Wheel's position in the base link's frame shared_ptr<Joint> steer_joint_; // Steering joint shared_ptr<Joint> axle_joint_; double theta_steer_; // Steering joint position double last_theta_steer_desired_; // Last desired steering joint position double last_theta_axle_; // Last axle joint position double radius_; // Unit: meter. double inv_radius_; // Inverse of radius_ double axle_vel_gain_; // Axle velocity gain }; Joint::Joint(const JointHandle& handle, const urdf::JointConstSharedPtr urdf_joint) : handle_(handle), lower_limit_(urdf_joint->limits->lower), upper_limit_(urdf_joint->limits->upper), check_joint_limit_(true) { // Do nothing. } bool Joint::isValidPos(const double pos) { if (!check_joint_limit_) return true; return pos >= lower_limit_ && pos <= upper_limit_; } // Initialize this joint. void PosJoint::init() { pos_ = getPos(); stop(); } // Stop this joint's motion. void PosJoint::stop() { handle_.setCommand(getPos()); } // Specify this joint's position. void PosJoint::setPos(const double pos, const Duration& /* period */) { pos_ = pos; handle_.setCommand(pos_); } // Specify this joint's velocity. void PosJoint::setVel(const double vel, const Duration& period) { pos_ += vel * period.toSec(); handle_.setCommand(pos_); } // Stop this joint's motion. void VelJoint::stop() { handle_.setCommand(0); } // Specify this joint's velocity. void VelJoint::setVel(const double vel, const Duration& /* period */) { handle_.setCommand(vel); } PIDJoint::PIDJoint(const JointHandle& handle, const urdf::JointConstSharedPtr urdf_joint, const NodeHandle& ctrlr_nh) : Joint(handle, urdf_joint), type_(urdf_joint->type) { const NodeHandle nh(ctrlr_nh, "pid_gains/" + handle.getName()); if (!pid_ctrlr_.init(nh)) { throw runtime_error("No PID gain values for \"" + handle.getName() + "\" were found."); } } // Initialize this joint. void PIDJoint::init() { pid_ctrlr_.reset(); stop(); } // Stop this joint's motion. void PIDJoint::stop() { // The command passed to setCommand() might be an effort value or a // velocity. In either case, the correct command to pass here is zero. handle_.setCommand(0); } // Specify this joint's position. void PIDJoint::setPos(const double pos, const Duration& period) { const double curr_pos = getPos(); double error; switch (type_) { case urdf::Joint::REVOLUTE: angles::shortest_angular_distance_with_limits(curr_pos, pos, lower_limit_, upper_limit_, error); check_joint_limit_ = true; break; case urdf::Joint::CONTINUOUS: error = angles::shortest_angular_distance(curr_pos, pos); check_joint_limit_ = false; break; default: error = pos - curr_pos; break; } handle_.setCommand(pid_ctrlr_.computeCommand(error, period)); } // Specify this joint's velocity. void PIDJoint::setVel(const double vel, const Duration& period) { const double error = vel - handle_.getVelocity(); handle_.setCommand(pid_ctrlr_.computeCommand(error, period)); } Wheel::Wheel(const KDL::Tree& tree, const string& base_link, const string& steer_link, const shared_ptr<Joint> steer_joint, const shared_ptr<Joint> axle_joint, const double circ) { steer_link_ = steer_link; initPos(tree, base_link); steer_joint_ = steer_joint; axle_joint_ = axle_joint; theta_steer_ = steer_joint_->getPos(); last_theta_steer_desired_ = theta_steer_; last_theta_axle_ = axle_joint_->getPos(); radius_ = circ / (2 * M_PI); inv_radius_ = 1 / radius_; axle_vel_gain_ = 0; } // Return the difference between this wheel's current position and its // position when getDeltaPos() was last called. The returned vector is defined // in the base link's frame. Vector2d Wheel::getDeltaPos() { const double theta_axle = axle_joint_->getPos(); const double delta_theta_axle = theta_axle - last_theta_axle_; last_theta_axle_ = theta_axle; const double vec_mag = delta_theta_axle * radius_; return Vector2d(cos(theta_steer_), sin(theta_steer_)) * vec_mag; } // Initialize this wheel's steering and axle joints. void Wheel::initJoints() { steer_joint_->init(); axle_joint_->init(); } // Stop this wheel's motion. void Wheel::stop() const { steer_joint_->stop(); axle_joint_->stop(); } // Maintain the position of this wheel's steering joint. Return a linear speed // gain value based on the difference between the desired steering angle and // the actual steering angle. double Wheel::ctrlSteering(const Duration& period, const double hermite_scale, const double hermite_offset) { return ctrlSteering(last_theta_steer_desired_, period, hermite_scale, hermite_offset); } // Control this wheel's steering joint. theta_desired range: [-pi, pi]. // Return a linear speed gain value based on the difference between the // desired steering angle and the actual steering angle. double Wheel::ctrlSteering(const double theta_desired, const Duration& period, const double hermite_scale, const double hermite_offset) { last_theta_steer_desired_ = theta_desired; // Find the minimum rotation that will align the wheel with theta_desired. theta_steer_ = steer_joint_->getPos(); const double theta_diff = fabs(theta_desired - theta_steer_); double theta; if (theta_diff > M_PI_2) { theta = theta_desired - copysign(M_PI, theta_desired); axle_vel_gain_ = -1; } else { theta = theta_desired; axle_vel_gain_ = 1; } // Keep theta within its valid range. if (!steer_joint_->isValidPos(theta)) { theta -= copysign(M_PI, theta); axle_vel_gain_ = -axle_vel_gain_; } steer_joint_->setPos(theta, period); return 1 - hermite(hermite_scale * (fabs(theta - theta_steer_) - hermite_offset)); } // Control this wheel's axle joint. void Wheel::ctrlAxle(const double lin_speed, const Duration& period) const { const double ang_vel = axle_vel_gain_ * inv_radius_ * lin_speed; axle_joint_->setVel(ang_vel, period); } // Initialize pos_. void Wheel::initPos(const KDL::Tree& tree, const string& base_link) { KDL::Chain chain; if (!tree.getChain(base_link, steer_link_, chain)) { throw runtime_error("No kinematic chain was found from \"" + base_link + "\" to \"" + steer_link_ + "\"."); } const unsigned int num_joints = chain.getNrOfJoints(); KDL::JntArray joint_positions(num_joints); for (unsigned int i = 0; i < num_joints; i++) joint_positions(i) = 0; KDL::ChainFkSolverPos_recursive solver(chain); KDL::Frame frame; if (solver.JntToCart(joint_positions, frame) < 0) { throw runtime_error("The position of steering link \"" + steer_link_ + "\" in base link frame \"" + base_link + "\" was not found."); } pos_ = Vector2d(frame.p.x(), frame.p.y()); } // Create an object of class Joint that corresponds to the URDF joint specified // by joint_name. shared_ptr<Joint> getJoint(const string& joint_name, const bool is_steer_joint, const NodeHandle& ctrlr_nh, const urdf::Model& urdf_model, EffortJointInterface *const eff_joint_iface, PositionJointInterface *const pos_joint_iface, VelocityJointInterface *const vel_joint_iface) { if (eff_joint_iface != NULL) { JointHandle handle; bool handle_found; try { handle = eff_joint_iface->getHandle(joint_name); handle_found = true; } catch (...) { handle_found = false; } if (handle_found) { const urdf::JointConstSharedPtr urdf_joint = urdf_model.getJoint(joint_name); if (urdf_joint == NULL) { throw runtime_error("\"" + joint_name + "\" was not found in the URDF data."); } shared_ptr<Joint> joint(new PIDJoint(handle, urdf_joint, ctrlr_nh)); return joint; } } if (pos_joint_iface != NULL) { JointHandle handle; bool handle_found; try { handle = pos_joint_iface->getHandle(joint_name); handle_found = true; } catch (...) { handle_found = false; } if (handle_found) { const urdf::JointConstSharedPtr urdf_joint = urdf_model.getJoint(joint_name); if (urdf_joint == NULL) { throw runtime_error("\"" + joint_name + "\" was not found in the URDF data."); } shared_ptr<Joint> joint(new PosJoint(handle, urdf_joint)); return joint; } } if (vel_joint_iface != NULL) { JointHandle handle; bool handle_found; try { handle = vel_joint_iface->getHandle(joint_name); handle_found = true; } catch (...) { handle_found = false; } if (handle_found) { const urdf::JointConstSharedPtr urdf_joint = urdf_model.getJoint(joint_name); if (urdf_joint == NULL) { throw runtime_error("\"" + joint_name + "\" was not found in the URDF data."); } if (is_steer_joint) { shared_ptr<Joint> joint(new PIDJoint(handle, urdf_joint, ctrlr_nh)); return joint; } shared_ptr<Joint> joint(new VelJoint(handle, urdf_joint)); return joint; } } throw runtime_error("No handle for \"" + joint_name + "\" was found."); } } // namespace namespace steered_wheel_base_controller{ // Steered-wheel base controller class SteeredWheelBaseController : public controller_interface::ControllerBase { public: SteeredWheelBaseController(); // These are not real-time safe. virtual bool initRequest(RobotHW *const robot_hw, NodeHandle& root_nh, NodeHandle& ctrlr_nh, ClaimedResources& claimed_resources); virtual string getHardwareInterfaceType() const; // These are real-time safe. virtual void starting(const Time& time); virtual void update(const Time& time, const Duration& period); virtual void stopping(const Time& time); private: struct VelCmd // Velocity command { double x_vel; // X velocity component. Unit: m/s. double y_vel; // Y velocity component. Unit: m/s. double yaw_vel; // Yaw velocity. Unit: rad/s. // last_vel_cmd_time is the time at which the most recent velocity command // was received. Time last_vel_cmd_time; }; static const string DEF_ROBOT_DESC_NAME; static const string DEF_BASE_LINK; static const double DEF_CMD_VEL_TIMEOUT; static const double DEF_LIN_SPEED_LIMIT; static const double DEF_LIN_ACCEL_LIMIT; static const double DEF_LIN_DECEL_LIMIT; static const double DEF_YAW_SPEED_LIMIT; static const double DEF_YAW_ACCEL_LIMIT; static const double DEF_YAW_DECEL_LIMIT; static const double DEF_FULL_AXLE_SPEED_ANG; static const double DEF_ZERO_AXLE_SPEED_ANG; static const double DEF_WHEEL_DIA_SCALE; static const double DEF_ODOM_PUB_FREQ; static const string DEF_ODOM_FRAME; static const string DEF_BASE_FRAME; static const double DEF_INIT_X; static const double DEF_INIT_Y; static const double DEF_INIT_YAW; static const Vector2d X_DIR; void init(EffortJointInterface *const eff_joint_iface, PositionJointInterface *const pos_joint_iface, VelocityJointInterface *const vel_joint_iface, NodeHandle& ctrlr_nh); void velCmdCB(const TwistConstPtr& vel_cmd); Vector2d enforceLinLimits(const Vector2d& desired_vel, const double delta_t, const double inv_delta_t); double enforceYawLimits(const double desired_vel, const double delta_t, const double inv_delta_t); void ctrlWheels(const Vector2d& lin_vel, const double yaw_vel, const Duration& period); void compOdometry(const Time& time, const double inv_delta_t); std::vector<Wheel> wheels_; // Linear motion limits bool has_lin_speed_limit_; double lin_speed_limit_; bool has_lin_accel_limit_; double lin_accel_limit_; bool has_lin_decel_limit_; double lin_decel_limit_; // Yaw limits bool has_yaw_speed_limit_; double yaw_speed_limit_; bool has_yaw_accel_limit_; double yaw_accel_limit_; bool has_yaw_decel_limit_; double yaw_decel_limit_; double hermite_scale_, hermite_offset_; Vector2d last_lin_vel_; // Last linear velocity. Unit: m/s. double last_yaw_vel_; // Last yaw velocity. Unit: rad/s. // Velocity command member variables VelCmd vel_cmd_; RealtimeBuffer<VelCmd> vel_cmd_buf_; bool vel_cmd_timeout_enabled_; Duration vel_cmd_timeout_; ros::Subscriber vel_cmd_sub_; // Odometry bool comp_odom_; // Compute odometry Duration odom_pub_period_; // Odometry publishing period Affine2d init_odom_to_base_; // Initial odometry to base frame transform Affine2d odom_to_base_; // Odometry to base frame transform Affine2d odom_affine_; double last_odom_x_, last_odom_y_, last_odom_yaw_; // wheel_pos_ contains the positions of the wheel's steering axles. // The positions are relative to the centroid of the steering axle positions // in the base link's frame. neg_wheel_centroid is the negative version of // that centroid. Eigen::Matrix2Xd wheel_pos_; Vector2d neg_wheel_centroid_; Eigen::MatrixX2d new_wheel_pos_; RealtimePublisher<nav_msgs::Odometry> odom_pub_; RealtimePublisher<tf::tfMessage> odom_tf_pub_; Time last_odom_pub_time_, last_odom_tf_pub_time_; }; const string SteeredWheelBaseController::DEF_ROBOT_DESC_NAME = "robot_description"; // NOLINT(runtime/string) const string SteeredWheelBaseController::DEF_BASE_LINK = "base_link"; // NOLINT(runtime/string) const double SteeredWheelBaseController::DEF_CMD_VEL_TIMEOUT = 0.5; const double SteeredWheelBaseController::DEF_LIN_SPEED_LIMIT = 1; const double SteeredWheelBaseController::DEF_LIN_ACCEL_LIMIT = 1; const double SteeredWheelBaseController::DEF_LIN_DECEL_LIMIT = -1; const double SteeredWheelBaseController::DEF_YAW_SPEED_LIMIT = 1; const double SteeredWheelBaseController::DEF_YAW_ACCEL_LIMIT = 1; const double SteeredWheelBaseController::DEF_YAW_DECEL_LIMIT = -1; const double SteeredWheelBaseController::DEF_FULL_AXLE_SPEED_ANG = 0.7854; const double SteeredWheelBaseController::DEF_ZERO_AXLE_SPEED_ANG = 1.5708; const double SteeredWheelBaseController::DEF_WHEEL_DIA_SCALE = 1; const double SteeredWheelBaseController::DEF_ODOM_PUB_FREQ = 30; const string SteeredWheelBaseController::DEF_ODOM_FRAME = "odom"; // NOLINT(runtime/string) const string SteeredWheelBaseController::DEF_BASE_FRAME = "base_link"; // NOLINT(runtime/string) const double SteeredWheelBaseController::DEF_INIT_X = 0; const double SteeredWheelBaseController::DEF_INIT_Y = 0; const double SteeredWheelBaseController::DEF_INIT_YAW = 0; // X direction const Vector2d SteeredWheelBaseController::X_DIR = Vector2d::UnitX(); SteeredWheelBaseController::SteeredWheelBaseController() { state_ = CONSTRUCTED; } bool SteeredWheelBaseController::initRequest(RobotHW *const robot_hw, NodeHandle& /* root_nh */, NodeHandle& ctrlr_nh, ClaimedResources& claimed_resources) { if (state_ != CONSTRUCTED) { ROS_ERROR("The steered-wheel base controller could not be created."); return false; } EffortJointInterface *const eff_joint_iface = robot_hw->get<EffortJointInterface>(); PositionJointInterface *const pos_joint_iface = robot_hw->get<PositionJointInterface>(); VelocityJointInterface *const vel_joint_iface = robot_hw->get<VelocityJointInterface>(); if (eff_joint_iface != NULL) eff_joint_iface->clearClaims(); if (pos_joint_iface != NULL) pos_joint_iface->clearClaims(); if (vel_joint_iface != NULL) vel_joint_iface->clearClaims(); try { init(eff_joint_iface, pos_joint_iface, vel_joint_iface, ctrlr_nh); } catch (const std::exception& ex) { ROS_ERROR_STREAM(ex.what()); return false; } claimed_resources.clear(); addClaimedResources(eff_joint_iface, "hardware_interface::EffortJointInterface", claimed_resources); addClaimedResources(pos_joint_iface, "hardware_interface::PositionJointInterface", claimed_resources); addClaimedResources(vel_joint_iface, "hardware_interface::VelocityJointInterface", claimed_resources); state_ = INITIALIZED; return true; } string SteeredWheelBaseController::getHardwareInterfaceType() const { return ""; } void SteeredWheelBaseController::starting(const Time& time) { BOOST_FOREACH(Wheel & wheel, wheels_) wheel.initJoints(); last_lin_vel_ = Vector2d(0, 0); last_yaw_vel_ = 0; if (comp_odom_) { last_odom_x_ = odom_to_base_.translation().x(); last_odom_y_ = odom_to_base_.translation().y(); last_odom_yaw_ = atan2(odom_to_base_(1, 0), odom_to_base_(0, 0)); last_odom_pub_time_ = time; last_odom_tf_pub_time_ = time; } vel_cmd_.x_vel = 0; vel_cmd_.y_vel = 0; vel_cmd_.yaw_vel = 0; vel_cmd_.last_vel_cmd_time = time; vel_cmd_buf_.initRT(vel_cmd_); } void SteeredWheelBaseController::update(const Time& time, const Duration& period) { const double delta_t = period.toSec(); if (delta_t <= 0) return; vel_cmd_ = *(vel_cmd_buf_.readFromRT()); Vector2d desired_lin_vel; double desired_yaw_vel; if (!vel_cmd_timeout_enabled_ || time - vel_cmd_.last_vel_cmd_time <= vel_cmd_timeout_) { desired_lin_vel = Vector2d(vel_cmd_.x_vel, vel_cmd_.y_vel); desired_yaw_vel = vel_cmd_.yaw_vel; } else { // Too much time has elapsed since the last velocity command was received. // Stop the robot. desired_lin_vel.setZero(); desired_yaw_vel = 0; } const double inv_delta_t = 1 / delta_t; const Vector2d lin_vel = enforceLinLimits(desired_lin_vel, delta_t, inv_delta_t); const double yaw_vel = enforceYawLimits(desired_yaw_vel, delta_t, inv_delta_t); ctrlWheels(lin_vel, yaw_vel, period); if (comp_odom_) compOdometry(time, inv_delta_t); } void SteeredWheelBaseController::stopping(const Time& time) { BOOST_FOREACH(Wheel & wheel, wheels_) wheel.stop(); } // Initialize this steered-wheel base controller. void SteeredWheelBaseController:: init(EffortJointInterface *const eff_joint_iface, PositionJointInterface *const pos_joint_iface, VelocityJointInterface *const vel_joint_iface, NodeHandle& ctrlr_nh) { string robot_desc_name; ctrlr_nh.param("robot_description_name", robot_desc_name, DEF_ROBOT_DESC_NAME); urdf::Model urdf_model; if (!urdf_model.initParam(robot_desc_name)) throw runtime_error("The URDF data was not found."); KDL::Tree model_tree; if (!kdl_parser::treeFromUrdfModel(urdf_model, model_tree)) throw runtime_error("The kinematic tree could not be created."); string base_link; ctrlr_nh.param("base_link", base_link, DEF_BASE_LINK); double timeout; ctrlr_nh.param("cmd_vel_timeout", timeout, DEF_CMD_VEL_TIMEOUT); vel_cmd_timeout_enabled_ = timeout > 0; if (vel_cmd_timeout_enabled_) vel_cmd_timeout_.fromSec(timeout); ctrlr_nh.param("linear_speed_limit", lin_speed_limit_, DEF_LIN_SPEED_LIMIT); has_lin_speed_limit_ = lin_speed_limit_ >= 0; ctrlr_nh.param("linear_acceleration_limit", lin_accel_limit_, DEF_LIN_ACCEL_LIMIT); has_lin_accel_limit_ = lin_accel_limit_ >= 0; // For safety, a valid deceleration limit must be greater than zero. ctrlr_nh.param("linear_deceleration_limit", lin_decel_limit_, DEF_LIN_DECEL_LIMIT); has_lin_decel_limit_ = lin_decel_limit_ > 0; ctrlr_nh.param("yaw_speed_limit", yaw_speed_limit_, DEF_YAW_SPEED_LIMIT); has_yaw_speed_limit_ = yaw_speed_limit_ >= 0; ctrlr_nh.param("yaw_acceleration_limit", yaw_accel_limit_, DEF_YAW_ACCEL_LIMIT); has_yaw_accel_limit_ = yaw_accel_limit_ >= 0; // For safety, a valid deceleration limit must be greater than zero. ctrlr_nh.param("yaw_deceleration_limit", yaw_decel_limit_, DEF_YAW_DECEL_LIMIT); has_yaw_decel_limit_ = yaw_decel_limit_ > 0; ctrlr_nh.param("full_axle_speed_angle", hermite_offset_, DEF_FULL_AXLE_SPEED_ANG); if (hermite_offset_ < 0 || hermite_offset_ > M_PI) throw runtime_error("full_axle_speed_angle must be in the range [0, pi]."); double zero_axle_speed_ang; ctrlr_nh.param("zero_axle_speed_angle", zero_axle_speed_ang, DEF_ZERO_AXLE_SPEED_ANG); if (zero_axle_speed_ang < 0 || zero_axle_speed_ang > M_PI) throw runtime_error("zero_axle_speed_angle must be in the range [0, pi]."); if (hermite_offset_ >= zero_axle_speed_ang) { throw runtime_error("full_axle_speed_angle must be less than " "zero_axle_speed_angle."); } hermite_scale_ = 1 / (zero_axle_speed_ang - hermite_offset_); // Wheels XmlRpcValue wheel_param_list; if (!ctrlr_nh.getParam("wheels", wheel_param_list)) throw runtime_error("No wheels were specified."); if (wheel_param_list.getType() != XmlRpcValue::TypeArray) throw runtime_error("The specified list of wheels is invalid."); if (wheel_param_list.size() < 2) throw runtime_error("At least two wheels must be specified."); double wheel_dia_scale; ctrlr_nh.param("wheel_diameter_scale", wheel_dia_scale, DEF_WHEEL_DIA_SCALE); if (wheel_dia_scale <= 0) { throw runtime_error("The specified wheel diameter scale is less than or " "equal to zero."); } for (int i = 0; i < wheel_param_list.size(); i++) { XmlRpcValue& wheel_params = wheel_param_list[i]; if (wheel_params.getType() != XmlRpcValue::TypeStruct) throw runtime_error("The specified list of wheels is invalid."); if (!wheel_params.hasMember("steering_joint")) throw runtime_error("A steering joint was not specified."); XmlRpcValue& xml_steer_joint = wheel_params["steering_joint"]; if (!xml_steer_joint.valid() || xml_steer_joint.getType() != XmlRpcValue::TypeString) { throw runtime_error("An invalid steering joint was specified."); } const string steer_joint_name = xml_steer_joint; const urdf::JointConstSharedPtr steer_joint = urdf_model.getJoint(steer_joint_name); if (steer_joint == NULL) { throw runtime_error("Steering joint \"" + steer_joint_name + "\" was not found in the URDF data."); } const string steer_link = steer_joint->child_link_name; if (!wheel_params.hasMember("axle_joint")) throw runtime_error("An axle joint was not specified."); XmlRpcValue& xml_axle_joint = wheel_params["axle_joint"]; if (!xml_axle_joint.valid() || xml_axle_joint.getType() != XmlRpcValue::TypeString) { throw runtime_error("An invalid axle joint was specified."); } const string axle_joint_name = xml_axle_joint; if (!wheel_params.hasMember("diameter")) throw runtime_error("A wheel diameter was not specified."); XmlRpcValue& xml_dia = wheel_params["diameter"]; if (!xml_dia.valid()) throw runtime_error("An invalid wheel diameter was specified."); double dia; switch (xml_dia.getType()) { case XmlRpcValue::TypeInt: { const int tmp = xml_dia; dia = tmp; } break; case XmlRpcValue::TypeDouble: dia = xml_dia; break; default: throw runtime_error("An invalid wheel diameter was specified."); } if (dia <= 0) { throw runtime_error("A specified wheel diameter is less than or " "equal to zero."); } // Circumference const double circ = (2 * M_PI) * (wheel_dia_scale * dia) / 2; wheels_.push_back(Wheel(model_tree, base_link, steer_link, getJoint(steer_joint_name, true, ctrlr_nh, urdf_model, eff_joint_iface, pos_joint_iface, vel_joint_iface), getJoint(axle_joint_name, false, ctrlr_nh, urdf_model, eff_joint_iface, pos_joint_iface, vel_joint_iface), circ)); } // Odometry double odom_pub_freq; ctrlr_nh.param("odometry_publishing_frequency", odom_pub_freq, DEF_ODOM_PUB_FREQ); comp_odom_ = odom_pub_freq > 0; if (comp_odom_) { odom_pub_period_ = Duration(1 / odom_pub_freq); double init_x, init_y, init_yaw; ctrlr_nh.param("initial_x", init_x, DEF_INIT_X); ctrlr_nh.param("initial_y", init_y, DEF_INIT_Y); ctrlr_nh.param("initial_yaw", init_yaw, DEF_INIT_YAW); init_odom_to_base_.setIdentity(); init_odom_to_base_.rotate(clamp(init_yaw, -M_PI, M_PI)); init_odom_to_base_.translation() = Vector2d(init_x, init_y); odom_to_base_ = init_odom_to_base_; odom_affine_.setIdentity(); wheel_pos_.resize(2, wheels_.size()); for (size_t col = 0; col < wheels_.size(); col++) wheel_pos_.col(col) = wheels_[col].pos(); const Vector2d centroid = wheel_pos_.rowwise().mean(); wheel_pos_.colwise() -= centroid; neg_wheel_centroid_ = -centroid; new_wheel_pos_.resize(wheels_.size(), 2); string odom_frame, base_frame; ctrlr_nh.param("odometry_frame", odom_frame, DEF_ODOM_FRAME); ctrlr_nh.param("base_frame", base_frame, DEF_BASE_FRAME); odom_pub_.msg_.header.frame_id = odom_frame; odom_pub_.msg_.child_frame_id = base_frame; odom_pub_.msg_.pose.pose.position.z = 0; odom_pub_.msg_.twist.twist.linear.z = 0; odom_pub_.msg_.twist.twist.angular.x = 0; odom_pub_.msg_.twist.twist.angular.y = 0; odom_pub_.init(ctrlr_nh, "/odom", 1); odom_tf_pub_.msg_.transforms.resize(1); geometry_msgs::TransformStamped& odom_tf_trans = odom_tf_pub_.msg_.transforms[0]; odom_tf_trans.header.frame_id = odom_pub_.msg_.header.frame_id; odom_tf_trans.child_frame_id = odom_pub_.msg_.child_frame_id; odom_tf_trans.transform.translation.z = 0; odom_tf_pub_.init(ctrlr_nh, "/tf", 1); } vel_cmd_sub_ = ctrlr_nh.subscribe("/cmd_vel", 1, &SteeredWheelBaseController::velCmdCB, this); } // Velocity command callback void SteeredWheelBaseController::velCmdCB(const TwistConstPtr& vel_cmd) { vel_cmd_.x_vel = vel_cmd->linear.x; vel_cmd_.y_vel = vel_cmd->linear.y; vel_cmd_.yaw_vel = vel_cmd->angular.z; vel_cmd_.last_vel_cmd_time = Time::now(); vel_cmd_buf_.writeFromNonRT(vel_cmd_); } // Enforce linear motion limits. Vector2d SteeredWheelBaseController:: enforceLinLimits(const Vector2d& desired_vel, const double delta_t, const double inv_delta_t) { Vector2d vel = desired_vel; if (has_lin_speed_limit_) { const double vel_mag = vel.norm(); if (vel_mag > lin_speed_limit_) vel = (vel / vel_mag) * lin_speed_limit_; } Vector2d accel = (vel - last_lin_vel_) * inv_delta_t; if (accel.dot(last_lin_vel_) >= 0) { // Acceleration if (has_lin_accel_limit_) { const double accel_mag = accel.norm(); if (accel_mag > lin_accel_limit_) { accel = (accel / accel_mag) * lin_accel_limit_; vel = last_lin_vel_ + accel * delta_t; } } } else { // Deceleration if (has_lin_decel_limit_) { const double accel_mag = accel.norm(); if (accel_mag > lin_decel_limit_) { accel = (accel / accel_mag) * lin_decel_limit_; vel = last_lin_vel_ + accel * delta_t; } } if (vel.dot(last_lin_vel_) < 0) vel = Vector2d(0, 0); } last_lin_vel_ = vel; return vel; } double SteeredWheelBaseController::enforceYawLimits(const double desired_vel, const double delta_t, const double inv_delta_t) { double vel = desired_vel; if (has_yaw_speed_limit_) vel = clamp(vel, -yaw_speed_limit_, yaw_speed_limit_); double accel = (vel - last_yaw_vel_) * inv_delta_t; const double accel_sign = sign(accel); const double last_yaw_vel_sign = sign(last_yaw_vel_); if (accel_sign == last_yaw_vel_sign || last_yaw_vel_sign == 0) { // Acceleration if (has_yaw_accel_limit_ && fabs(accel) > yaw_accel_limit_) { accel = accel_sign * yaw_accel_limit_; vel = last_yaw_vel_ + accel * delta_t; } } else { // Deceleration if (has_yaw_decel_limit_ && fabs(accel) > yaw_decel_limit_) { accel = accel_sign * yaw_decel_limit_; vel = last_yaw_vel_ + accel * delta_t; } if (sign(vel) != last_yaw_vel_sign) vel = 0; } last_yaw_vel_ = vel; return vel; } // Control the wheels. void SteeredWheelBaseController::ctrlWheels(const Vector2d& lin_vel, const double yaw_vel, const Duration& period) { const double lin_speed = lin_vel.norm(); if (yaw_vel == 0) { if (lin_speed > 0) { // Point the wheels in the same direction. const Vector2d dir = lin_vel / lin_speed; const double theta = copysign(acos(dir.dot(SteeredWheelBaseController::X_DIR)), dir.y()); double min_speed_gain = 1; BOOST_FOREACH(Wheel & wheel, wheels_) { const double speed_gain = wheel.ctrlSteering(theta, period, hermite_scale_, hermite_offset_); } const double lin_speed_2 = min_speed_gain * lin_speed; BOOST_FOREACH(Wheel & wheel, wheels_) { wheel.ctrlAxle(lin_speed_2, period); } } else { // Stop wheel rotation. BOOST_FOREACH(Wheel & wheel, wheels_) { wheel.ctrlSteering(period, hermite_scale_, hermite_offset_); wheel.ctrlAxle(0, period); } } } else // The yaw velocity is nonzero. { // Align the wheels so that they are tangent to circles centered // at "center". Vector2d center; if (lin_speed > 0) { const Vector2d dir = lin_vel / lin_speed; center = Vector2d(-dir.y(), dir.x()) * lin_speed / yaw_vel; } else { center.setZero(); } std::vector<double> radii; double min_speed_gain = 1; BOOST_FOREACH(Wheel & wheel, wheels_) { Vector2d vec = wheel.pos(); vec -= center; const double radius = vec.norm(); radii.push_back(radius); double theta; if (radius > 0) { vec /= radius; theta = copysign(acos(vec.dot(SteeredWheelBaseController::X_DIR)), vec.y()) + M_PI_2; } else { theta = 0; } const double speed_gain = wheel.ctrlSteering(theta, period, hermite_scale_, hermite_offset_); } const double lin_speed_gain = min_speed_gain * yaw_vel; size_t i = 0; BOOST_FOREACH(Wheel & wheel, wheels_) { wheel.ctrlAxle(lin_speed_gain * radii[i++], period); } } } // Compute odometry. void SteeredWheelBaseController::compOdometry(const Time& time, const double inv_delta_t) { // Compute the rigid transform from wheel_pos_ to new_wheel_pos_. for (size_t row = 0; row < wheels_.size(); row++) new_wheel_pos_.row(row) = wheels_[row].pos() + wheels_[row].getDeltaPos(); const Eigen::RowVector2d new_wheel_centroid = new_wheel_pos_.colwise().mean(); new_wheel_pos_.rowwise() -= new_wheel_centroid; const Matrix2d h = wheel_pos_ * new_wheel_pos_; const Eigen::JacobiSVD<Matrix2d> svd(h, Eigen::ComputeFullU | Eigen::ComputeFullV); Matrix2d rot = svd.matrixV() * svd.matrixU().transpose(); if (rot.determinant() < 0) rot.col(1) *= -1; odom_affine_.matrix().block(0, 0, 2, 2) = rot; odom_affine_.translation() = rot * neg_wheel_centroid_ + new_wheel_centroid.transpose(); odom_to_base_ = odom_to_base_ * odom_affine_; const double odom_x = odom_to_base_.translation().x(); const double odom_y = odom_to_base_.translation().y(); const double odom_yaw = atan2(odom_to_base_(1, 0), odom_to_base_(0, 0)); // Publish the odometry. geometry_msgs::Quaternion orientation; bool orientation_comped = false; // tf if (time - last_odom_tf_pub_time_ >= odom_pub_period_ && odom_tf_pub_.trylock()) { orientation = tf::createQuaternionMsgFromYaw(odom_yaw); orientation_comped = true; geometry_msgs::TransformStamped& odom_tf_trans = odom_tf_pub_.msg_.transforms[0]; odom_tf_trans.header.stamp = time; odom_tf_trans.transform.translation.x = odom_x; odom_tf_trans.transform.translation.y = odom_y; odom_tf_trans.transform.rotation = orientation; odom_tf_pub_.unlockAndPublish(); last_odom_tf_pub_time_ = time; } // odom if (time - last_odom_pub_time_ >= odom_pub_period_ && odom_pub_.trylock()) { if (!orientation_comped) orientation = tf::createQuaternionMsgFromYaw(odom_yaw); odom_pub_.msg_.header.stamp = time; odom_pub_.msg_.pose.pose.position.x = odom_x; odom_pub_.msg_.pose.pose.position.y = odom_y; odom_pub_.msg_.pose.pose.orientation = orientation; odom_pub_.msg_.twist.twist.linear.x = (odom_x - last_odom_x_) * inv_delta_t; odom_pub_.msg_.twist.twist.linear.y = (odom_y - last_odom_y_) * inv_delta_t; odom_pub_.msg_.twist.twist.angular.z = (odom_yaw - last_odom_yaw_) * inv_delta_t; odom_pub_.unlockAndPublish(); last_odom_pub_time_ = time; } last_odom_x_ = odom_x; last_odom_y_ = odom_y; last_odom_yaw_ = odom_yaw; } } // namespace steered_wheel_base_controller PLUGINLIB_EXPORT_CLASS(steered_wheel_base_controller::SteeredWheelBaseController, controller_interface::ControllerBase)
33.882725
182
0.648304
[ "geometry", "object", "vector", "model", "transform" ]
cf649557d4fb180bdf613af0890f916d4f26308c
35,163
cxx
C++
SmallUPBP/src/Bre/Bre.cxx
PetrVevoda/smallupbp
15430256733938d529a2f5c7ef4cdcd940ae4208
[ "MIT", "Apache-2.0", "Unlicense" ]
107
2015-01-27T22:01:49.000Z
2021-12-27T07:44:25.000Z
SmallUPBP/src/Bre/Bre.cxx
PetrVevoda/smallupbp
15430256733938d529a2f5c7ef4cdcd940ae4208
[ "MIT", "Apache-2.0", "Unlicense" ]
1
2015-03-17T18:53:59.000Z
2015-03-17T18:53:59.000Z
SmallUPBP/src/Bre/Bre.cxx
PetrVevoda/smallupbp
15430256733938d529a2f5c7ef4cdcd940ae4208
[ "MIT", "Apache-2.0", "Unlicense" ]
17
2015-03-12T19:11:30.000Z
2020-11-30T15:51:23.000Z
/* * Copyright (C) 2014, Petr Vevoda, Martin Sik (http://cgg.mff.cuni.cz/~sik/), * Tomas Davidovic (http://www.davidovic.cz), Iliyan Georgiev (http://www.iliyan.com/), * Jaroslav Krivanek (http://cgg.mff.cuni.cz/~jaroslav/) * * 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. * * (The above is MIT License: http://en.wikipedia.origin/wiki/MIT_License) */ // embree includes #include "include\embree.h" #include "common\ray.h" #include "Bre.hxx" #include "..\Beams\PhBeams.hxx" #include "..\Misc\Timer.hxx" #include "..\Misc\KdTmpl.hxx" #include "..\Misc\DebugImages.hxx" #include "..\Path\PathWeight.hxx" #include "..\Structs\BoundingBox.hxx" /** * @brief Defines an alias representing the kd tree. */ typedef KdTreeTmplPtr< Pos,Pos > KdTree; const float MAX_FLOAT_SQUARE_ROOT = std::sqrtf(std::numeric_limits< float >::max()); //!< The maximum float square root // ---------------------------------------------------------------------------------------------- /** * @brief Converts the \c Pos to \c embree::Vector3f. * * @param pos The position. * * @return Pos as an embree::Vector3f. */ INLINE embree::Vector3f toEmbreeV3f (const Pos& pos) { return embree::Vector3f(pos.x(), pos.y(), pos.z()); } // ---------------------------------------------------------------------------------------------- /** * @brief Converts the \c Dir to \c embree::Vector3f. * * @param dir The direction. * * @return Dir as an embree::Vector3f. */ INLINE embree::Vector3f toEmbreeV3f (const Dir& dir) { return embree::Vector3f(dir.x(), dir.y(), dir.z()); } // ---------------------------------------------------------------------------------------------- INLINE Pos toPos(const embree::Vector3f& pos) { return Pos(pos.x, pos.y, pos.z); } // ---------------------------------------------------------------------------------------------- /** * @brief Converts \c embree::Vector3f to \c Pos. * * @param dir The direction. * * @return embree::Vector3f as a Dir. */ INLINE Dir toDir(const embree::Vector3f& dir) { return Dir(dir.x, dir.y, dir.z); } // ---------------------------------------------------------------------------------------------- /** * @brief An embree photon. */ class EmbreePhoton : public embree::Intersector1 { public: Pos pos; //!< The position. float radius; //!< The radius. float radiusSqr; //!< The radius squared. Dir incDir; //!< The incoming direction. Rgb flux; //!< The flux. const UPBPLightVertex *lightVertex; //!< The corresponding light vertex. /** * @brief Default constructor. */ EmbreePhoton() {} /** * @brief Constructor. * * @param aPos The position. * @param aRadius The radius. * @param aIncDir The incoming direction. * @param aFlux The flux. */ EmbreePhoton(const Pos& aPos, const float aRadius, const Dir& aIncDir, const Rgb& aFlux ) : Intersector1( breIntersectFuncHomogeneous, breOccludedFunc ) , pos(aPos) , radius(aRadius) , radiusSqr(aRadius*aRadius) , incDir(aIncDir) , flux(aFlux) { } /** * @brief Sets photon properties and function pointers. * * @param aPos The position. * @param aRadius The radius. * @param aIncDir The incoming direction. * @param aFlux The flux. */ void set(const Pos& aPos, const float aRadius, const Dir& aIncDir, const Rgb& aFlux) { intersectPtr = breIntersectFuncHomogeneous; occludedPtr = breOccludedFunc; pos = aPos; radius = aRadius; radiusSqr = aRadius*aRadius; incDir = aIncDir; flux = aFlux; } /** * @brief Sets photon properties and function pointers. * * @param aRadius The radius. * @param aLightVertex The light vertex corresponding to the photon. */ void set(const float aRadius, const UPBPLightVertex * aLightVertex) { intersectPtr = breIntersectFuncHomogeneous2; occludedPtr = breOccludedFunc; pos = aLightVertex->mHitpoint; radius = aRadius; radiusSqr = aRadius*aRadius; lightVertex = aLightVertex; } /** * @brief Gets the bounding box. * * @return The bounding box. */ BoundingBox3 getBbox() { return BoundingBox3( pos - Dir(radius), pos + Dir(radius) ); } /** * @brief Test intersection between a ray and a 'photon disc'. * * The photon disc is specified by the position aPhotonPos and radius aPhotonRad. The * disc is assumed to face the ray (i.e. the disc plane is perpendicular to the ray). * Intersections are reported only in the interval [aMinT, aMaxT) (i.e. includes aMinT * but excludes aMaxT). * * @param [in,out] oIsectDist The intersection distance along the ray. * @param [in,out] oIsectRadSqr The square of the distance of the intersection point from the photon location. * @param aQueryRay The query ray. * @param aMinT The minimum t. * @param aMaxT The maximum t. * @param aPhotonPos The photon position. * @param aPhotonRadSqr The photon radius. * * @return true is an intersection is found, false otherwise. If an intersection is found, * oIsectDist is set to the intersection distance along the ray, and oIsectRadSqr is set * to the square of the distance of the intersection point from the photon location. */ static INLINE bool testIntersectionBre( float& oIsectDist, float& oIsectRadSqr, const Ray &aQueryRay, const float aMinT, const float aMaxT, const Pos &aPhotonPos, const float aPhotonRadSqr) { const Dir rayOrigToPhoton = aPhotonPos - aQueryRay.origin; const float isectDist = dot(rayOrigToPhoton, aQueryRay.direction); if ( isectDist > aMinT && isectDist < aMaxT ) { const float isectRadSqr = (aQueryRay.origin + aQueryRay.direction * isectDist - aPhotonPos).square(); if ( isectRadSqr <= aPhotonRadSqr ) { oIsectDist = isectDist; oIsectRadSqr = isectRadSqr; return true; } } return false; } /** * @brief BRE intersection function for a photon. * * Version used by pure PB2D algorithm from \c VolLightTracer.hxx. * * @param This EmbreePhoton that we are testing intersection with. * @param [in,out] ray BRE query ray. * * @return If no intersection is found, ray is left unchanged. To report an intersection * back to embree, one needs to set ray.tfar to the intersection distance and * ray.id0 and ray.id1 to the id of the intersected object. In the BRE query we * never report intersections to embree because we want to keep traversing the data * structure. */ static void breIntersectFuncHomogeneous(const embree::Intersector1* This, embree::Ray& ray) { const EmbreePhoton* thisPhoton = (const EmbreePhoton*)This; float photonIsectDist, isectRadSqr; if (testIntersectionBre(photonIsectDist, isectRadSqr, *ray.origRay, ray.tnear, ray.tfar, thisPhoton->pos, thisPhoton->radiusSqr)) { // Found an intersection. const Pos isectPt = ray.origRay->origin + photonIsectDist * ray.origRay->direction; const Rgb& scatteringCoeff = ray.medium->IsHomogeneous() ? ((const HomogeneousMedium *)ray.medium)->GetScatteringCoef() : ray.medium->GetScatteringCoef(isectPt); Rgb attenuation; if (ray.medium->IsHomogeneous()) { const HomogeneousMedium * medium = ((const HomogeneousMedium *)ray.medium); attenuation = medium->EvalAttenuation(photonIsectDist - ray.tnear); if (ray.flags & SHORT_BEAM) attenuation /= attenuation[medium->mMinPositiveAttenuationCoefCompIndex()]; } else { attenuation = ray.medium->EvalAttenuation(*ray.origRay, ray.tnear, photonIsectDist); if (ray.flags & SHORT_BEAM) attenuation /= ray.medium->RaySamplePdf(*ray.origRay, ray.tnear, photonIsectDist); } *static_cast<Rgb*>(ray.accumResult) += thisPhoton->flux * attenuation * scatteringCoeff * PhaseFunction::Evaluate(ray.origRay->direction, -thisPhoton->incDir, ray.medium->MeanCosine()) * // Epanechnikov kernel (1 - isectRadSqr / thisPhoton->radiusSqr) / (thisPhoton->radiusSqr * PI_F * 0.5f); //UPBP_ASSERT((1 - isectRadSqr) / (PI_F * (thisPhoton->radiusSqr - thisPhoton->radiusSqr * thisPhoton->radiusSqr * 0.5f)) > 0.0f); } } /** * @brief BRE intersection function for a photon. * * Version used by combined PB2D algorithms from \c UPBP.hxx. * * @param This EmbreePhoton that we are testing intersection with. * @param [in,out] ray BRE query ray. * * @return If no intersection is found, ray is left unchanged. To report an intersection * back to embree, one needs to set ray.tfar to the intersection distance and * ray.id0 and ray.id1 to the id of the intersected object. In the BRE query we * never report intersections to embree because we want to keep traversing the data * structure. */ static void breIntersectFuncHomogeneous2(const embree::Intersector1* This, embree::Ray& ray) { const EmbreePhoton* thisPhoton = (const EmbreePhoton*)This; const UPBPLightVertex* lightVertex = thisPhoton->lightVertex; const embree::AdditionalRayDataForMis* data = ray.additionalRayDataForMis; UPBP_ASSERT(lightVertex); UPBP_ASSERT(lightVertex->mInMedium); UPBP_ASSERT(data); float photonIsectDist, isectRadSqr; if (testIntersectionBre(photonIsectDist, isectRadSqr, *ray.origRay, ray.tnear, ray.tfar, lightVertex->mHitpoint, thisPhoton->radiusSqr)) { UPBP_ASSERT(photonIsectDist); // Heterogeneous medium is not supported. UPBP_ASSERT(ray.medium->IsHomogeneous()); // Reject if full path length below/above min/max path length. if ((lightVertex->mPathLength + data->mCameraPathLength > data->mMaxPathLength) || (lightVertex->mPathLength + data->mCameraPathLength < data->mMinPathLength)) return; // Ignore contribution of primary rays from medium too close to camera. if (data->mCameraPathLength == 1 && photonIsectDist < data->mMinDistToMed) return; // Compute intersection. const Pos isectPt = ray.origRay->origin + photonIsectDist * ray.origRay->direction; // Compute attenuation in current segment and overall pdfs. Rgb attenuation; float raySamplePdf = 1.0f; float raySampleRevPdf = 1.0f; float raySamplePdfsRatio = 1.0f; if (ray.medium->IsHomogeneous()) { const HomogeneousMedium * medium = ((const HomogeneousMedium *)ray.medium); attenuation = medium->EvalAttenuation(photonIsectDist - ray.tnear); const float pdf = attenuation[medium->mMinPositiveAttenuationCoefCompIndex()]; if (ray.flags & SHORT_BEAM) attenuation /= pdf; raySamplePdf = medium->mMinPositiveAttenuationCoefComp() * pdf; raySampleRevPdf = (data->mRaySamplingFlags & AbstractMedium::kOriginInMedium) ? raySamplePdf : pdf; raySamplePdfsRatio = 1.0f / medium->mMinPositiveAttenuationCoefComp(); } else { attenuation = ray.medium->EvalAttenuation(*ray.origRay, ray.tnear, photonIsectDist); if (ray.flags & SHORT_BEAM) attenuation /= ray.medium->RaySamplePdf(*ray.origRay, ray.tnear, photonIsectDist); raySamplePdf = ray.medium->RaySamplePdf(*ray.origRay, ray.tnear, photonIsectDist, data->mRaySamplingFlags, &raySampleRevPdf); raySamplePdfsRatio = ray.medium->RaySamplePdf(*ray.origRay, ray.tnear, photonIsectDist, 0) / raySamplePdf; } if (!attenuation.isPositive()) return; raySamplePdf *= data->mRaySamplePdf; raySampleRevPdf *= data->mRaySampleRevPdf; UPBP_ASSERT(raySamplePdf); UPBP_ASSERT(raySampleRevPdf); // Retrieve light incoming direction in world coordinates. const Dir lightDirection = lightVertex->mBSDF.WorldDirFix(); // BSDF. float cameraBsdfDirPdfW, cameraBsdfRevPdfW, sinTheta; const Rgb cameraBsdfFactor = PhaseFunction::Evaluate(-(*((Dir*)&ray.dir)), lightDirection, ray.medium->MeanCosine(), &cameraBsdfDirPdfW, &cameraBsdfRevPdfW, &sinTheta); if (cameraBsdfFactor.isBlackOrNegative()) return; cameraBsdfDirPdfW *= ray.medium->ContinuationProb(); UPBP_ASSERT(cameraBsdfDirPdfW > 0); // Even though this is PDF from camera BSDF, the continuation probability // must come from light BSDF, because that would govern it if light path // actually continued. cameraBsdfRevPdfW *= lightVertex->mBSDF.ContinuationProb(); UPBP_ASSERT(cameraBsdfRevPdfW > 0); // Epanechnikov kernel. const float kernel = (1 - isectRadSqr / thisPhoton->radiusSqr) / (thisPhoton->radiusSqr * PI_F * 0.5f); if (!Float::isPositive(kernel)) return; // Scattering coefficient. const Rgb& scatteringCoeff = ray.medium->IsHomogeneous() ? ((const HomogeneousMedium *)ray.medium)->GetScatteringCoef() : ray.medium->GetScatteringCoef(isectPt); // Unweighted result. const Rgb unweightedResult = lightVertex->mThroughput * attenuation * scatteringCoeff * cameraBsdfFactor * kernel; if (unweightedResult.isBlackOrNegative()) return; // Update affected MIS data. const float distSq = Utils::sqr(photonIsectDist); const float raySamplePdfInv = 1.0f / raySamplePdf; MisData* cameraVerticesMisData = static_cast<MisData*>(data->mCameraVerticesMisData); cameraVerticesMisData[data->mCameraPathLength].mPdfAInv = data->mLastPdfWInv * distSq * raySamplePdfInv; //cameraVerticesMisData[data->mCameraPathLength].mRevPdfA = 1.0f; // not used (sent through AccumulateCameraPathWeight params) cameraVerticesMisData[data->mCameraPathLength].mRaySamplePdfInv = raySamplePdfInv; //cameraVerticesMisData[data->mCameraPathLength].mRaySampleRevPdfInv = lightVertex->mMisData.mRaySamplePdfInv; // not used (sent through AccumulateCameraPathWeight params) cameraVerticesMisData[data->mCameraPathLength].mRaySamplePdfsRatio = raySamplePdfsRatio; //cameraVerticesMisData[data->mCameraPathLength].mRaySampleRevPdfsRatio = lightVertex->mMisData.mRaySamplePdfsRatio; // not used (sent through AccumulateCameraPathWeight params) //cameraVerticesMisData[data->mCameraPathLength].mSinTheta = sinTheta; // not used (sent through AccumulateCameraPathWeight params) cameraVerticesMisData[data->mCameraPathLength].mSurfMisWeightFactor = 0; cameraVerticesMisData[data->mCameraPathLength].mPP3DMisWeightFactor = data->mPP3DMisWeightFactor; cameraVerticesMisData[data->mCameraPathLength].mPB2DMisWeightFactor = data->mPB2DMisWeightFactor; //data->mLightSubPathCount / kernel; cameraVerticesMisData[data->mCameraPathLength].mBB1DMisWeightFactor = data->mBB1DMisWeightFactor; if (!data->mBB1DPhotonBeams) cameraVerticesMisData[data->mCameraPathLength].mBB1DBeamSelectionPdf = 0.0f; else { PhotonBeamsEvaluator* pbe = static_cast<PhotonBeamsEvaluator*>(data->mBB1DPhotonBeams); if (pbe->sMaxBeamsInCell) cameraVerticesMisData[data->mCameraPathLength].mBB1DBeamSelectionPdf = pbe->getBeamSelectionPdf(isectPt); else cameraVerticesMisData[data->mCameraPathLength].mBB1DBeamSelectionPdf = 1.0f; } cameraVerticesMisData[data->mCameraPathLength].mIsDelta = false; cameraVerticesMisData[data->mCameraPathLength].mIsOnLightSource = false; cameraVerticesMisData[data->mCameraPathLength].mIsSpecular = false; cameraVerticesMisData[data->mCameraPathLength].mInMediumWithBeams = ray.medium->GetMeanFreePath(isectPt) > data->mBB1DMinMFP; // Update reverse PDFs of the previous vertex. cameraVerticesMisData[data->mCameraPathLength - 1].mRaySampleRevPdfInv = 1.0f / raySampleRevPdf; // Compute MIS weight. const float last = (ray.flags & SHORT_BEAM) ? 1.0 / (raySamplePdfsRatio * cameraVerticesMisData[data->mCameraPathLength].mPB2DMisWeightFactor) : raySamplePdf / cameraVerticesMisData[data->mCameraPathLength].mPB2DMisWeightFactor; const float wCamera = AccumulateCameraPathWeight( data->mCameraPathLength, last, sinTheta, lightVertex->mMisData.mRaySamplePdfInv, lightVertex->mMisData.mRaySamplePdfsRatio, cameraBsdfRevPdfW * raySampleRevPdf / distSq, data->mQueryBeamType, data->mPhotonBeamType, ray.flags, cameraVerticesMisData); const float wLight = AccumulateLightPathWeight( lightVertex->mPathIdx, lightVertex->mPathLength, last, 0, 0, 0, cameraBsdfDirPdfW, PB2D, data->mQueryBeamType, data->mPhotonBeamType, ray.flags, false, static_cast<std::vector<int>*>(data->mPathEnds), static_cast<std::vector<UPBPLightVertex>*>(data->mLightVertices)); const float misWeight = 1.f / (wLight + wCamera); // Weight and accumulate contribution. *static_cast<Rgb*>(ray.accumResult) += misWeight * unweightedResult; DebugImages & debugImages = *static_cast<DebugImages *>(data->mDebugImages); debugImages.accumRgb2Weight(lightVertex->mPathLength, DebugImages::PB2D, unweightedResult, misWeight); } } /** * @brief BRE intersection function for a photon - should never be called. * * @param This This. * @param [in,out] ray The ray. * * @return Never returns. */ static bool breOccludedFunc(const embree::Intersector1* This, embree::Ray& ray) { std::cerr << "Error: breOccludedFunc() called - makes not sense" << std::endl; exit(2); } }; // ---------------------------------------------------------------------------------------------- /** * @brief Build a structure of 'virtual' objects - i.e. photon spheres. * * @param [in,out] photons The photons. * @param numPhotons Number of photons. * * @return The structure of photon spheres. */ static embree::RTCGeometry* buildPhotonTree(EmbreePhoton *photons, int numPhotons) { embree::RTCGeometry* embreeGeo = embree::rtcNewVirtualGeometry(numPhotons, "default"); for(int i = 0; i < numPhotons; ++i) { BoundingBox3 bbox = photons[i].getBbox(); embree::rtcSetVirtualGeometryUserData(embreeGeo, i, i, 0); embree::rtcSetVirtualGeometryBounds(embreeGeo, i, &bbox.point1.x(), &bbox.point2.x()); embree::rtcSetVirtualGeometryIntersector1 (embreeGeo, i, &photons[i]); } embree::rtcBuildAccel(embreeGeo, "default"); embree::rtcCleanupGeometry(embreeGeo); return embreeGeo; } // ---------------------------------------------------------------------------------------------- /** * @brief Build the data structure for BRE queries. * * Version used by pure PB2D algorithm from \c VolLightTracer.hxx. * * @param lightSubPathVertices Light sub path vertices. * @param numVertices Number of vertices. * @param radiusCalculation Type of radius calculation. * @param photonRadius Photon radius. * @param knn Value x means that x-th closest photon will be used for * calculation of radius of the current photon. * @param verbose Whether to print information about progress. * * @return Number of photons made from the given light sub path vertices. */ int EmbreeBre::build(const VltLightVertex* lightSubPathVertices, const int numVertices, RadiusCalculation radiusCalculation, const float photonRadius, const int knn, bool verbose) { UPBP_ASSERT( embreePhotons == nullptr ); UPBP_ASSERT( numEmbreePhotons == 0 ); UPBP_ASSERT( embreeGeo == nullptr ); UPBP_ASSERT( embreeIntersector == nullptr ); UPBP_ASSERT( lightSubPathVertices != nullptr ); UPBP_ASSERT( numVertices > 0 ); UPBP_ASSERT(radiusCalculation == CONSTANT_RADIUS || knn > 0); // Count number of vertices in medium. int numVerticesInMedium = 0; for ( int i=0; i<numVertices; i++ ) { if( lightSubPathVertices[i].mIsInMedium ) numVerticesInMedium ++; } // Nothing to do. if( numVerticesInMedium <= 0 ) return numVerticesInMedium; if(verbose) std::cout << " + BRE data struct construction over " << numVerticesInMedium << " photons..." << std::endl; Timer timer; timer.Start(); // Allocate embree photons. embreePhotons = new EmbreePhoton[numVerticesInMedium]; numEmbreePhotons = numVerticesInMedium; UPBP_ASSERT( embreePhotons != nullptr ); KdTree * tree; KdTree::CKNNQuery * query; if (radiusCalculation == KNN_RADIUS) { tree = new KdTree(); tree->Reserve(numVerticesInMedium); for (int i = 0; i < numVertices; i++) { if (lightSubPathVertices[i].mIsInMedium) { tree->AddItem((Pos *)(&lightSubPathVertices[i].mHitpoint), i); } } tree->BuildUp(); query = new KdTree::CKNNQuery(knn); } // Convert path vertices to embree photons. int inMediumIdx = 0; for(int i=0; i<numVertices; i++) { if( lightSubPathVertices[i].mIsInMedium ) { const VltLightVertex& v = lightSubPathVertices[i]; float radius = photonRadius; if (radiusCalculation == KNN_RADIUS) { query->Init(v.mHitpoint, knn, MAX_FLOAT_SQUARE_ROOT); // Execute query. tree->KNNQuery(*query, tree->truePred); UPBP_ASSERT(query->found > 1); radius *= 2.0f * sqrtf(query->dist2[1]); } embreePhotons[inMediumIdx].set( v.mHitpoint, radius, v.mBSDF.WorldDirFix(), v.mThroughput ); inMediumIdx++; } } if (radiusCalculation == KNN_RADIUS) { delete query; delete tree; } UPBP_ASSERT( inMediumIdx == numVerticesInMedium ); timer.Stop(); const double dataCopnversionTime = timer.GetLastElapsedTime(); timer.Start(); // Build embree data structure. embreeGeo = buildPhotonTree( embreePhotons, numVerticesInMedium ); UPBP_ASSERT( embreeGeo != nullptr ); // Retrieve the intersectable interface for this data structure. embreeIntersector = embree::rtcQueryIntersector1 ( embreeGeo, "default" ); UPBP_ASSERT( embreeIntersector != nullptr ); timer.Stop(); const double treeConstructionTime = timer.GetLastElapsedTime(); if(verbose) { std::cout << std::setprecision(3) << " - BRE struct took " << dataCopnversionTime+treeConstructionTime << " sec.\n" << " data conversion: " << dataCopnversionTime << " sec.\n" << " tree construction: " << treeConstructionTime << " sec." << std::endl; } return numVerticesInMedium; } /** * @brief Build the data structure for BRE queries. * * Version used by combined PB2D algorithms from \c UPBP.hxx. * * @param lightSubPathVertices Light sub path vertices. * @param numVertices Number of vertices. * @param radiusCalculation Type of radius calculation. * @param photonRadius Photon radius. * @param knn Value x means that x-th closest photon will be used for * calculation of radius of the current photon. * @param verbose Whether to print information about progress. * * @return Number of photons made from the given light sub path vertices. */ int EmbreeBre::build(const UPBPLightVertex* lightSubPathVertices, const int numVertices, RadiusCalculation radiusCalculation, const float photonRadius, const int knn, bool verbose) { UPBP_ASSERT(embreePhotons == nullptr); UPBP_ASSERT(numEmbreePhotons == 0); UPBP_ASSERT(embreeGeo == nullptr); UPBP_ASSERT(embreeIntersector == nullptr); UPBP_ASSERT(lightSubPathVertices != nullptr); UPBP_ASSERT(numVertices > 0); UPBP_ASSERT(radiusCalculation == CONSTANT_RADIUS || knn > 0); // Count number of vertices in medium. int numVerticesInMedium = 0; for (int i = 0; i<numVertices; i++) { if (lightSubPathVertices[i].mInMedium) numVerticesInMedium++; } // Nothing to do. if (numVerticesInMedium <= 0) return numVerticesInMedium; if (verbose) std::cout << " + BRE data struct construction over " << numVerticesInMedium << " photons..." << std::endl; Timer timer; timer.Start(); // Allocate embree photons. embreePhotons = new EmbreePhoton[numVerticesInMedium]; numEmbreePhotons = numVerticesInMedium; UPBP_ASSERT(embreePhotons != nullptr); KdTree * tree; KdTree::CKNNQuery * query; if (radiusCalculation == KNN_RADIUS) { tree = new KdTree(); tree->Reserve(numVerticesInMedium); for (int i = 0; i < numVertices; i++) { if (lightSubPathVertices[i].mInMedium) { tree->AddItem((Pos *)(&lightSubPathVertices[i].mHitpoint), i); } } tree->BuildUp(); query = new KdTree::CKNNQuery(knn); } // Convert path vertices to embree photons. int inMediumIdx = 0; for (int i = 0; i<numVertices; i++) { if (lightSubPathVertices[i].mInMedium) { const UPBPLightVertex& v = lightSubPathVertices[i]; float radius = photonRadius; if (radiusCalculation == KNN_RADIUS) { query->Init(v.mHitpoint, knn, MAX_FLOAT_SQUARE_ROOT); // Execute query. tree->KNNQuery(*query, tree->truePred); UPBP_ASSERT(query->found > 1); radius *= 2.0f * sqrtf(query->dist2[1]); } embreePhotons[inMediumIdx].set(radius, &v); inMediumIdx++; } } if (radiusCalculation == KNN_RADIUS) { delete query; delete tree; } UPBP_ASSERT(inMediumIdx == numVerticesInMedium); timer.Stop(); const double dataCopnversionTime = timer.GetLastElapsedTime(); timer.Start(); // Build embree data structure. embreeGeo = buildPhotonTree(embreePhotons, numVerticesInMedium); UPBP_ASSERT(embreeGeo != nullptr); // Retrieve the intersectable interface for this data structure. embreeIntersector = embree::rtcQueryIntersector1(embreeGeo, "default"); UPBP_ASSERT(embreeIntersector != nullptr); timer.Stop(); const double treeConstructionTime = timer.GetLastElapsedTime(); if (verbose) { std::cout << std::setprecision(3) << " - BRE struct took " << dataCopnversionTime + treeConstructionTime << " sec.\n" << " data conversion: " << dataCopnversionTime << " sec.\n" << " tree construction: " << treeConstructionTime << " sec." << std::endl; } return numVerticesInMedium; } // ---------------------------------------------------------------------------------------------- /** * @brief Destroy the data structure for BRE queries. */ void EmbreeBre::destroy( ) { if( embreePhotons != nullptr ) delete[] embreePhotons; if( embreeGeo != nullptr ) embree::rtcDeleteGeometry(embreeGeo); if( embreeIntersector != nullptr ) rtcDeleteIntersector1 (embreeIntersector); embreePhotons = nullptr; numEmbreePhotons = 0; embreeGeo = nullptr; embreeIntersector = nullptr; } // ---------------------------------------------------------------------------------------------- /** * @brief Destructor. */ EmbreeBre::~EmbreeBre() { // The user should call destroy manually before deleting this object. UPBP_ASSERT( embreePhotons == nullptr ); UPBP_ASSERT( numEmbreePhotons == 0 ); UPBP_ASSERT( embreeGeo == nullptr ); UPBP_ASSERT( embreeIntersector == nullptr ); // Destroy anyway even if the user has forgotten to destroy(). destroy(); } // ---------------------------------------------------------------------------------------------- /** * @brief Evaluates the beam radiance estimate for the given query ray. * * @param beamType Type of the beam. * @param queryRay The query ray (=beam) for the beam radiance estimate. * @param segments Full volume segments of media intersected by the ray. * @param estimatorTechniques the estimator techniques to use. * @param raySamplingFlags the ray sampling flags (\c * AbstractMedium::kOriginInMedium). * @param [in,out] additionalRayDataForMis (Optional) additional data needed for MIS weights * computations. * * @return The accumulated radiance along the ray. */ Rgb EmbreeBre::evalBre( BeamType beamType, const Ray& queryRay, const VolumeSegments& segments, const uint estimatorTechniques, const uint raySamplingFlags, embree::AdditionalRayDataForMis* additionalRayDataForMis) { UPBP_ASSERT(estimatorTechniques & PB2D); UPBP_ASSERT(raySamplingFlags == 0 || raySamplingFlags == AbstractMedium::kOriginInMedium); Rgb result(0); if(embreeIntersector == nullptr) return result; Rgb attenuation(1); float raySamplePdf = 1.0f; float raySampleRevPdf = 1.0f; /// Accumulate for each segment. for (VolumeSegments::const_iterator it = segments.begin(); it != segments.end(); ++it) { // Get segment medium. const AbstractMedium * medium = scene.mMedia[it->mMediumID]; // Accumulate. Rgb segmentResult(0); if (medium->HasScattering()) { if (additionalRayDataForMis) { additionalRayDataForMis->mRaySamplePdf = raySamplePdf; additionalRayDataForMis->mRaySampleRevPdf = raySampleRevPdf; additionalRayDataForMis->mRaySamplingFlags = AbstractMedium::kEndInMedium; if (it == segments.begin()) additionalRayDataForMis->mRaySamplingFlags |= raySamplingFlags; } embree::Ray embreeRay(toEmbreeV3f(queryRay.origin), toEmbreeV3f(queryRay.direction), it->mDistMin, it->mDistMax); embreeRay.setAdditionalData(medium, &segmentResult, beamType | estimatorTechniques, &queryRay, additionalRayDataForMis); embreeIntersector->intersect(embreeRay); } // Add to total result. result += attenuation * segmentResult; if (additionalRayDataForMis) { DebugImages & debugImages = *static_cast<DebugImages *>(additionalRayDataForMis->mDebugImages); debugImages.accumRgb2ToRgb(DebugImages::PB2D, attenuation); debugImages.ResetAccum2(); } // Update attenuation. attenuation *= beamType == SHORT_BEAM ? it->mAttenuation / it->mRaySamplePdf : // Short beams - no attenuation it->mAttenuation; if (!attenuation.isPositive()) return result; // Update PDFs. raySamplePdf *= it->mRaySamplePdf; raySampleRevPdf *= it->mRaySampleRevPdf; } UPBP_ASSERT(!result.isNanInfNeg()); return result; } /** * @brief Evaluates the beam radiance estimate for the given query ray. * * @param beamType Type of the beam. * @param queryRay The query ray (=beam) for the beam radiance estimate. * @param segments Lite volume segments of media intersected by the ray. * @param estimatorTechniques the estimator techniques to use. * @param raySamplingFlags the ray sampling flags (\c * AbstractMedium::kOriginInMedium). * @param [in,out] additionalRayDataForMis (Optional) additional data needed for MIS weights * computations. * * @return The accumulated radiance along the ray. */ Rgb EmbreeBre::evalBre( BeamType beamType, const Ray& queryRay, const LiteVolumeSegments& segments, const uint estimatorTechniques, const uint raySamplingFlags, embree::AdditionalRayDataForMis* additionalRayDataForMis) { UPBP_ASSERT(beamType == LONG_BEAM); UPBP_ASSERT(estimatorTechniques & PB2D); UPBP_ASSERT(raySamplingFlags == 0 || raySamplingFlags == AbstractMedium::kOriginInMedium); Rgb result(0); if (embreeIntersector == nullptr) return result; Rgb attenuation(1); float raySamplePdf = 1.0f; float raySampleRevPdf = 1.0f; /// Accumulate for each segment. for (LiteVolumeSegments::const_iterator it = segments.begin(); it != segments.end(); ++it) { // Get segment medium. const AbstractMedium * medium = scene.mMedia[it->mMediumID]; // Accumulate. Rgb segmentResult(0); if (medium->HasScattering()) { if (additionalRayDataForMis) { additionalRayDataForMis->mRaySamplePdf = raySamplePdf; additionalRayDataForMis->mRaySampleRevPdf = raySampleRevPdf; additionalRayDataForMis->mRaySamplingFlags = AbstractMedium::kEndInMedium; if (it == segments.begin()) additionalRayDataForMis->mRaySamplingFlags |= raySamplingFlags; } embree::Ray embreeRay(toEmbreeV3f(queryRay.origin), toEmbreeV3f(queryRay.direction), it->mDistMin, it->mDistMax); embreeRay.setAdditionalData(medium, &segmentResult, beamType | estimatorTechniques, &queryRay, additionalRayDataForMis); embreeIntersector->intersect(embreeRay); } // Add to total result. result += attenuation * segmentResult; if (additionalRayDataForMis) { DebugImages & debugImages = *static_cast<DebugImages *>(additionalRayDataForMis->mDebugImages); debugImages.accumRgb2ToRgb(DebugImages::PB2D, attenuation); debugImages.ResetAccum2(); } // Update attenuation. attenuation *= medium->EvalAttenuation(queryRay, it->mDistMin, it->mDistMax); if (!attenuation.isPositive()) return result; // Update PDFs. float segmentRaySampleRevPdf; float segmentRaySamplePdf = medium->RaySamplePdf(queryRay, it->mDistMin, it->mDistMax, it == segments.begin() ? raySamplingFlags : 0, &segmentRaySampleRevPdf); raySamplePdf *= segmentRaySamplePdf; raySampleRevPdf *= segmentRaySampleRevPdf; } UPBP_ASSERT(!result.isNanInfNeg()); return result; } // ---------------------------------------------------------------------------------------------- /** * @brief Same as evalBre() except that no acceleration structure is used for the photon * lookups. * * @param beamType Type of the beam. * @param queryRay The query ray (=beam) for the beam radiance estimate. * @param minT Minimum value of the ray t parameter. * @param maxT Maximum value of the ray t parameter. * @param medium Medium the current ray segment is in. * * @return The accumulated radiance along the ray. */ Rgb EmbreeBre::evalBreBruteForce( BeamType beamType, const Ray &queryRay, const float minT, const float maxT, const AbstractMedium* medium) { Rgb result(0); // No photons - return zero. if(embreePhotons == nullptr) return result; Rgb attenuationCoeff, scatteringCoeff; // Make sure we're in a homogeneous medium. const int isHomogeneous = medium->IsHomogeneous(); if( !isHomogeneous ) { std::cerr << "Error: EmbreeBre::evalBreBruteForce() - only homogeneous media are currently supported" << std::endl; exit(2); } if( isHomogeneous ) { attenuationCoeff = medium->GetAttenuationCoef( queryRay.target(minT) ); scatteringCoeff = medium->GetScatteringCoef( queryRay.target(minT) ); } // Convert the query ray to embree format. embree::Ray embreeRay(toEmbreeV3f(queryRay.origin), toEmbreeV3f(queryRay.direction), minT, maxT); // Loop over all photons, test intersections and possibly accumulate radiance contributions. for( int i=0; i<numEmbreePhotons; i++ ) { const EmbreePhoton& photon = embreePhotons[i]; float photonIsectDist, photonIsectRadSqr; if( EmbreePhoton::testIntersectionBre(photonIsectDist, photonIsectRadSqr, queryRay, minT, maxT, photon.pos, photon.radiusSqr) ) { result += photon.flux * Rgb::exp( -photonIsectDist*attenuationCoeff ) * PhaseFunction::Evaluate(queryRay.direction, photon.incDir, medium->MeanCosine() ) / (photon.radiusSqr); } } return result * scatteringCoeff * INV_PI_F; }
34.172012
180
0.695077
[ "object", "vector" ]
cf6a81ea664648af90cfc6754032a8547694cdcf
18,907
cpp
C++
src/bin/manager/silvia_manager.cpp
identificaatcie/silvia
2dc4b8b6e31f084692114a820b3a13a56a43b966
[ "BSD-3-Clause" ]
null
null
null
src/bin/manager/silvia_manager.cpp
identificaatcie/silvia
2dc4b8b6e31f084692114a820b3a13a56a43b966
[ "BSD-3-Clause" ]
null
null
null
src/bin/manager/silvia_manager.cpp
identificaatcie/silvia
2dc4b8b6e31f084692114a820b3a13a56a43b966
[ "BSD-3-Clause" ]
null
null
null
/* $Id$ */ /* * Copyright (c) 2014 Antonio de la Piedra * Copyright (c) 2013 Roland van Rijswijk-Deij * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /***************************************************************************** silvia_manager.cpp Command-line management utility *****************************************************************************/ #include "config.h" #include "silvia_parameters.h" #include "silvia_apdu.h" #ifdef WITH_PCSC #include "silvia_pcsc_card.h" #endif // WITH_PCSC #ifdef WITH_NFC #include "silvia_nfc_card.h" #endif // WITH_NFC #include "silvia_card_channel.h" #include "silvia_irma_xmlreader.h" #include "silvia_irma_manager.h" #include "silvia_idemix_xmlreader.h" #include "silvia_types.h" #include <assert.h> #include <string> #include <iostream> #include <sstream> #include <ctime> #include <unistd.h> #include <stdio.h> #include <time.h> #include <signal.h> static bool debug_output = false; #define DEBUG_MSG(...) { if (debug_output) printf(__VA_ARGS__); } #define MANAGER_OPT_LOG 0x00 #define MANAGER_OPT_CRED 0x01 #define MANAGER_OPT_UPDATE_ADMIN 0x02 #define MANAGER_OPT_DEL_CRED 0x03 #define MANAGER_OPT_UPDATE_CRED 0x04 #define MANAGER_OPT_READ_CRED 0x05 #define IRMA_VERIFIER_METADATA_OFFSET (32 - 6) /* Log entries */ const int IDX_TIMESTAMP = 0; const int SIZE_TIMESTAMP = 4; const int IDX_TERMINAL = 4; const int SIZE_TERMINAL = 4; const int IDX_ACTION = 8; const int IDX_CREDENTIAL = 9; const int IDX_SELECTION = 11; const char ACTION_NONE = '0'; const char ACTION_ISSUE = '1'; const char ACTION_PROVE = '2'; const char ACTION_REMOVE = '3'; void print_timestamp_log(std::string msg, std::string timestamp) { time_t tstamp_int; std::stringstream tstamp_ss; tstamp_ss << std::hex << timestamp.c_str(); tstamp_ss >> tstamp_int; printf("%s: %s\n", msg.c_str(), ctime(&tstamp_int)); } void print_timestamp_irma(std::string msg, bytestring timestamp) { time_t expires; if (timestamp[IRMA_VERIFIER_METADATA_OFFSET] != 0x00) { // Check metadata version number if (timestamp[IRMA_VERIFIER_METADATA_OFFSET] != 0x01) { printf("Invalid metadata attribute found!\n"); } else { // Reconstruct expiry data from metadata expires = 0; expires += timestamp[IRMA_VERIFIER_METADATA_OFFSET + 1] << 16; expires += timestamp[IRMA_VERIFIER_METADATA_OFFSET + 2] << 8; expires += timestamp[IRMA_VERIFIER_METADATA_OFFSET + 3]; expires *= 86400; // convert days to seconds } } else { // This is old style expires = (timestamp[timestamp.size() - 2] << 8) + (timestamp[timestamp.size() - 1]); expires *= 86400; // convert days to seconds } printf("%s: %s\n", msg.c_str(), ctime(&expires)); } /* print_log_entry is based on IdemixLogEntry by Wouter Lueks, Radboud University Nijmegen, March 2013. */ void print_log_entry(int n, std::string e) { std::vector<char> array(e.begin(), e.end()); printf("Entry %d: ", n); char action = array[IDX_ACTION*2 + 1]; switch(action) { case ACTION_PROVE: printf("VERIFICATION\n"); break; case ACTION_ISSUE: printf("ISSUANCE\n"); break; case ACTION_REMOVE: printf("REMOVE\n"); break; case ACTION_NONE: printf("-- EMPTY ENTRY --\n"); break; default: break; } std::string timestamp = e.substr(IDX_TIMESTAMP, SIZE_TIMESTAMP*2); std::string credential = e.substr(IDX_CREDENTIAL*2, 4); std::string mask = e.substr(IDX_SELECTION*2, 4); std::stringstream cred_ss; unsigned int cred_int; cred_ss << std::hex << credential; cred_ss >> cred_int; if (array[IDX_ACTION*2 + 1] == ACTION_PROVE) printf("Policy: %s\n", mask.c_str()); if (array[IDX_ACTION*2 + 1] != ACTION_NONE) { printf("Credential: %d\n", cred_int); print_timestamp_log("Timestamp", timestamp); } } void signal_handler(int signal) { // Exit on any signal we receive and handle fprintf(stderr, "\nCaught signal, exiting...\n"); exit(0); } void version(void) { printf("The Simple Library for Verifying and Issuing Attributes (silvia)\n"); printf("\n"); printf("Command-line issuing utility for IRMA cards %s\n", VERSION); printf("\n"); printf("Copyright (c) 2013 Roland van Rijswijk-Deij\n\n"); printf("Use, modification and redistribution of this software is subject to the terms\n"); printf("of the license agreement. This software is licensed under a 2-clause BSD-style\n"); printf("license a copy of which is included as the file LICENSE in the distribution.\n"); } void usage(void) { printf("Silvia command-line IRMA manager %s\n\n", VERSION); printf("Usage:\n"); printf("\tsilvia_manager [-lracso] [<credential>]"); #if defined(WITH_PCSC) && defined(WITH_NFC) printf(" [-P] [-N]"); #endif // WITH_PCSC && WITH_NFC printf("\n"); printf("\tsilvia_manager -l Read the log of the IRMA card\n"); printf("\tsilvia_manager -r <credential> Remove a credential stored in the card\n"); printf("\tsilvia_manager -a Update admin pin\n"); printf("\tsilvia_manager -c Update credential pin\n"); printf("\tsilvia_manager -s List the credentials stored in the IRMA card\n"); printf("\tsilvia_manager -o <credential> Read all the attributes of <credential>\n"); printf("\n"); #if defined(WITH_PCSC) && defined(WITH_NFC) printf("\t-P Use PC/SC for card communication (default)\n"); printf("\t-N Use NFC for card communication\n"); #endif // WITH_PCSC && WITH_NFC printf("\n"); printf("\t-d Print debug output\n"); printf("\n"); printf("\t-h Print this help message\n"); printf("\n"); printf("\t-v Print the version number\n"); } std::string get_pin(std::string msg) { printf("\n"); printf("=================================================\n"); printf(" PIN VERIFICATION REQUIRED \n"); printf("=================================================\n"); printf("\n"); std::string PIN; do { PIN = getpass(msg.c_str()); if (PIN.size() > 8) { printf("PIN too long; 8 characters or less expected!\n"); } else if (PIN.empty()) { printf("You must enter a PIN!\n"); } } while (PIN.empty() || (PIN.size() > 8)); printf("\n"); return PIN; } bool communicate_with_card(silvia_card_channel* card, std::vector<bytestring>& commands, std::vector<bytestring>& results) { printf("Communicating with the card... "); fflush(stdout); bool comm_ok = true; size_t cmd_ctr = 0; for (std::vector<bytestring>::iterator i = commands.begin(); (i != commands.end()) && comm_ok; i++) { bytestring result; DEBUG_MSG("--> %s\n", i->hex_str().c_str()); if (!card->transmit(*i, result)) { comm_ok = false; break; } DEBUG_MSG("<-- %s\n", result.hex_str().c_str()); cmd_ctr++; if (result.substr(result.size() - 2) == "6B00") { // This is a workaround for the fact that we have no idea how many attributes were in the current credential (we do not read the Issues spec) // With INS_ADMIN_ATTRIBUTE (getting attribute value), this error is returned if we ask more values than are present in this credential // Let's just continue for now, because who knows what we might request more in the future? // Because we bail out before the push_back, we do not store anything, so we don't show anything either. continue; } else if (result.substr(result.size() - 2) != "9000") { // Return values between 63C0--63CF indicate a wrong PIN const unsigned int PIN_attempts = ((result.substr(result.size() - 2) ^ "63C0")[0] << 8) | ((result.substr(result.size() - 2) ^ "63C0")[1]); if (PIN_attempts <= 0xF) { printf("wrong PIN, %u attempts remaining ", PIN_attempts); } else { printf("(0x%s) ", result.substr(result.size() - 2).hex_str().c_str()); } comm_ok = false; break; } results.push_back(result); } if (comm_ok) { printf("OK\n"); } else { printf("FAILED!\n"); } return comm_ok; } bool read_log(silvia_card_channel* card, std::string userPIN) { bool rv = true; std::vector<bytestring> commands; std::vector<bytestring> results; silvia_irma_manager irma_manager; commands = irma_manager.get_log_commands(userPIN); int n_ent = 1; if (communicate_with_card(card, commands, results)) { int i = 2; // The first two results corresponds to SELECT and VERIFY APDUs. for (char start_entry = 0x00; start_entry < irma_manager.LOG_SIZE; start_entry = (char)(start_entry + irma_manager.LOG_ENTRIES_PER_APDU)) { std::string entry = results[i].hex_str(); for (int j = 0; j < irma_manager.LOG_ENTRIES_PER_APDU; j++) { std::string e = entry.substr(j*irma_manager.LOG_ENTRY_SIZE*2, irma_manager.LOG_ENTRY_SIZE*2); print_log_entry(n_ent++, e); } i++; } } else { printf("Failed to communicate with the card, was it removed prematurely?\n"); rv = false; } return rv; } bool get_list_cred(silvia_card_channel* card, std::string userPIN) { bool rv = true; std::vector<bytestring> commands; std::vector<bytestring> results; silvia_irma_manager irma_manager; commands = irma_manager.list_credentials_commands(userPIN); if (communicate_with_card(card, commands, results)) { assert(results.size() == 3); // SELECT + VERIFY + LIST_CREDS std::string creds = results[2].hex_str(); for (int i = 0; i < creds.size() - 4; i = i+4) { std::string cred = creds.substr(i, 4); std::stringstream cred_ss; int cred_int; cred_ss << std::hex << cred; cred_ss >> cred_int; std::stringstream out; out << cred_int; printf("Slot #%d: %s\n", i/4, (cred == "0000") ? "-- EMPTY ENTRY --" : out.str().c_str()); } } else { printf("Failed to communicate with the card, was it removed prematurely?\n"); rv = false; } return rv; } bool update_admin_pin(silvia_card_channel* card, std::string old_pin, std::string new_pin) { bool rv = true; std::vector<bytestring> commands; std::vector<bytestring> results; silvia_irma_manager irma_manager; commands = irma_manager.update_admin_pin_commands(old_pin, new_pin); if (!communicate_with_card(card, commands, results)) { printf("Failed to communicate with the card, was it removed prematurely?\n"); rv = false; } return rv; } bool update_cred_pin(silvia_card_channel* card, std::string admin_pin, std::string new_pin) { bool rv = true; std::vector<bytestring> commands; std::vector<bytestring> results; silvia_irma_manager irma_manager; commands = irma_manager.update_cred_pin_commands(admin_pin, new_pin); if (!communicate_with_card(card, commands, results)) { printf("Failed to communicate with the card, was it removed prematurely?\n"); rv = false; } return rv; } bool delete_credential(silvia_card_channel* card, std::string credential, std::string userPIN) { bool rv = true; std::vector<bytestring> commands; std::vector<bytestring> results; silvia_irma_manager irma_manager; commands = irma_manager.del_cred_commands(credential, userPIN); if (!communicate_with_card(card, commands, results)) { printf("Failed to communicate with the card, was it removed prematurely?\n"); rv = false; } return rv; } bool read_credential(silvia_card_channel* card, std::string cred, std::string userPIN) { bool rv = true; std::vector<bytestring> commands; std::vector<bytestring> results; silvia_irma_manager irma_manager; commands = irma_manager.read_credential_commands(cred, userPIN); if (!communicate_with_card(card, commands, results)) { printf("Failed to communicate with the card, was it removed prematurely?\n"); rv = false; } else { for (int i = 3; i < results.size(); i++) { // Remove 0x9000 std::string attr_hex = results[i].hex_str().substr(0, results[i].hex_str().size() - 4);; // Remove 0's std::string::size_type pos = attr_hex.find_first_not_of('0', 0); if(pos > 0) attr_hex.erase(0, pos); if (i == 3) { print_timestamp_irma("Expiration date", results[i]); } else { std::string attr_ascii; for (int j = 0; j < attr_hex.length(); j += 2) attr_ascii.push_back(strtol(attr_hex.substr(j, 2).c_str(), NULL, 16)); printf("Attribute [%i]: %s\n", (i-3), attr_ascii.c_str()); } } } return rv; } void do_manager(int channel_type, int opt, std::string credential) { silvia_card_channel* card = NULL; printf("Silvia command-line IRMA manager %s\n\n", VERSION); // Wait for card printf("\n********************************************************************************\n"); printf("Waiting for card"); #ifdef WITH_PCSC if (channel_type == SILVIA_CHANNEL_PCSC) { printf(" (PCSC) ..."); fflush(stdout); silvia_pcsc_card* pcsc_card = NULL; if (!silvia_pcsc_card_monitor::i()->wait_for_card(&pcsc_card)) { printf("FAILED, exiting\n"); exit(-1); } card = pcsc_card; } #endif // WITH_PCSC #ifdef WITH_NFC if (channel_type == SILVIA_CHANNEL_NFC) { printf(" (NFC) ..."); fflush(stdout); silvia_nfc_card* nfc_card = NULL; if (!silvia_nfc_card_monitor::i()->wait_for_card(&nfc_card)) { printf("FAILED, exiting\n"); exit(-1); } card = nfc_card; } #endif // WITH_NFC printf("OK\n"); if (opt == MANAGER_OPT_LOG) { // Ask the user to enter their PIN std::string PIN = get_pin("Please enter your administration PIN: "); read_log(card, PIN); printf("OK\n"); } else if (opt == MANAGER_OPT_CRED) { // Ask the user to enter their PIN std::string PIN = get_pin("Please enter your administration PIN: "); get_list_cred(card, PIN); printf("OK\n"); } else if (opt == MANAGER_OPT_UPDATE_ADMIN) { // Ask the user to enter their PIN std::string old_pin = get_pin("Please enter your current administration PIN: "); std::string new_pin = get_pin("Please enter your new administration PIN: "); update_admin_pin(card, old_pin, new_pin); printf("OK\n"); } else if (opt == MANAGER_OPT_UPDATE_CRED) { // Ask the user to enter their PIN std::string admin_pin = get_pin("Please enter your current administration PIN: "); std::string new_pin = get_pin("Please enter your new credential PIN: "); update_cred_pin(card, admin_pin, new_pin); printf("OK\n"); } else if (opt == MANAGER_OPT_DEL_CRED) { // Ask the user to enter their PIN std::string pin = get_pin("Please enter your administration PIN: "); delete_credential(card, credential, pin); printf("OK\n"); } else if (opt == MANAGER_OPT_READ_CRED) { // Ask the user to enter their PIN std::string pin = get_pin("Please enter your administration PIN: "); read_credential(card, credential, pin); printf("OK\n"); } printf("********************************************************************************\n"); delete card; } int main(int argc, char* argv[]) { std::string credential; std::string attribute; int c = 0; int read_cred = 0; int get_log = 0; int get_cred = 0; int update_admin_pin = 0; int update_cred_pin = 0; int del_cred = 0; #if defined(WITH_PCSC) && defined(WITH_NFC) int channel_type = SILVIA_CHANNEL_PCSC; #elif defined(WITH_PCSC) int channel_type = SILVIA_CHANNEL_PCSC; #elif defined(WITH_NFC) int channel_type = SILVIA_CHANNEL_NFC; #endif #if defined(WITH_PCSC) && defined(WITH_NFC) while ((c = getopt(argc, argv, "r:cdaso:lhvPN")) != -1) #else while ((c = getopt(argc, argv, "r:cdaso:lhv")) != -1) #endif { switch (c) { case 'h': usage(); return 0; case 'v': version(); return 0; case 'l': get_log = 1; break; case 's': get_cred = 1; break; case 'a': update_admin_pin = 1; break; case 'c': update_cred_pin = 1; break; case 'o': read_cred = 1; credential = std::string(optarg); break; case 'r': del_cred = 1; credential = std::string(optarg); break; #if defined(WITH_PCSC) && defined(WITH_NFC) case 'P': channel_type = SILVIA_CHANNEL_PCSC; break; case 'N': channel_type = SILVIA_CHANNEL_NFC; break; #endif case 'd': debug_output = true; break; } } #ifdef WITH_NFC if (channel_type == SILVIA_CHANNEL_NFC) { // Handle signals when using NFC; this prevents the NFC reader // from going into an undefined state when the user aborts the // program by pressing Ctrl+C signal(SIGQUIT, signal_handler); signal(SIGTERM, signal_handler); signal(SIGINT, signal_handler); signal(SIGABRT, signal_handler); } #endif if (get_log == 1 && get_cred == 0 && update_admin_pin == 0 && del_cred == 0 && update_cred_pin == 0 && read_cred == 0) do_manager(channel_type, MANAGER_OPT_LOG, ""); else if (get_log == 0 && get_cred == 1 && update_admin_pin == 0 && del_cred == 0 && update_cred_pin == 0 && read_cred == 0) do_manager(channel_type, MANAGER_OPT_CRED, ""); else if (get_log == 0 && get_cred == 0 && update_admin_pin == 1 && del_cred == 0 && update_cred_pin == 0 && read_cred == 0) do_manager(channel_type, MANAGER_OPT_UPDATE_ADMIN, ""); else if (get_log == 0 && get_cred == 0 && update_admin_pin == 0 && del_cred == 1 && update_cred_pin == 0 && read_cred == 0) do_manager(channel_type, MANAGER_OPT_DEL_CRED, credential); else if (get_log == 0 && get_cred == 0 && update_admin_pin == 0 && del_cred == 0 && update_cred_pin == 1 && read_cred == 0) do_manager(channel_type, MANAGER_OPT_UPDATE_CRED, ""); else if (get_log == 0 && get_cred == 0 && update_admin_pin == 0 && del_cred == 0 && update_cred_pin == 0 && read_cred == 1) do_manager(channel_type, MANAGER_OPT_READ_CRED, credential); else { usage(); return 0; } return 0; }
26.554775
153
0.657852
[ "vector" ]
cf788e69cb80c52ebf47ea9efc5e1ca777065973
1,005
hpp
C++
othello_cpp/src/colorprint.hpp
Esgrove/othellogame
f11c52f0e399c9402eafcc2249dc433817ae0e46
[ "MIT" ]
null
null
null
othello_cpp/src/colorprint.hpp
Esgrove/othellogame
f11c52f0e399c9402eafcc2249dc433817ae0e46
[ "MIT" ]
null
null
null
othello_cpp/src/colorprint.hpp
Esgrove/othellogame
f11c52f0e399c9402eafcc2249dc433817ae0e46
[ "MIT" ]
null
null
null
//========================================================== // Colorprint util // Interface for colored printing // Akseli Lukkarila //========================================================== #pragma once #include <fmt/color.h> #include <fmt/ostream.h> #include <iostream> // std::cout #include <string> // std::string template<typename T> std::string get_color(const T& object, fmt::color color) { return fmt::format(fmt::fg(color), "{}", object); } template<typename T> void print_color(const T& object, fmt::color color = fmt::color::white) { fmt::print(fmt::fg(color), object); } template<typename T> void print_bold(const T& object, fmt::color color = fmt::color::white) { fmt::print(fmt::emphasis::bold | fmt::fg(color), object); } template<typename T> void print_error(const T& message, const int& indent = 0) { auto whitespace = std::string(indent, ' '); fmt::print(fmt::fg(fmt::color::red), "{}{} {}", whitespace, get_color("Error:", fmt::color::red), message); }
30.454545
111
0.589055
[ "object" ]
cf80a479b6548b7d92590985032ea28ba6effcc8
2,078
cpp
C++
lib/poplibs_test/Embedding.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
1
2021-02-23T05:58:24.000Z
2021-02-23T05:58:24.000Z
lib/poplibs_test/Embedding.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
lib/poplibs_test/Embedding.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #include "poplibs_test/Embedding.hpp" #include <poputil/exceptions.hpp> namespace poplibs_test { namespace embedding { void multiSlice(const boost::multi_array<double, 2> &embeddingMatrix, const std::vector<unsigned> &indices, boost::multi_array<double, 2> &result) { const auto size = embeddingMatrix.shape()[1]; if (size != result.shape()[1]) { throw poputil::poplibs_error("Inner-most dimension of the result does not " "match the same dim in the embedding matrix"); } if (indices.size() != result.shape()[0]) { throw poputil::poplibs_error("Number of indices does not match the number " "of rows in the output"); } for (unsigned i = 0; i < indices.size(); ++i) { if (indices[i] >= embeddingMatrix.size()) { throw poputil::poplibs_error("Index is out-of-bounds."); } const auto &row = embeddingMatrix[indices[i]]; std::copy_n(std::begin(row), size, result.data() + i * size); } } void multiUpdateAdd(const boost::multi_array<double, 2> &deltas, const std::vector<unsigned> &indices, const double scale, boost::multi_array<double, 2> &embeddingMatrix) { const auto size = deltas.shape()[1]; if (size != embeddingMatrix.shape()[1]) { throw poputil::poplibs_error("Inner-most dimension of the deltas does not " "match the same dim in the embedding matrix"); } if (indices.size() != deltas.shape()[0]) { throw poputil::poplibs_error("Number of indices does not match the number " "of rows in the deltas"); } for (unsigned i = 0; i < indices.size(); ++i) { if (indices[i] >= embeddingMatrix.size()) { throw poputil::poplibs_error("Index is out-of-bounds."); } for (unsigned j = 0; j < size; ++j) { embeddingMatrix[indices[i]][j] += deltas[i][j] * scale; } } } } // namespace embedding } // namespace poplibs_test
34.633333
79
0.604909
[ "shape", "vector" ]
cf8e2dcde3733dd7215dd78e903b25e3838f3906
1,675
cpp
C++
atcoder/abc/abc138/d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
atcoder/abc/abc138/d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
atcoder/abc/abc138/d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using pll = pair<ll, ll>; #define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i) #define all(x) (x).begin(),(x).end() #define m0(x) memset(x,0,sizeof(x)) int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1}; vector<ll> gTmp[200010], g[200010]; ll ans[200010], pls[200010]; int main() { m0(ans); ll n,q; cin>>n>>q; for (int i = 0; i < n-1; i++) { ll a,b; cin>>a>>b; a--; b--; gTmp[a].push_back(b); gTmp[b].push_back(a); } unordered_set<ll> se; se.insert(0); queue<ll> qGraph; qGraph.push(0); while (qGraph.size()>0) { ll now = qGraph.front(); qGraph.pop(); for (int i = 0; i < gTmp[now].size(); i++) { ll next = gTmp[now][i]; if(se.find(next)==se.end()) //mada yattenai { se.insert(next); qGraph.push(next); g[now].push_back(next); } } } for (int i = 0; i < q; i++) { ll p,x; cin>>p>>x; p--; pls[p]+=x; } queue<ll> qCalc; qCalc.push(0); while (qCalc.size()>0) { ll now = qCalc.front(); qCalc.pop(); ans[now]=pls[now]; for (int i = 0; i < g[now].size(); i++) { ll next = g[now][i]; qCalc.push(next); pls[next]+=pls[now]; } } for (int i = 0; i < n; i++) { if(i>0) cout<<" "; cout<<ans[i]; } cout<<endl; return 0; }
19.476744
58
0.421493
[ "vector" ]
cf9c0cc6b32c498d7570b501194faffff8882ddf
60,348
cc
C++
src/socket.cc
ymrdf/socketjs
683cc160f2dd2a2ac638af04ad801e46b6ebeea2
[ "MIT" ]
1
2021-03-01T07:19:26.000Z
2021-03-01T07:19:26.000Z
src/socket.cc
ymrdf/socketjs
683cc160f2dd2a2ac638af04ad801e46b6ebeea2
[ "MIT" ]
null
null
null
src/socket.cc
ymrdf/socketjs
683cc160f2dd2a2ac638af04ad801e46b6ebeea2
[ "MIT" ]
null
null
null
// socket.cc #include "socket.h" namespace node_socket { sockaddr_in value_to_addr(Napi::Value orgv){ Napi::Object addr = orgv.As<Napi::Object>(); int sin_family = addr.Get("sin_family").As<Napi::Number>().Int32Value(); int sin_port = addr.Get("sin_port").As<Napi::Number>().Int32Value(); unsigned int sin_addr = addr.Get("s_addr").As<Napi::Number>().Uint32Value(); struct sockaddr_in sockaddr; memset(&sockaddr, 0, sizeof(sockaddr)); //每个字节都用0填充 sockaddr.sin_family = sin_family; sockaddr.sin_port = htons(sin_port); sockaddr.sin_addr.s_addr = htonl(sin_addr); return sockaddr; } Napi::Object addr_to_value(Napi::Env env, sockaddr_in sockaddr){ Napi::Object result = Napi::Object::New(env); result.Set(Napi::String::New(env, "sin_family"),Napi::Number::New(env, sockaddr.sin_family)); result.Set(Napi::String::New(env, "sin_port"),Napi::Number::New(env, ntohs(sockaddr.sin_port))); result.Set(Napi::String::New(env, "s_addr"),Napi::Number::New(env, ntohl(sockaddr.sin_addr.s_addr))); return result; } void error_handle(Napi::Env env,const char *e){ perror(e); Napi::TypeError::New(env, e).ThrowAsJavaScriptException(); } void judge_fn_result(Napi::Env env, int r, const char *e){ #ifdef SOCKET_OS_WIN if(r == SOCKET_ERROR){ error_handle(env, e); } #else if(r < 0){ error_handle(env, e); } #endif } class AcceptAsyncWorker : public Napi::AsyncWorker { public: AcceptAsyncWorker(Napi::Function& callback, int n) : AsyncWorker(callback), n_(n) {} void Execute() override { // 定义sockaddr_in struct sockaddr_in client_addr; socklen_t length = sizeof(client_addr); int res = accept(n_,(struct sockaddr *)&client_addr, &length); judge_fn_result(Env(), res, "bind error"); result = res; client_addr_r = client_addr; } void OnOK() override { Napi::Object res = Napi::Object::New(Env()); res.Set(Napi::String::New(Env(), "fd"), Napi::Number::New(Env(), result)); res.Set(Napi::String::New(Env(), "addr"), addr_to_value(Env(), client_addr_r )); Callback().Call({Env().Null(), res}); } private: int n_; unsigned long long result; struct sockaddr_in client_addr_r; }; class RecvAsyncWorker : public Napi::AsyncWorker { public: RecvAsyncWorker(Napi::Function& callback, int n, char* buffer, int buflen, int flag) : AsyncWorker(callback) { n_ = n; buffer_ = buffer; buflen_ = buflen; flag_ = flag; } void Execute() override { long res = recv(n_, buffer_, buflen_, flag_); result = res; } void OnOK() override { Callback().Call({Env().Null(), Napi::Number::New(Env(), result)}); } private: int n_; char * buffer_; int buflen_; int flag_; unsigned long long result; }; class RecvfromAsyncWorker : public Napi::AsyncWorker { public: RecvfromAsyncWorker(Napi::Function& callback, int n, char* buffer, int buflen, int flag) : AsyncWorker(callback) { n_ = n; buffer_ = buffer; buflen_ = buflen; flag_ = flag; } void Execute() override { struct sockaddr_in from_addr; socklen_t length = sizeof(from_addr); long len = recvfrom(n_, buffer_, buflen_, flag_, (struct sockaddr *)&from_addr, &length); from_addr_ = from_addr; len_ = len; } void OnOK() override { Napi::Object res = Napi::Object::New(Env()); res.Set(Napi::String::New(Env(), "length"), Napi::Number::New(Env(), len_)); res.Set(Napi::String::New(Env(), "fromAddr"), addr_to_value(Env(), from_addr_ )); Callback().Call({Env().Null(), res}); } private: int n_; int buflen_; int flag_; struct sockaddr_in from_addr_; unsigned long long len_; char *buffer_; }; Napi::Value Socket(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 3) { Napi::TypeError::New(env, "Wrong number of arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsNumber() || !args[2].IsNumber()) { Napi::TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); return env.Null(); } int domain = args[0].As<Napi::Number>().Int32Value(); int type = args[1].As<Napi::Number>().Int32Value(); int protocol = args[2].As<Napi::Number>().Int32Value(); int fd = socket(domain, type, protocol); if(fd < 0) { perror("socket error"); Napi::TypeError::New(env, "socket error").ThrowAsJavaScriptException(); return env.Null(); } return Napi::Number::New(env, fd); } Napi::Value Bind(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 2) { Napi::TypeError::New(env, "Expected two arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsObject()) { Napi::TypeError::New(env, "Supplied arguments should be: integer, object") .ThrowAsJavaScriptException(); return env.Null(); } struct sockaddr_in server_sockaddr = value_to_addr(args[1]); int id = args[0].As<Napi::Number>().Int32Value(); int result = bind(id,(struct sockaddr *)&server_sockaddr,sizeof(server_sockaddr)); judge_fn_result(env, result, "bind error"); return Napi::Number::New(env, result); } Napi::Value Listen(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 2) { Napi::TypeError::New(env, "Expected two arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsNumber() ) { Napi::TypeError::New(env, "Supplied arguments should be: integer, integer").ThrowAsJavaScriptException(); return env.Null(); } int fd = args[0].As<Napi::Number>().Int32Value(); int backlog = args[1].As<Napi::Number>().Int32Value(); int result = listen(fd, backlog); judge_fn_result(env, result, "listen error"); return Napi::Number::New(env, result); } Napi::Value Accept(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 1) { Napi::TypeError::New(env, "Expected just one arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber()) { Napi::TypeError::New(env, "Supplied arguments should be: integer") .ThrowAsJavaScriptException(); return env.Null(); } struct sockaddr_in client_addr; if(args.Length() > 1){ client_addr = value_to_addr(args[1]); } int id = args[0].As<Napi::Number>().Int32Value(); socklen_t length = sizeof(client_addr); int result = accept(id,(struct sockaddr *)&client_addr, &length); judge_fn_result(env, result, "bind error"); Napi::Object res = Napi::Object::New(env); res.Set(Napi::String::New(env, "fd"), Napi::Number::New(env, result)); res.Set(Napi::String::New(env, "addr"), addr_to_value(env, client_addr )); return res; } Napi::Value Recv(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 4) { Napi::TypeError::New(env, "Expected four arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsArrayBuffer() || !args[2].IsNumber() || !args[3].IsNumber() ) { Napi::TypeError::New(env, "Supplied arguments should be: integer, uint8array, integer, integer") .ThrowAsJavaScriptException(); return env.Null(); } int fd = args[0].As<Napi::Number>().Int32Value(); int buflen = args[2].As<Napi::Number>().Int32Value(); int flag = args[3].As<Napi::Number>().Int32Value(); Napi::ArrayBuffer buf = args[1].As<Napi::ArrayBuffer>(); char* buffer = reinterpret_cast<char*>(buf.Data()); long len = recv(fd, buffer, buflen, flag); return Napi::Number::New(env, len); } Napi::Value AsyncAccept(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 2) { Napi::TypeError::New(env, "Expected two arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsFunction()) { Napi::TypeError::New(env, "Arguments wrong") .ThrowAsJavaScriptException(); return env.Null(); } Napi::Function cb = args[1].As<Napi::Function>(); int id = args[0].As<Napi::Number>().Int32Value(); AcceptAsyncWorker* worker = new AcceptAsyncWorker(cb, id); worker->Queue(); return Napi::String::New(env, "start calc fibonacci"); } Napi::Value AsyncRecv(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 5) { Napi::TypeError::New(env, "Expected four arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsArrayBuffer() || !args[2].IsNumber() || !args[3].IsNumber() || !args[4].IsFunction() ) { Napi::TypeError::New(env, "Supplied arguments should be: integer, array buffer, integer, integer") .ThrowAsJavaScriptException(); return env.Null(); } int fd = args[0].As<Napi::Number>().Int32Value(); int buflen = args[2].As<Napi::Number>().Int32Value(); int flag = args[3].As<Napi::Number>().Int32Value(); Napi::ArrayBuffer buf = args[1].As<Napi::ArrayBuffer>(); char* buffer = reinterpret_cast<char*>(buf.Data()); Napi::Function cb = args[4].As<Napi::Function>(); RecvAsyncWorker* worker = new RecvAsyncWorker(cb, fd, buffer, buflen, flag); worker->Queue(); return Napi::String::New(env, "start calc fibonacci"); } Napi::Value Recvfrom(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 4) { Napi::TypeError::New(env, "Expected four arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsArrayBuffer() || !args[2].IsNumber() || !args[3].IsNumber() ) { Napi::TypeError::New(env, "Supplied arguments should be: integer, ArrayBuffer, integer, integer, address object") .ThrowAsJavaScriptException(); return env.Null(); } int fd = args[0].As<Napi::Number>().Int32Value(); int buflen = args[2].As<Napi::Number>().Int32Value(); int flag = args[3].As<Napi::Number>().Int32Value(); Napi::ArrayBuffer buf = args[1].As<Napi::ArrayBuffer>(); char* buffer = reinterpret_cast<char*>(buf.Data()); struct sockaddr_in from_addr; socklen_t length = sizeof(from_addr); long len = recvfrom(fd, buffer, buflen, flag, (struct sockaddr *)&from_addr, &length); Napi::Object res = Napi::Object::New(env); res.Set(Napi::String::New(env, "length"), Napi::Number::New(env, len)); res.Set(Napi::String::New(env, "buffer"), buf); res.Set(Napi::String::New(env, "fromAddr"), addr_to_value(env, from_addr )); return res; } Napi::Value AsyncRecvfrom(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 5) { Napi::TypeError::New(env, "Expected three arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsArrayBuffer() || !args[2].IsNumber() || !args[3].IsNumber() || !args[4].IsFunction()) { Napi::TypeError::New(env, "Supplied arguments should be: integer, integer, integer") .ThrowAsJavaScriptException(); return env.Null(); } int fd = args[0].As<Napi::Number>().Int32Value(); int buflen = args[2].As<Napi::Number>().Int32Value(); int flag = args[3].As<Napi::Number>().Int32Value(); Napi::ArrayBuffer buf = args[1].As<Napi::ArrayBuffer>(); char* buffer = reinterpret_cast<char*>(buf.Data()); Napi::Function cb = args[4].As<Napi::Function>(); RecvfromAsyncWorker* worker = new RecvfromAsyncWorker(cb, fd, buffer, buflen, flag); worker->Queue(); return Napi::Number::New(env, 1); } Napi::Value Sendto(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 5) { Napi::TypeError::New(env, "Expected five arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsArrayBuffer() || !args[2].IsNumber() || !args[3].IsNumber() || !args[4].IsObject() ) { Napi::TypeError::New(env, "Supplied arguments should be: integer, uint8array, integer, integer, address object") .ThrowAsJavaScriptException(); return env.Null(); } int fd = args[0].As<Napi::Number>().Int32Value(); int buflen = args[2].As<Napi::Number>().Int32Value(); int flag = args[3].As<Napi::Number>().Int32Value(); Napi::ArrayBuffer buf = args[1].As<Napi::ArrayBuffer>(); char* buffer = reinterpret_cast<char*>(buf.Data()); // 定义sockaddr_in struct sockaddr_in socket_addr = value_to_addr(args[4]); int len = sendto(fd, buffer, buflen, flag, (struct sockaddr *)&socket_addr, sizeof(socket_addr)); judge_fn_result(env, len, "sendto error"); return Napi::Number::New(env, len); } Napi::Value Send(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 4) { Napi::TypeError::New(env, "Expected four arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsArrayBuffer() || !args[2].IsNumber() || !args[3].IsNumber() ) { Napi::TypeError::New(env, "Supplied arguments should be: integer, uint8array, integer, integer") .ThrowAsJavaScriptException(); return env.Null(); } int fd = args[0].As<Napi::Number>().Int32Value(); int buflen = args[2].As<Napi::Number>().Int32Value(); int flag = args[3].As<Napi::Number>().Int32Value(); Napi::ArrayBuffer buf = args[1].As<Napi::ArrayBuffer>(); char* buffer = reinterpret_cast<char*>(buf.Data()); fwrite(buffer, buflen, 1, stdout); int result = send(fd, buffer, buflen, flag); judge_fn_result(env, result, "send error"); return Napi::Number::New(env, result); } Napi::Value Connect(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 2) { Napi::TypeError::New(env, "Expected two arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsObject()) { Napi::TypeError::New(env, "Supplied arguments should be: integer, address object") .ThrowAsJavaScriptException(); return env.Null(); } sockaddr_in server_sockaddr = value_to_addr(args[1]); int id = args[0].As<Napi::Number>().Int32Value(); int result = connect(id,(struct sockaddr *)&server_sockaddr,sizeof(server_sockaddr)); judge_fn_result(env, result, "connect error"); return Napi::Number::New(env, result); } Napi::Value Close(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 1) { Napi::TypeError::New(env, "Expected just one argument") .ThrowAsJavaScriptException(); return env.Null(); } // 检查参数的类型。 if (!args[0].IsNumber()) { Napi::TypeError::New(env, "Supplied argument should be: integer ").ThrowAsJavaScriptException(); return env.Null(); } int fd = args[0].As<Napi::Number>().Int32Value(); int result = SOCKETCLOSE(fd); judge_fn_result(env, result, "close error"); return Napi::Number::New(env, result); } Napi::Value Shutdown(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 2) { Napi::TypeError::New(env, "Expected just two argument") .ThrowAsJavaScriptException(); return env.Null(); } // 检查参数的类型。 if (!args[0].IsNumber() || !args[1].IsNumber()) { Napi::TypeError::New(env, "Supplied argument should be: integer, integer ").ThrowAsJavaScriptException(); return env.Null(); } int fd = args[0].As<Napi::Number>().Int32Value(); int type = args[1].As<Napi::Number>().Int32Value(); int result = shutdown(fd, type); judge_fn_result(env, result, "shutdown error"); return Napi::Number::New(env, result); } Napi::Value Setsockopt(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 3) { Napi::TypeError::New(env, "Expected tree arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsNumber() || (!args[2].IsNumber() && !args[2].IsArrayBuffer()) ) { Napi::TypeError::New(env, "Supplied arguments should be: integer, integer, integer/buffer") .ThrowAsJavaScriptException(); return env.Null(); } int fd = args[0].As<Napi::Number>().Int32Value(); int level = args[1].As<Napi::Number>().Int32Value(); int optname = args[2].As<Napi::Number>().Int32Value(); int result = -1; if(args[3].IsNumber()){ int optval = args[3].As<Napi::Number>().Int32Value(); result = setsockopt(fd, level, optname, (char *)& optval, sizeof(optval)); }else{ Napi::ArrayBuffer buf = args[3].As<Napi::ArrayBuffer>(); char* buffer = reinterpret_cast<char*>(buf.Data()); result = setsockopt(fd, level, optname, buffer, sizeof(buffer)); } judge_fn_result(env, result, "setsockopt error"); return Napi::Number::New(env, result); } Napi::Value Getsockopt(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 4) { Napi::TypeError::New(env, "Expected tree arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsNumber() || !args[2].IsNumber() || !args[3].IsNumber() ) { Napi::TypeError::New(env, "Supplied arguments should be: integer, integer, integer, integer") .ThrowAsJavaScriptException(); return env.Null(); } int fd = args[0].As<Napi::Number>().Int32Value(); int level = args[1].As<Napi::Number>().Int32Value(); int optname = args[2].As<Napi::Number>().Int32Value(); int len = args[3].As<Napi::Number>().Int32Value(); socklen_t default_len = 0; socklen_t * optLen = &default_len; Napi::ArrayBuffer buf; if(len == 0){ buf = Napi::ArrayBuffer::New(env, 1); }else{ buf = Napi::ArrayBuffer::New(env, len); } char* buffer = reinterpret_cast<char*>(buf.Data()); int result = getsockopt(fd, level, optname, (char *)& buffer, optLen); judge_fn_result(env, result, "getsockopt error"); Napi::Object res = Napi::Object::New(env); res.Set(Napi::String::New(env, "result"), Napi::Number::New(env, result)); res.Set(Napi::String::New(env, "buffer"), buf); res.Set(Napi::String::New(env, "bufferLen"), Napi::Number::New(env, * optLen) ); return res; } Napi::Value Getsockname(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 1) { Napi::TypeError::New(env, "Expected one arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() ) { Napi::TypeError::New(env, "Supplied arguments should be: integer") .ThrowAsJavaScriptException(); return env.Null(); } struct sockaddr_in local_sockaddr; socklen_t len = sizeof(local_sockaddr); int id = args[0].As<Napi::Number>().Int32Value(); int result = getsockname(id,(struct sockaddr *)&local_sockaddr, &len); Napi::Object res = Napi::Object::New(env); res.Set(Napi::String::New(env, "result"), Napi::Number::New(env, result)); res.Set(Napi::String::New(env, "addr"), addr_to_value(env, local_sockaddr )); return res; } Napi::Value Getpeername(const Napi::CallbackInfo& args) { Napi::Env env = args.Env(); if (args.Length() < 1) { Napi::TypeError::New(env, "Expected one arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber()) { Napi::TypeError::New(env, "Supplied arguments should be: integer") .ThrowAsJavaScriptException(); return env.Null(); } struct sockaddr_in server_sockaddr; socklen_t len = sizeof(server_sockaddr); int id = args[0].As<Napi::Number>().Int32Value(); int result = getpeername(id,(struct sockaddr *)&server_sockaddr, &len); Napi::Object res = Napi::Object::New(env); res.Set(Napi::String::New(env, "result"), Napi::Number::New(env, result)); res.Set(Napi::String::New(env, "addr"), addr_to_value(env, server_sockaddr )); return res; } Napi::Value Ioctl(const Napi::CallbackInfo& args) { #ifdef SOCKET_OS_WIN Napi::Env env = args.Env(); if (args.Length() < 3) { Napi::TypeError::New(env, "Expected two arguments") .ThrowAsJavaScriptException(); return env.Null(); } if (!args[0].IsNumber() || !args[1].IsNumber()) { Napi::TypeError::New(env, "Supplied arguments should be: integer, interger") .ThrowAsJavaScriptException(); return env.Null(); } int id = args[0].As<Napi::Number>().Int32Value(); int cmd = args[1].As<Napi::Number>().Int32Value(); int option = args[2].As<Napi::Number>().Int32Value(); DWORD recv; switch (cmd) { case SIO_RCVALL: { WSAIoctl(id, cmd, &option, sizeof(option), NULL, 0, &recv, NULL, NULL); return Napi::Number::New(env, recv); } default: return env.Null(); } #else Napi::Env env = args.Env(); return env.Null(); #endif } #ifdef SOCKET_OS_WIN #define OS_INIT_DEFINED /* Additional initialization and cleanup for Windows */ static void os_cleanup(void) { WSACleanup(); } static int os_init(void) { WSADATA WSAData; int ret; ret = WSAStartup(0x0101, &WSAData); switch (ret) { case 0: /* No error */ // Py_AtExit(os_cleanup); return 1; /* Success */ case WSASYSNOTREADY: perror("WSAStartup failed: network not ready"); break; case WSAVERNOTSUPPORTED: case WSAEINVAL: perror("WSAStartup failed: requested version not supported"); break; default: perror("WSAStartup failed: error code %d"); break; } return 0; /* Failure */ } #endif /* MS_WINDOWS */ #ifndef OS_INIT_DEFINED static int os_init(void) { return 1; /* Success */ } #endif Napi::Object Init(Napi::Env env, Napi::Object exports) { os_init(); exports.Set(Napi::String::New(env, "_socket"), Napi::Function::New(env, Socket)); exports.Set(Napi::String::New(env, "_bind"), Napi::Function::New(env, Bind)); exports.Set(Napi::String::New(env, "_close"), Napi::Function::New(env, Close)); exports.Set(Napi::String::New(env, "_shutdown"), Napi::Function::New(env, Shutdown)); exports.Set(Napi::String::New(env, "_listen"), Napi::Function::New(env, Listen)); exports.Set(Napi::String::New(env, "_accept"), Napi::Function::New(env, Accept)); exports.Set(Napi::String::New(env, "_asyncAccept"), Napi::Function::New(env, AsyncAccept)); exports.Set(Napi::String::New(env, "_recv"), Napi::Function::New(env, Recv)); exports.Set(Napi::String::New(env, "_asyncRecvfrom"), Napi::Function::New(env, AsyncRecvfrom)); exports.Set(Napi::String::New(env, "_recvfrom"), Napi::Function::New(env, Recvfrom)); exports.Set(Napi::String::New(env, "_sendto"), Napi::Function::New(env, Sendto)); exports.Set(Napi::String::New(env, "_send"), Napi::Function::New(env, Send)); exports.Set(Napi::String::New(env, "_connect"), Napi::Function::New(env, Connect)); exports.Set(Napi::String::New(env, "_asyncRecv"), Napi::Function::New(env, AsyncRecv)); exports.Set(Napi::String::New(env, "_getsockname"), Napi::Function::New(env, Getsockname)); exports.Set(Napi::String::New(env, "_getpeername"), Napi::Function::New(env, Getpeername)); exports.Set(Napi::String::New(env, "_setsockopt"), Napi::Function::New(env, Setsockopt)); exports.Set(Napi::String::New(env, "_getsockopt"), Napi::Function::New(env, Getsockopt)); exports.Set(Napi::String::New(env, "_ioctl"), Napi::Function::New(env, Ioctl)); #define NODE_SOCKET_SET_CONSTANT(m,p,v) NODE_SOCKET_SET_CONSTANT_ENV(env, m, p, v); /* Address families (we only support AF_INET and AF_UNIX) */ #ifdef AF_UNSPEC NODE_SOCKET_SET_MACRO(env, exports, AF_UNSPEC); #endif NODE_SOCKET_SET_MACRO(env, exports, AF_INET); #if defined(AF_UNIX) NODE_SOCKET_SET_MACRO(env, exports, AF_UNIX); #endif /* AF_UNIX */ #ifdef AF_AX25 /* Amateur Radio AX.25 */ NODE_SOCKET_SET_MACRO(env, exports, AF_AX25); #endif #ifdef AF_IPX NODE_SOCKET_SET_MACRO(env, exports, AF_IPX); /* Novell IPX */ #endif #ifdef AF_APPLETALK /* Appletalk DDP */ NODE_SOCKET_SET_MACRO(env, exports, AF_APPLETALK); #endif #ifdef AF_NETROM /* Amateur radio NetROM */ NODE_SOCKET_SET_MACRO(env, exports, AF_NETROM); #endif #ifdef AF_BRIDGE /* Multiprotocol bridge */ NODE_SOCKET_SET_MACRO(env, exports, AF_BRIDGE); #endif #ifdef AF_ATMPVC /* ATM PVCs */ NODE_SOCKET_SET_MACRO(env, exports, AF_ATMPVC); #endif #ifdef AF_AAL5 /* Reserved for Werner's ATM */ NODE_SOCKET_SET_MACRO(env, exports, AF_AAL5); #endif #ifdef HAVE_SOCKADDR_ALG NODE_SOCKET_SET_MACRO(env, exports, AF_ALG); /* Linux crypto */ #endif #ifdef AF_X25 /* Reserved for X.25 project */ NODE_SOCKET_SET_MACRO(env, exports, AF_X25); #endif #ifdef AF_INET6 NODE_SOCKET_SET_MACRO(env, exports, AF_INET6); /* IP version 6 */ #endif #ifdef AF_ROSE /* Amateur Radio X.25 PLP */ NODE_SOCKET_SET_MACRO(env, exports, AF_ROSE); #endif #ifdef AF_DECnet /* Reserved for DECnet project */ NODE_SOCKET_SET_MACRO(env, exports, AF_DECnet); #endif #ifdef AF_NETBEUI /* Reserved for 802.2LLC project */ NODE_SOCKET_SET_MACRO(env, exports, AF_NETBEUI); #endif #ifdef AF_SECURITY /* Security callback pseudo AF */ NODE_SOCKET_SET_MACRO(env, exports, AF_SECURITY); #endif #ifdef AF_KEY /* PF_KEY key management API */ NODE_SOCKET_SET_MACRO(env, exports, AF_KEY); #endif #ifdef AF_NETLINK /* */ NODE_SOCKET_SET_MACRO(env, exports, AF_NETLINK); #ifdef NETLINK_ROUTE NODE_SOCKET_SET_MACRO(env, exports, NETLINK_ROUTE); #endif #ifdef NETLINK_SKIP NODE_SOCKET_SET_MACRO(env, exports, NETLINK_SKIP); #endif #ifdef NETLINK_W1 NODE_SOCKET_SET_MACRO(env, exports, NETLINK_W1); #endif #ifdef NETLINK_USERSOCK NODE_SOCKET_SET_MACRO(env, exports, NETLINK_USERSOCK); #endif #ifdef NETLINK_FIREWALL NODE_SOCKET_SET_MACRO(env, exports, NETLINK_FIREWALL); #endif #ifdef NETLINK_TCPDIAG NODE_SOCKET_SET_MACRO(env, exports, NETLINK_TCPDIAG); #endif #ifdef NETLINK_NFLOG NODE_SOCKET_SET_MACRO(env, exports, NETLINK_NFLOG); #endif #ifdef NETLINK_XFRM NODE_SOCKET_SET_MACRO(env, exports, NETLINK_XFRM); #endif #ifdef NETLINK_ARPD NODE_SOCKET_SET_MACRO(env, exports, NETLINK_ARPD); #endif #ifdef NETLINK_ROUTE6 NODE_SOCKET_SET_MACRO(env, exports, NETLINK_ROUTE6); #endif #ifdef NETLINK_IP6_FW NODE_SOCKET_SET_MACRO(env, exports, NETLINK_IP6_FW); #endif #ifdef NETLINK_DNRTMSG NODE_SOCKET_SET_MACRO(env, exports, NETLINK_DNRTMSG); #endif #ifdef NETLINK_TAPBASE NODE_SOCKET_SET_MACRO(env, exports, NETLINK_TAPBASE); #endif #ifdef NETLINK_CRYPTO NODE_SOCKET_SET_MACRO(env, exports, NETLINK_CRYPTO); #endif #endif /* AF_NETLINK */ #ifdef AF_QIPCRTR /* Qualcomm IPCROUTER */ NODE_SOCKET_SET_MACRO(env, exports, AF_QIPCRTR); #endif #ifdef AF_VSOCK NODE_SOCKET_SET_CONSTANT(exports, "AF_VSOCK", AF_VSOCK); NODE_SOCKET_SET_CONSTANT(exports, "SO_VM_SOCKETS_BUFFER_SIZE", 0); NODE_SOCKET_SET_CONSTANT(exports, "SO_VM_SOCKETS_BUFFER_MIN_SIZE", 1); NODE_SOCKET_SET_CONSTANT(exports, "SO_VM_SOCKETS_BUFFER_MAX_SIZE", 2); NODE_SOCKET_SET_CONSTANT(exports, "VMADDR_CID_ANY", 0xffffffff); NODE_SOCKET_SET_CONSTANT(exports, "VMADDR_PORT_ANY", 0xffffffff); NODE_SOCKET_SET_CONSTANT(exports, "VMADDR_CID_HOST", 2); NODE_SOCKET_SET_CONSTANT(exports, "VM_SOCKETS_INVALID_VERSION", 0xffffffff); // NODE_SOCKET_SET_CONSTANT(exports, "IOCTL_VM_SOCKETS_GET_LOCAL_CID", _IO(7, 0xb9)); #endif #ifdef AF_ROUTE /* Alias to emulate 4.4BSD */ NODE_SOCKET_SET_MACRO(env, exports, AF_ROUTE); #endif #ifdef AF_LINK NODE_SOCKET_SET_MACRO(env, exports, AF_LINK); #endif #ifdef AF_ASH /* Ash */ NODE_SOCKET_SET_MACRO(env, exports, AF_ASH); #endif #ifdef AF_ECONET /* Acorn Econet */ NODE_SOCKET_SET_MACRO(env, exports, AF_ECONET); #endif #ifdef AF_ATMSVC /* ATM SVCs */ NODE_SOCKET_SET_MACRO(env, exports, AF_ATMSVC); #endif #ifdef AF_SNA /* Linux SNA Project (nutters!) */ NODE_SOCKET_SET_MACRO(env, exports, AF_SNA); #endif #ifdef AF_IRDA /* IRDA sockets */ NODE_SOCKET_SET_MACRO(env, exports, AF_IRDA); #endif #ifdef AF_PPPOX /* PPPoX sockets */ NODE_SOCKET_SET_MACRO(env, exports, AF_PPPOX); #endif #ifdef AF_WANPIPE /* Wanpipe API Sockets */ NODE_SOCKET_SET_MACRO(env, exports, AF_WANPIPE); #endif #ifdef AF_LLC /* Linux LLC */ NODE_SOCKET_SET_MACRO(env, exports, AF_LLC); #endif #ifdef SIO_RCVALL NODE_SOCKET_SET_MACRO(env, exports, SIO_RCVALL); NODE_SOCKET_SET_MACRO(env, exports, RCVALL_OFF); NODE_SOCKET_SET_MACRO(env, exports, RCVALL_ON); NODE_SOCKET_SET_MACRO(env, exports, RCVALL_SOCKETLEVELONLY); #endif #ifdef SIO_KEEPALIVE_VALS NODE_SOCKET_SET_MACRO(env, exports, SIO_KEEPALIVE_VALS); #endif #ifdef USE_BLUETOOTH NODE_SOCKET_SET_MACRO(env, exports, AF_BLUETOOTH); NODE_SOCKET_SET_MACRO(env, exports, BTPROTO_L2CAP); NODE_SOCKET_SET_MACRO(env, exports, BTPROTO_HCI); NODE_SOCKET_SET_MACRO(env, exports, SOL_HCI); #if !defined(__NetBSD__) && !defined(__DragonFly__) NODE_SOCKET_SET_MACRO(env, exports, HCI_FILTER); #endif #if !defined(__FreeBSD__) #if !defined(__NetBSD__) && !defined(__DragonFly__) NODE_SOCKET_SET_MACRO(env, exports, HCI_TIME_STAMP); #endif NODE_SOCKET_SET_MACRO(env, exports, HCI_DATA_DIR); NODE_SOCKET_SET_MACRO(env, exports, BTPROTO_SCO); #endif NODE_SOCKET_SET_MACRO(env, exports, BTPROTO_RFCOMM); // PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00"); // PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF"); #endif #ifdef AF_CAN /* Controller Area Network */ NODE_SOCKET_SET_MACRO(env, exports, AF_CAN); #endif #ifdef PF_CAN /* Controller Area Network */ NODE_SOCKET_SET_MACRO(env, exports, PF_CAN); #endif /* Reliable Datagram Sockets */ #ifdef AF_RDS NODE_SOCKET_SET_MACRO(env, exports, AF_RDS); #endif #ifdef PF_RDS NODE_SOCKET_SET_MACRO(env, exports, PF_RDS); #endif /* Kernel event messages */ #ifdef PF_SYSTEM NODE_SOCKET_SET_MACRO(env, exports, PF_SYSTEM); #endif #ifdef AF_SYSTEM NODE_SOCKET_SET_MACRO(env, exports, AF_SYSTEM); #endif #ifdef AF_PACKET NODE_SOCKET_SET_MACRO(env, exports, AF_PACKET); #endif #ifdef PF_PACKET NODE_SOCKET_SET_MACRO(env, exports, PF_PACKET); #endif #ifdef PACKET_HOST NODE_SOCKET_SET_MACRO(env, exports, PACKET_HOST); #endif #ifdef PACKET_BROADCAST NODE_SOCKET_SET_MACRO(env, exports, PACKET_BROADCAST); #endif #ifdef PACKET_MULTICAST NODE_SOCKET_SET_MACRO(env, exports, PACKET_MULTICAST); #endif #ifdef PACKET_OTHERHOST NODE_SOCKET_SET_MACRO(env, exports, PACKET_OTHERHOST); #endif #ifdef PACKET_OUTGOING NODE_SOCKET_SET_MACRO(env, exports, PACKET_OUTGOING); #endif #ifdef PACKET_LOOPBACK NODE_SOCKET_SET_MACRO(env, exports, PACKET_LOOPBACK); #endif #ifdef PACKET_FASTROUTE NODE_SOCKET_SET_MACRO(env, exports, PACKET_FASTROUTE); #endif #ifdef HAVE_LINUX_TIPC_H NODE_SOCKET_SET_MACRO(env, exports, AF_TIPC); /* for addresses */ NODE_SOCKET_SET_MACRO(env, exports, TIPC_ADDR_NAMESEQ); NODE_SOCKET_SET_MACRO(env, exports, TIPC_ADDR_NAME); NODE_SOCKET_SET_MACRO(env, exports, TIPC_ADDR_ID); NODE_SOCKET_SET_MACRO(env, exports, TIPC_ZONE_SCOPE); NODE_SOCKET_SET_MACRO(env, exports, TIPC_CLUSTER_SCOPE); NODE_SOCKET_SET_MACRO(env, exports, TIPC_NODE_SCOPE); /* for setsockopt() */ NODE_SOCKET_SET_MACRO(env, exports, SOL_TIPC); NODE_SOCKET_SET_MACRO(env, exports, TIPC_IMPORTANCE); NODE_SOCKET_SET_MACRO(env, exports, TIPC_SRC_DROPPABLE); NODE_SOCKET_SET_MACRO(env, exports, TIPC_DEST_DROPPABLE); NODE_SOCKET_SET_MACRO(env, exports, TIPC_CONN_TIMEOUT); NODE_SOCKET_SET_MACRO(env, exports, TIPC_LOW_IMPORTANCE); NODE_SOCKET_SET_MACRO(env, exports, TIPC_MEDIUM_IMPORTANCE); NODE_SOCKET_SET_MACRO(env, exports, TIPC_HIGH_IMPORTANCE); NODE_SOCKET_SET_MACRO(env, exports, TIPC_CRITICAL_IMPORTANCE); /* for subscriptions */ NODE_SOCKET_SET_MACRO(env, exports, TIPC_SUB_PORTS); NODE_SOCKET_SET_MACRO(env, exports, TIPC_SUB_SERVICE); #ifdef TIPC_SUB_CANCEL /* doesn't seem to be available everywhere */ NODE_SOCKET_SET_MACRO(env, exports, TIPC_SUB_CANCEL); #endif NODE_SOCKET_SET_MACRO(env, exports, TIPC_WAIT_FOREVER); NODE_SOCKET_SET_MACRO(env, exports, TIPC_PUBLISHED); NODE_SOCKET_SET_MACRO(env, exports, TIPC_WITHDRAWN); NODE_SOCKET_SET_MACRO(env, exports, TIPC_SUBSCR_TIMEOUT); NODE_SOCKET_SET_MACRO(env, exports, TIPC_CFG_SRV); NODE_SOCKET_SET_MACRO(env, exports, TIPC_TOP_SRV); #endif #ifdef HAVE_SOCKADDR_ALG /* Socket options */ NODE_SOCKET_SET_MACRO(env, exports, ALG_SET_KEY); NODE_SOCKET_SET_MACRO(env, exports, ALG_SET_IV); NODE_SOCKET_SET_MACRO(env, exports, ALG_SET_OP); NODE_SOCKET_SET_MACRO(env, exports, ALG_SET_AEAD_ASSOCLEN); NODE_SOCKET_SET_MACRO(env, exports, ALG_SET_AEAD_AUTHSIZE); NODE_SOCKET_SET_MACRO(env, exports, ALG_SET_PUBKEY); /* Operations */ NODE_SOCKET_SET_MACRO(env, exports, ALG_OP_DECRYPT); NODE_SOCKET_SET_MACRO(env, exports, ALG_OP_ENCRYPT); NODE_SOCKET_SET_MACRO(env, exports, ALG_OP_SIGN); NODE_SOCKET_SET_MACRO(env, exports, ALG_OP_VERIFY); #endif /* Socket types */ NODE_SOCKET_SET_MACRO(env, exports, SOCK_STREAM); NODE_SOCKET_SET_MACRO(env, exports, SOCK_DGRAM); /* We have incomplete socket support. */ #ifdef SOCK_RAW /* SOCK_RAW is marked as optional in the POSIX specification */ NODE_SOCKET_SET_MACRO(env, exports, SOCK_RAW); #endif NODE_SOCKET_SET_MACRO(env, exports, SOCK_SEQPACKET); #if defined(SOCK_RDM) NODE_SOCKET_SET_MACRO(env, exports, SOCK_RDM); #endif #ifdef SOCK_CLOEXEC NODE_SOCKET_SET_MACRO(env, exports, SOCK_CLOEXEC); #endif #ifdef SOCK_NONBLOCK NODE_SOCKET_SET_MACRO(env, exports, SOCK_NONBLOCK); #endif #ifdef SO_DEBUG NODE_SOCKET_SET_MACRO(env, exports, SO_DEBUG); #endif #ifdef SO_ACCEPTCONN NODE_SOCKET_SET_MACRO(env, exports, SO_ACCEPTCONN); #endif #ifdef SO_REUSEADDR NODE_SOCKET_SET_MACRO(env, exports, SO_REUSEADDR); #endif #ifdef SO_EXCLUSIVEADDRUSE NODE_SOCKET_SET_MACRO(env, exports, SO_EXCLUSIVEADDRUSE); #endif #ifdef SO_KEEPALIVE NODE_SOCKET_SET_MACRO(env, exports, SO_KEEPALIVE); #endif #ifdef SO_DONTROUTE NODE_SOCKET_SET_MACRO(env, exports, SO_DONTROUTE); #endif #ifdef SO_BROADCAST NODE_SOCKET_SET_MACRO(env, exports, SO_BROADCAST); #endif #ifdef SO_USELOOPBACK NODE_SOCKET_SET_MACRO(env, exports, SO_USELOOPBACK); #endif #ifdef SO_LINGER NODE_SOCKET_SET_MACRO(env, exports, SO_LINGER); #endif #ifdef SO_OOBINLINE NODE_SOCKET_SET_MACRO(env, exports, SO_OOBINLINE); #endif #ifndef __GNU__ #ifdef SO_REUSEPORT NODE_SOCKET_SET_MACRO(env, exports, SO_REUSEPORT); #endif #endif #ifdef SO_SNDBUF NODE_SOCKET_SET_MACRO(env, exports, SO_SNDBUF); #endif #ifdef SO_RCVBUF NODE_SOCKET_SET_MACRO(env, exports, SO_RCVBUF); #endif #ifdef SO_SNDLOWAT NODE_SOCKET_SET_MACRO(env, exports, SO_SNDLOWAT); #endif #ifdef SO_RCVLOWAT NODE_SOCKET_SET_MACRO(env, exports, SO_RCVLOWAT); #endif #ifdef SO_SNDTIMEO NODE_SOCKET_SET_MACRO(env, exports, SO_SNDTIMEO); #endif #ifdef SO_RCVTIMEO NODE_SOCKET_SET_MACRO(env, exports, SO_RCVTIMEO); #endif #ifdef SO_ERROR NODE_SOCKET_SET_MACRO(env, exports, SO_ERROR); #endif #ifdef SO_TYPE NODE_SOCKET_SET_MACRO(env, exports, SO_TYPE); #endif #ifdef SO_SETFIB NODE_SOCKET_SET_MACRO(env, exports, SO_SETFIB); #endif #ifdef SO_PASSCRED NODE_SOCKET_SET_MACRO(env, exports, SO_PASSCRED); #endif #ifdef SO_PEERCRED NODE_SOCKET_SET_MACRO(env, exports, SO_PEERCRED); #endif #ifdef LOCAL_PEERCRED NODE_SOCKET_SET_MACRO(env, exports, LOCAL_PEERCRED); #endif #ifdef SO_PASSSEC NODE_SOCKET_SET_MACRO(env, exports, SO_PASSSEC); #endif #ifdef SO_PEERSEC NODE_SOCKET_SET_MACRO(env, exports, SO_PEERSEC); #endif #ifdef SO_BINDTODEVICE NODE_SOCKET_SET_MACRO(env, exports, SO_BINDTODEVICE); #endif #ifdef SO_PRIORITY NODE_SOCKET_SET_MACRO(env, exports, SO_PRIORITY); #endif #ifdef SO_MARK NODE_SOCKET_SET_MACRO(env, exports, SO_MARK); #endif #ifdef SO_DOMAIN NODE_SOCKET_SET_MACRO(env, exports, SO_DOMAIN); #endif #ifdef SO_PROTOCOL NODE_SOCKET_SET_MACRO(env, exports, SO_PROTOCOL); #endif /* Maximum number of connections for "listen" */ #ifdef SOMAXCONN NODE_SOCKET_SET_MACRO(env, exports, SOMAXCONN); #else NODE_SOCKET_SET_CONSTANT(exports, "SOMAXCONN", 5); /* Common value */ #endif /* Ancillary message types */ #ifdef SCM_RIGHTS NODE_SOCKET_SET_MACRO(env, exports, SCM_RIGHTS); #endif #ifdef SCM_CREDENTIALS NODE_SOCKET_SET_MACRO(env, exports, SCM_CREDENTIALS); #endif #ifdef SCM_CREDS NODE_SOCKET_SET_MACRO(env, exports, SCM_CREDS); #endif /* Flags for send, recv */ #ifdef MSG_OOB NODE_SOCKET_SET_MACRO(env, exports, MSG_OOB); #endif #ifdef MSG_PEEK NODE_SOCKET_SET_MACRO(env, exports, MSG_PEEK); #endif #ifdef MSG_DONTROUTE NODE_SOCKET_SET_MACRO(env, exports, MSG_DONTROUTE); #endif #ifdef MSG_DONTWAIT NODE_SOCKET_SET_MACRO(env, exports, MSG_DONTWAIT); #endif #ifdef MSG_EOR NODE_SOCKET_SET_MACRO(env, exports, MSG_EOR); #endif #ifdef MSG_TRUNC NODE_SOCKET_SET_MACRO(env, exports, MSG_TRUNC); #endif #ifdef MSG_CTRUNC NODE_SOCKET_SET_MACRO(env, exports, MSG_CTRUNC); #endif #ifdef MSG_WAITALL NODE_SOCKET_SET_MACRO(env, exports, MSG_WAITALL); #endif #ifdef MSG_BTAG NODE_SOCKET_SET_MACRO(env, exports, MSG_BTAG); #endif #ifdef MSG_ETAG NODE_SOCKET_SET_MACRO(env, exports, MSG_ETAG); #endif #ifdef MSG_NOSIGNAL NODE_SOCKET_SET_MACRO(env, exports, MSG_NOSIGNAL); #endif #ifdef MSG_NOTIFICATION NODE_SOCKET_SET_MACRO(env, exports, MSG_NOTIFICATION); #endif #ifdef MSG_CMSG_CLOEXEC NODE_SOCKET_SET_MACRO(env, exports, MSG_CMSG_CLOEXEC); #endif #ifdef MSG_ERRQUEUE NODE_SOCKET_SET_MACRO(env, exports, MSG_ERRQUEUE); #endif #ifdef MSG_CONFIRM NODE_SOCKET_SET_MACRO(env, exports, MSG_CONFIRM); #endif #ifdef MSG_MORE NODE_SOCKET_SET_MACRO(env, exports, MSG_MORE); #endif #ifdef MSG_EOF NODE_SOCKET_SET_MACRO(env, exports, MSG_EOF); #endif #ifdef MSG_BCAST NODE_SOCKET_SET_MACRO(env, exports, MSG_BCAST); #endif #ifdef MSG_MCAST NODE_SOCKET_SET_MACRO(env, exports, MSG_MCAST); #endif #ifdef MSG_FASTOPEN NODE_SOCKET_SET_MACRO(env, exports, MSG_FASTOPEN); #endif /* Protocol level and numbers, usable for [gs]etsockopt */ #ifdef SOL_SOCKET NODE_SOCKET_SET_MACRO(env, exports, SOL_SOCKET); #endif #ifdef SOL_IP NODE_SOCKET_SET_MACRO(env, exports, SOL_IP); #else NODE_SOCKET_SET_CONSTANT(exports, "SOL_IP", 0); #endif #ifdef SOL_IPX NODE_SOCKET_SET_MACRO(env, exports, SOL_IPX); #endif #ifdef SOL_AX25 NODE_SOCKET_SET_MACRO(env, exports, SOL_AX25); #endif #ifdef SOL_ATALK NODE_SOCKET_SET_MACRO(env, exports, SOL_ATALK); #endif #ifdef SOL_NETROM NODE_SOCKET_SET_MACRO(env, exports, SOL_NETROM); #endif #ifdef SOL_ROSE NODE_SOCKET_SET_MACRO(env, exports, SOL_ROSE); #endif #ifdef SOL_TCP NODE_SOCKET_SET_MACRO(env, exports, SOL_TCP); #else NODE_SOCKET_SET_CONSTANT(exports, "SOL_TCP", 6); #endif #ifdef SOL_UDP NODE_SOCKET_SET_MACRO(env, exports, SOL_UDP); #else NODE_SOCKET_SET_CONSTANT(exports, "SOL_UDP", 17); #endif #ifdef SOL_CAN_BASE NODE_SOCKET_SET_MACRO(env, exports, SOL_CAN_BASE); #endif #ifdef SOL_CAN_RAW NODE_SOCKET_SET_MACRO(env, exports, SOL_CAN_RAW); NODE_SOCKET_SET_MACRO(env, exports, CAN_RAW); #endif #ifdef HAVE_LINUX_CAN_H NODE_SOCKET_SET_MACRO(env, exports, CAN_EFF_FLAG); NODE_SOCKET_SET_MACRO(env, exports, CAN_RTR_FLAG); NODE_SOCKET_SET_MACRO(env, exports, CAN_ERR_FLAG); NODE_SOCKET_SET_MACRO(env, exports, CAN_SFF_MASK); NODE_SOCKET_SET_MACRO(env, exports, CAN_EFF_MASK); NODE_SOCKET_SET_MACRO(env, exports, CAN_ERR_MASK); #ifdef CAN_ISOTP NODE_SOCKET_SET_MACRO(env, exports, CAN_ISOTP); #endif #endif #ifdef HAVE_LINUX_CAN_RAW_H NODE_SOCKET_SET_MACRO(env, exports, CAN_RAW_FILTER); NODE_SOCKET_SET_MACRO(env, exports, CAN_RAW_ERR_FILTER); NODE_SOCKET_SET_MACRO(env, exports, CAN_RAW_LOOPBACK); NODE_SOCKET_SET_MACRO(env, exports, CAN_RAW_RECV_OWN_MSGS); #endif #ifdef HAVE_LINUX_CAN_RAW_FD_FRAMES NODE_SOCKET_SET_MACRO(env, exports, CAN_RAW_FD_FRAMES); #endif #ifdef HAVE_LINUX_CAN_BCM_H NODE_SOCKET_SET_MACRO(env, exports, CAN_BCM); /* BCM opcodes */ NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_TX_SETUP", TX_SETUP); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_TX_DELETE", TX_DELETE); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_TX_READ", TX_READ); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_TX_SEND", TX_SEND); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_RX_SETUP", RX_SETUP); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_RX_DELETE", RX_DELETE); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_RX_READ", RX_READ); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_TX_STATUS", TX_STATUS); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_TX_EXPIRED", TX_EXPIRED); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_RX_STATUS", RX_STATUS); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_RX_TIMEOUT", RX_TIMEOUT); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_RX_CHANGED", RX_CHANGED); /* BCM flags */ NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_SETTIMER", SETTIMER); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_STARTTIMER", STARTTIMER); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_TX_COUNTEVT", TX_COUNTEVT); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_TX_ANNOUNCE", TX_ANNOUNCE); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_TX_CP_CAN_ID", TX_CP_CAN_ID); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_RX_FILTER_ID", RX_FILTER_ID); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_RX_CHECK_DLC", RX_CHECK_DLC); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_RX_NO_AUTOTIMER", RX_NO_AUTOTIMER); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_RX_ANNOUNCE_RESUME", RX_ANNOUNCE_RESUME); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_TX_RESET_MULTI_IDX", TX_RESET_MULTI_IDX); NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_RX_RTR_FRAME", RX_RTR_FRAME); #ifdef CAN_FD_FRAME /* CAN_FD_FRAME was only introduced in the 4.8.x kernel series */ NODE_SOCKET_SET_CONSTANT(exports, "CAN_BCM_CAN_FD_FRAME", CAN_FD_FRAME); #endif #endif #ifdef SOL_RDS NODE_SOCKET_SET_MACRO(env, exports, SOL_RDS); #endif #ifdef HAVE_SOCKADDR_ALG NODE_SOCKET_SET_MACRO(env, exports, SOL_ALG); #endif #ifdef RDS_CANCEL_SENT_TO NODE_SOCKET_SET_MACRO(env, exports, RDS_CANCEL_SENT_TO); #endif #ifdef RDS_GET_MR NODE_SOCKET_SET_MACRO(env, exports, RDS_GET_MR); #endif #ifdef RDS_FREE_MR NODE_SOCKET_SET_MACRO(env, exports, RDS_FREE_MR); #endif #ifdef RDS_RECVERR NODE_SOCKET_SET_MACRO(env, exports, RDS_RECVERR); #endif #ifdef RDS_CONG_MONITOR NODE_SOCKET_SET_MACRO(env, exports, RDS_CONG_MONITOR); #endif #ifdef RDS_GET_MR_FOR_DEST NODE_SOCKET_SET_MACRO(env, exports, RDS_GET_MR_FOR_DEST); #endif #ifdef IPPROTO_IP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_IP); #else NODE_SOCKET_SET_CONSTANT(exports, "IPPROTO_IP", 0); #endif #ifdef IPPROTO_HOPOPTS NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_HOPOPTS); #endif #ifdef IPPROTO_ICMP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_ICMP); #else NODE_SOCKET_SET_CONSTANT(exports, "IPPROTO_ICMP", 1); #endif #ifdef IPPROTO_IGMP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_IGMP); #endif #ifdef IPPROTO_GGP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_GGP); #endif #ifdef IPPROTO_IPV4 NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_IPV4); #endif #ifdef IPPROTO_IPV6 NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_IPV6); #endif #ifdef IPPROTO_IPIP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_IPIP); #endif #ifdef IPPROTO_TCP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_TCP); #else NODE_SOCKET_SET_CONSTANT(exports, "IPPROTO_TCP", 6); #endif #ifdef IPPROTO_EGP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_EGP); #endif #ifdef IPPROTO_PUP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_PUP); #endif #ifdef IPPROTO_UDP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_UDP); #else NODE_SOCKET_SET_CONSTANT(exports, "IPPROTO_UDP", 17); #endif #ifdef IPPROTO_IDP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_IDP); #endif #ifdef IPPROTO_HELLO NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_HELLO); #endif #ifdef IPPROTO_ND NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_ND); #endif #ifdef IPPROTO_TP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_TP); #endif #ifdef IPPROTO_ROUTING NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_ROUTING); #endif #ifdef IPPROTO_FRAGMENT NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_FRAGMENT); #endif #ifdef IPPROTO_RSVP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_RSVP); #endif #ifdef IPPROTO_GRE NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_GRE); #endif #ifdef IPPROTO_ESP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_ESP); #endif #ifdef IPPROTO_AH NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_AH); #endif #ifdef IPPROTO_MOBILE NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_MOBILE); #endif #ifdef IPPROTO_ICMPV6 NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_ICMPV6); #endif #ifdef IPPROTO_NONE NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_NONE); #endif #ifdef IPPROTO_DSTOPTS NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_DSTOPTS); #endif #ifdef IPPROTO_XTP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_XTP); #endif #ifdef IPPROTO_EON NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_EON); #endif #ifdef IPPROTO_PIM NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_PIM); #endif #ifdef IPPROTO_IPCOMP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_IPCOMP); #endif #ifdef IPPROTO_VRRP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_VRRP); #endif #ifdef IPPROTO_SCTP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_SCTP); #endif #ifdef IPPROTO_BIP NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_BIP); #endif /**/ #ifdef IPPROTO_RAW NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_RAW); #else NODE_SOCKET_SET_CONSTANT(exports, "IPPROTO_RAW", 255); #endif #ifdef IPPROTO_MAX NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_MAX); #endif #ifdef MS_WINDOWS NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_ICLFXBM); NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_ST); NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_CBT); NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_IGP); NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_RDP); NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_PGM); NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_L2TP); NODE_SOCKET_SET_MACRO(env, exports, IPPROTO_SCTP); #endif #ifdef SYSPROTO_CONTROL NODE_SOCKET_SET_MACRO(env, exports, SYSPROTO_CONTROL); #endif /* Some port configuration */ #ifdef IPPORT_RESERVED NODE_SOCKET_SET_MACRO(env, exports, IPPORT_RESERVED); #else NODE_SOCKET_SET_CONSTANT(exports, "IPPORT_RESERVED", 1024); #endif #ifdef IPPORT_USERRESERVED NODE_SOCKET_SET_MACRO(env, exports, IPPORT_USERRESERVED); #else NODE_SOCKET_SET_CONSTANT(exports, "IPPORT_USERRESERVED", 5000); #endif /* Some reserved IP v.4 addresses */ #ifdef INADDR_ANY NODE_SOCKET_SET_MACRO(env, exports, INADDR_ANY); #else NODE_SOCKET_SET_CONSTANT(exports, "INADDR_ANY", 0x00000000); #endif #ifdef INADDR_BROADCAST NODE_SOCKET_SET_MACRO(env, exports, INADDR_BROADCAST); #else NODE_SOCKET_SET_CONSTANT(exports, "INADDR_BROADCAST", 0xffffffff); #endif #ifdef INADDR_LOOPBACK NODE_SOCKET_SET_MACRO(env, exports, INADDR_LOOPBACK); #else NODE_SOCKET_SET_CONSTANT(exports, "INADDR_LOOPBACK", 0x7F000001); #endif #ifdef INADDR_UNSPEC_GROUP NODE_SOCKET_SET_MACRO(env, exports, INADDR_UNSPEC_GROUP); #else NODE_SOCKET_SET_CONSTANT(exports, "INADDR_UNSPEC_GROUP", 0xe0000000); #endif #ifdef INADDR_ALLHOSTS_GROUP NODE_SOCKET_SET_CONSTANT(exports, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP); #else NODE_SOCKET_SET_CONSTANT(exports, "INADDR_ALLHOSTS_GROUP", 0xe0000001); #endif #ifdef INADDR_MAX_LOCAL_GROUP NODE_SOCKET_SET_MACRO(env, exports, INADDR_MAX_LOCAL_GROUP); #else NODE_SOCKET_SET_CONSTANT(exports, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff); #endif #ifdef INADDR_NONE NODE_SOCKET_SET_MACRO(env, exports, INADDR_NONE); #else NODE_SOCKET_SET_CONSTANT(exports, "INADDR_NONE", 0xffffffff); #endif /* IPv4 [gs]etsockopt options */ #ifdef IP_OPTIONS NODE_SOCKET_SET_MACRO(env, exports, IP_OPTIONS); #endif #ifdef IP_HDRINCL NODE_SOCKET_SET_MACRO(env, exports, IP_HDRINCL); #endif #ifdef IP_TOS NODE_SOCKET_SET_MACRO(env, exports, IP_TOS); #endif #ifdef IP_TTL NODE_SOCKET_SET_MACRO(env, exports, IP_TTL); #endif #ifdef IP_RECVOPTS NODE_SOCKET_SET_MACRO(env, exports, IP_RECVOPTS); #endif #ifdef IP_RECVRETOPTS NODE_SOCKET_SET_MACRO(env, exports, IP_RECVRETOPTS); #endif #ifdef IP_RECVDSTADDR NODE_SOCKET_SET_MACRO(env, exports, IP_RECVDSTADDR); #endif #ifdef IP_RETOPTS NODE_SOCKET_SET_MACRO(env, exports, IP_RETOPTS); #endif #ifdef IP_MULTICAST_IF NODE_SOCKET_SET_MACRO(env, exports, IP_MULTICAST_IF); #endif #ifdef IP_MULTICAST_TTL NODE_SOCKET_SET_MACRO(env, exports, IP_MULTICAST_TTL); #endif #ifdef IP_MULTICAST_LOOP NODE_SOCKET_SET_MACRO(env, exports, IP_MULTICAST_LOOP); #endif #ifdef IP_ADD_MEMBERSHIP NODE_SOCKET_SET_MACRO(env, exports, IP_ADD_MEMBERSHIP); #endif #ifdef IP_DROP_MEMBERSHIP NODE_SOCKET_SET_MACRO(env, exports, IP_DROP_MEMBERSHIP); #endif #ifdef IP_DEFAULT_MULTICAST_TTL NODE_SOCKET_SET_MACRO(env, exports, IP_DEFAULT_MULTICAST_TTL); #endif #ifdef IP_DEFAULT_MULTICAST_LOOP NODE_SOCKET_SET_MACRO(env, exports, IP_DEFAULT_MULTICAST_LOOP); #endif #ifdef IP_MAX_MEMBERSHIPS NODE_SOCKET_SET_MACRO(env, exports, IP_MAX_MEMBERSHIPS); #endif #ifdef IP_TRANSPARENT NODE_SOCKET_SET_MACRO(env, exports, IP_TRANSPARENT); #endif /* IPv6 [gs]etsockopt options, defined in RFC2553 */ #ifdef IPV6_JOIN_GROUP NODE_SOCKET_SET_MACRO(env, exports, IPV6_JOIN_GROUP); #endif #ifdef IPV6_LEAVE_GROUP NODE_SOCKET_SET_MACRO(env, exports, IPV6_LEAVE_GROUP); #endif #ifdef IPV6_MULTICAST_HOPS NODE_SOCKET_SET_MACRO(env, exports, IPV6_MULTICAST_HOPS); #endif #ifdef IPV6_MULTICAST_IF NODE_SOCKET_SET_MACRO(env, exports, IPV6_MULTICAST_IF); #endif #ifdef IPV6_MULTICAST_LOOP NODE_SOCKET_SET_MACRO(env, exports, IPV6_MULTICAST_LOOP); #endif #ifdef IPV6_UNICAST_HOPS NODE_SOCKET_SET_MACRO(env, exports, IPV6_UNICAST_HOPS); #endif /* Additional IPV6 socket options, defined in RFC 3493 */ #ifdef IPV6_V6ONLY NODE_SOCKET_SET_MACRO(env, exports, IPV6_V6ONLY); #endif /* Advanced IPV6 socket options, from RFC 3542 */ #ifdef IPV6_CHECKSUM NODE_SOCKET_SET_MACRO(env, exports, IPV6_CHECKSUM); #endif #ifdef IPV6_DONTFRAG NODE_SOCKET_SET_MACRO(env, exports, IPV6_DONTFRAG); #endif #ifdef IPV6_DSTOPTS NODE_SOCKET_SET_MACRO(env, exports, IPV6_DSTOPTS); #endif #ifdef IPV6_HOPLIMIT NODE_SOCKET_SET_MACRO(env, exports, IPV6_HOPLIMIT); #endif #ifdef IPV6_HOPOPTS NODE_SOCKET_SET_MACRO(env, exports, IPV6_HOPOPTS); #endif #ifdef IPV6_NEXTHOP NODE_SOCKET_SET_MACRO(env, exports, IPV6_NEXTHOP); #endif #ifdef IPV6_PATHMTU NODE_SOCKET_SET_MACRO(env, exports, IPV6_PATHMTU); #endif #ifdef IPV6_PKTINFO NODE_SOCKET_SET_MACRO(env, exports, IPV6_PKTINFO); #endif #ifdef IPV6_RECVDSTOPTS NODE_SOCKET_SET_MACRO(env, exports, IPV6_RECVDSTOPTS); #endif #ifdef IPV6_RECVHOPLIMIT NODE_SOCKET_SET_MACRO(env, exports, IPV6_RECVHOPLIMIT); #endif #ifdef IPV6_RECVHOPOPTS NODE_SOCKET_SET_MACRO(env, exports, IPV6_RECVHOPOPTS); #endif #ifdef IPV6_RECVPKTINFO NODE_SOCKET_SET_MACRO(env, exports, IPV6_RECVPKTINFO); #endif #ifdef IPV6_RECVRTHDR NODE_SOCKET_SET_MACRO(env, exports, IPV6_RECVRTHDR); #endif #ifdef IPV6_RECVTCLASS NODE_SOCKET_SET_MACRO(env, exports, IPV6_RECVTCLASS); #endif #ifdef IPV6_RTHDR NODE_SOCKET_SET_MACRO(env, exports, IPV6_RTHDR); #endif #ifdef IPV6_RTHDRDSTOPTS NODE_SOCKET_SET_MACRO(env, exports, IPV6_RTHDRDSTOPTS); #endif #ifdef IPV6_RTHDR_TYPE_0 NODE_SOCKET_SET_MACRO(env, exports, IPV6_RTHDR_TYPE_0); #endif #ifdef IPV6_RECVPATHMTU NODE_SOCKET_SET_MACRO(env, exports, IPV6_RECVPATHMTU); #endif #ifdef IPV6_TCLASS NODE_SOCKET_SET_MACRO(env, exports, IPV6_TCLASS); #endif #ifdef IPV6_USE_MIN_MTU NODE_SOCKET_SET_MACRO(env, exports, IPV6_USE_MIN_MTU); #endif /* TCP options */ #ifdef TCP_NODELAY NODE_SOCKET_SET_MACRO(env, exports, TCP_NODELAY); #endif #ifdef TCP_MAXSEG NODE_SOCKET_SET_MACRO(env, exports, TCP_MAXSEG); #endif #ifdef TCP_CORK NODE_SOCKET_SET_MACRO(env, exports, TCP_CORK); #endif #ifdef TCP_KEEPIDLE NODE_SOCKET_SET_MACRO(env, exports, TCP_KEEPIDLE); #endif #ifdef TCP_KEEPINTVL NODE_SOCKET_SET_MACRO(env, exports, TCP_KEEPINTVL); #endif #ifdef TCP_KEEPCNT NODE_SOCKET_SET_MACRO(env, exports, TCP_KEEPCNT); #endif #ifdef TCP_SYNCNT NODE_SOCKET_SET_MACRO(env, exports, TCP_SYNCNT); #endif #ifdef TCP_LINGER2 NODE_SOCKET_SET_MACRO(env, exports, TCP_LINGER2); #endif #ifdef TCP_DEFER_ACCEPT NODE_SOCKET_SET_MACRO(env, exports, TCP_DEFER_ACCEPT); #endif #ifdef TCP_WINDOW_CLAMP NODE_SOCKET_SET_MACRO(env, exports, TCP_WINDOW_CLAMP); #endif #ifdef TCP_INFO NODE_SOCKET_SET_MACRO(env, exports, TCP_INFO); #endif #ifdef TCP_QUICKACK NODE_SOCKET_SET_MACRO(env, exports, TCP_QUICKACK); #endif #ifdef TCP_FASTOPEN NODE_SOCKET_SET_MACRO(env, exports, TCP_FASTOPEN); #endif #ifdef TCP_CONGESTION NODE_SOCKET_SET_MACRO(env, exports, TCP_CONGESTION); #endif #ifdef TCP_USER_TIMEOUT NODE_SOCKET_SET_MACRO(env, exports, TCP_USER_TIMEOUT); #endif #ifdef TCP_NOTSENT_LOWAT NODE_SOCKET_SET_MACRO(env, exports, TCP_NOTSENT_LOWAT); #endif /* IPX options */ #ifdef IPX_TYPE NODE_SOCKET_SET_MACRO(env, exports, IPX_TYPE); #endif /* Reliable Datagram Sockets */ #ifdef RDS_CMSG_RDMA_ARGS NODE_SOCKET_SET_MACRO(env, exports, RDS_CMSG_RDMA_ARGS); #endif #ifdef RDS_CMSG_RDMA_DEST NODE_SOCKET_SET_MACRO(env, exports, RDS_CMSG_RDMA_DEST); #endif #ifdef RDS_CMSG_RDMA_MAP NODE_SOCKET_SET_MACRO(env, exports, RDS_CMSG_RDMA_MAP); #endif #ifdef RDS_CMSG_RDMA_STATUS NODE_SOCKET_SET_MACRO(env, exports, RDS_CMSG_RDMA_STATUS); #endif #ifdef RDS_CMSG_RDMA_UPDATE NODE_SOCKET_SET_MACRO(env, exports, RDS_CMSG_RDMA_UPDATE); #endif #ifdef RDS_RDMA_READWRITE NODE_SOCKET_SET_MACRO(env, exports, RDS_RDMA_READWRITE); #endif #ifdef RDS_RDMA_FENCE NODE_SOCKET_SET_MACRO(env, exports, RDS_RDMA_FENCE); #endif #ifdef RDS_RDMA_INVALIDATE NODE_SOCKET_SET_MACRO(env, exports, RDS_RDMA_INVALIDATE); #endif #ifdef RDS_RDMA_USE_ONCE NODE_SOCKET_SET_MACRO(env, exports, RDS_RDMA_USE_ONCE); #endif #ifdef RDS_RDMA_DONTWAIT NODE_SOCKET_SET_MACRO(env, exports, RDS_RDMA_DONTWAIT); #endif #ifdef RDS_RDMA_NOTIFY_ME NODE_SOCKET_SET_MACRO(env, exports, RDS_RDMA_NOTIFY_ME); #endif #ifdef RDS_RDMA_SILENT NODE_SOCKET_SET_MACRO(env, exports, RDS_RDMA_SILENT); #endif /* get{addr,name}info parameters */ #ifdef EAI_ADDRFAMILY NODE_SOCKET_SET_MACRO(env, exports, EAI_ADDRFAMILY); #endif #ifdef EAI_AGAIN NODE_SOCKET_SET_MACRO(env, exports, EAI_AGAIN); #endif #ifdef EAI_BADFLAGS NODE_SOCKET_SET_MACRO(env, exports, EAI_BADFLAGS); #endif #ifdef EAI_FAIL NODE_SOCKET_SET_MACRO(env, exports, EAI_FAIL); #endif #ifdef EAI_FAMILY NODE_SOCKET_SET_MACRO(env, exports, EAI_FAMILY); #endif #ifdef EAI_MEMORY NODE_SOCKET_SET_MACRO(env, exports, EAI_MEMORY); #endif #ifdef EAI_NODATA NODE_SOCKET_SET_MACRO(env, exports, EAI_NODATA); #endif #ifdef EAI_NONAME NODE_SOCKET_SET_MACRO(env, exports, EAI_NONAME); #endif #ifdef EAI_OVERFLOW NODE_SOCKET_SET_MACRO(env, exports, EAI_OVERFLOW); #endif #ifdef EAI_SERVICE NODE_SOCKET_SET_MACRO(env, exports, EAI_SERVICE); #endif #ifdef EAI_SOCKTYPE NODE_SOCKET_SET_MACRO(env, exports, EAI_SOCKTYPE); #endif #ifdef EAI_SYSTEM NODE_SOCKET_SET_MACRO(env, exports, EAI_SYSTEM); #endif #ifdef EAI_BADHINTS NODE_SOCKET_SET_MACRO(env, exports, EAI_BADHINTS); #endif #ifdef EAI_PROTOCOL NODE_SOCKET_SET_MACRO(env, exports, EAI_PROTOCOL); #endif #ifdef EAI_MAX NODE_SOCKET_SET_MACRO(env, exports, EAI_MAX); #endif #ifdef AI_PASSIVE NODE_SOCKET_SET_MACRO(env, exports, AI_PASSIVE); #endif #ifdef AI_CANONNAME NODE_SOCKET_SET_MACRO(env, exports, AI_CANONNAME); #endif #ifdef AI_NUMERICHOST NODE_SOCKET_SET_MACRO(env, exports, AI_NUMERICHOST); #endif #ifdef AI_NUMERICSERV NODE_SOCKET_SET_MACRO(env, exports, AI_NUMERICSERV); #endif #ifdef AI_MASK NODE_SOCKET_SET_MACRO(env, exports, AI_MASK); #endif #ifdef AI_ALL NODE_SOCKET_SET_MACRO(env, exports, AI_ALL); #endif #ifdef AI_V4MAPPED_CFG NODE_SOCKET_SET_MACRO(env, exports, AI_V4MAPPED_CFG); #endif #ifdef AI_ADDRCONFIG NODE_SOCKET_SET_MACRO(env, exports, AI_ADDRCONFIG); #endif #ifdef AI_V4MAPPED NODE_SOCKET_SET_MACRO(env, exports, AI_V4MAPPED); #endif #ifdef AI_DEFAULT NODE_SOCKET_SET_MACRO(env, exports, AI_DEFAULT); #endif #ifdef NI_MAXHOST NODE_SOCKET_SET_MACRO(env, exports, NI_MAXHOST); #endif #ifdef NI_MAXSERV NODE_SOCKET_SET_MACRO(env, exports, NI_MAXSERV); #endif #ifdef NI_NOFQDN NODE_SOCKET_SET_MACRO(env, exports, NI_NOFQDN); #endif #ifdef NI_NUMERICHOST NODE_SOCKET_SET_MACRO(env, exports, NI_NUMERICHOST); #endif #ifdef NI_NAMEREQD NODE_SOCKET_SET_MACRO(env, exports, NI_NAMEREQD); #endif #ifdef NI_NUMERICSERV NODE_SOCKET_SET_MACRO(env, exports, NI_NUMERICSERV); #endif #ifdef NI_DGRAM NODE_SOCKET_SET_MACRO(env, exports, NI_DGRAM); #endif /* shutdown() parameters */ #ifdef SHUT_RD NODE_SOCKET_SET_MACRO(env, exports, SHUT_RD); #elif defined(SD_RECEIVE) NODE_SOCKET_SET_CONSTANT(exports, "SHUT_RD", SD_RECEIVE); #else NODE_SOCKET_SET_CONSTANT(exports, "SHUT_RD", 0); #endif #ifdef SHUT_WR NODE_SOCKET_SET_MACRO(env, exports, SHUT_WR); #elif defined(SD_SEND) NODE_SOCKET_SET_CONSTANT(exports, "SHUT_WR", SD_SEND); #else NODE_SOCKET_SET_CONSTANT(exports, "SHUT_WR", 1); #endif #ifdef SHUT_RDWR NODE_SOCKET_SET_MACRO(env, exports, SHUT_RDWR); #elif defined(SD_BOTH) NODE_SOCKET_SET_CONSTANT(exports, "SHUT_RDWR", SD_BOTH); #else NODE_SOCKET_SET_CONSTANT(exports, "SHUT_RDWR", 2); #endif // } // NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) return exports; } NODE_API_MODULE(fibonacci, Init); }
29.904856
130
0.702061
[ "object" ]
cfa7105e2c52b11909a4d7544a91b8f848171bbe
1,913
cxx
C++
competitive_coding/spoj/dp/alicecub.cxx
5aurabhpathak/src
dda72beba2aaae67542a2f10e89048e86d04cb28
[ "BSD-3-Clause" ]
1
2021-07-07T06:51:18.000Z
2021-07-07T06:51:18.000Z
competitive_coding/spoj/dp/alicecub.cxx
5aurabhpathak/all-I-ve-done
dda72beba2aaae67542a2f10e89048e86d04cb28
[ "BSD-3-Clause" ]
null
null
null
competitive_coding/spoj/dp/alicecub.cxx
5aurabhpathak/all-I-ve-done
dda72beba2aaae67542a2f10e89048e86d04cb28
[ "BSD-3-Clause" ]
1
2020-08-11T09:53:22.000Z
2020-08-11T09:53:22.000Z
#include <algorithm> #include <bitset> #include <climits> #include <iostream> #include <queue> #include <string> #include <vector> using namespace std; struct Vertex { bitset<16> b; int dist; Vertex(const char *c) : b(bitset<16>(c)), dist(0) {} }; vector<Vertex> bfs(); vector<Vertex> neighbours(Vertex &, vector<Vertex> &); int main() { int t, i = 1; bitset<16> b; string s; vector<Vertex> v(bfs()); cin >> t; cin.get(); while (t--) { do getline(cin, s); while (s == ""); s.erase(remove(s.begin(), s.end(), ' '), s.end()); b = bitset<16>(s); auto pred = [&b](Vertex &a)->bool{ return a.b == b; }; auto d = find_if(v.begin(), v.end(), pred); if (d != v.end()) cout << "Case #" << i++ << ": " << d->dist; else cout << "Case #" << i++ << ": more"; cout << endl; } } vector<Vertex> bfs() { vector<Vertex> v; auto comp = [](Vertex &a, Vertex &b)->bool{ return a.dist > b.dist; }; priority_queue<Vertex, vector<Vertex>, decltype(comp)> pq(comp); pq.push("0000000011111111"); auto a = pq.top(); while (a.dist < 4) { v.push_back(a); pq.pop(); for (Vertex n: neighbours(a, v)) { n.dist = a.dist + 1; pq.push(n); } a = pq.top(); } return v; } vector<Vertex> neighbours(Vertex &v, vector<Vertex> &visited) { vector<Vertex> n; static const int a[16][4]{{2,3,5,9}, {1,4,6,10}, {1,4,7,11}, {2,3,8,12}, {1,6,7,13}, {2,5,8,14}, {3,5,8,15}, {4,6,7,16}, {1,10,11,13}, {2,9,12,14}, {3,9,12,15}, {4,10,11,16}, {5,9,14,15}, {6,10,13,16}, {7,11,13,16}, {8,12,14,15}}; for (int i = 0; i < 16; i++) for (int j = 0; j < 4; j++) if (a[i][j] > i+1 && v.b[i] != v.b[a[i][j]-1]) { Vertex newn(v); newn.b[i].flip(); newn.b[a[i][j]-1].flip(); newn.dist = INT_MAX; auto comp = [&newn](Vertex &x)->bool{ return x.b == newn.b; }; auto k = find_if(visited.begin(), visited.end(), comp); if (k == visited.end()) n.push_back(newn); } return n; }
24.21519
73
0.545217
[ "vector" ]
bbb92a1f46548aa004035d14a7c684932cd5956f
24,008
cpp
C++
Source/Cpp/Generated/Time_TypeSupportC.cpp
binary42/OpenDDS
c614bd4207aa962aedc257b669298dbeda05acaa
[ "MIT" ]
1
2019-01-11T12:12:42.000Z
2019-01-11T12:12:42.000Z
Source/Cpp/Generated/Time_TypeSupportC.cpp
binary42/OpenDDS
c614bd4207aa962aedc257b669298dbeda05acaa
[ "MIT" ]
null
null
null
Source/Cpp/Generated/Time_TypeSupportC.cpp
binary42/OpenDDS
c614bd4207aa962aedc257b669298dbeda05acaa
[ "MIT" ]
null
null
null
// -*- C++ -*- // $Id$ /** * Code generated by the The ACE ORB (TAO) IDL Compiler v2.2a_p15 * TAO and the TAO IDL Compiler have been developed by: * Center for Distributed Object Computing * Washington University * St. Louis, MO * USA * http://www.cs.wustl.edu/~schmidt/doc-center.html * and * Distributed Object Computing Laboratory * University of California at Irvine * Irvine, CA * USA * and * Institute for Software Integrated Systems * Vanderbilt University * Nashville, TN * USA * http://www.isis.vanderbilt.edu/ * * Information about TAO is available at: * http://www.cs.wustl.edu/~schmidt/TAO.html **/ // TAO_IDL - Generated from // be/be_codegen.cpp:376 #include "Time_TypeSupportC.h" #include "tao/AnyTypeCode/Null_RefCount_Policy.h" #include "tao/AnyTypeCode/TypeCode_Constants.h" #include "tao/AnyTypeCode/Alias_TypeCode_Static.h" #include "tao/AnyTypeCode/Objref_TypeCode_Static.h" #include "tao/AnyTypeCode/Sequence_TypeCode_Static.h" #include "tao/CDR.h" #include "tao/CDR.h" #include "tao/AnyTypeCode/Any.h" #include "tao/AnyTypeCode/Any_Impl_T.h" #include "tao/AnyTypeCode/Any_Dual_Impl_T.h" #include "ace/OS_NS_string.h" #if !defined (__ACE_INLINE__) #include "Time_TypeSupportC.inl" #endif /* !defined INLINE */ // TAO_IDL - Generated from // be/be_visitor_typecode/alias_typecode.cpp:51 // TAO_IDL - Generated from // be/be_visitor_typecode/typecode_defn.cpp:464 #ifndef _TAO_TYPECODE_builtin_interfaces_msg_dds__Time_Seq_GUARD #define _TAO_TYPECODE_builtin_interfaces_msg_dds__Time_Seq_GUARD TAO_BEGIN_VERSIONED_NAMESPACE_DECL namespace TAO { namespace TypeCode { namespace { TAO::TypeCode::Sequence< ::CORBA::TypeCode_ptr const *, TAO::Null_RefCount_Policy> builtin_interfaces_msg_dds__Time_Seq_0 ( ::CORBA::tk_sequence, &builtin_interfaces::msg::dds_::_tc_Time_, 0U); ::CORBA::TypeCode_ptr const tc_builtin_interfaces_msg_dds__Time_Seq_0 = &builtin_interfaces_msg_dds__Time_Seq_0; } } } TAO_END_VERSIONED_NAMESPACE_DECL #endif /* _TAO_TYPECODE_builtin_interfaces_msg_dds__Time_Seq_GUARD */ static TAO::TypeCode::Alias<char const *, ::CORBA::TypeCode_ptr const *, TAO::Null_RefCount_Policy> _tao_tc_builtin_interfaces_msg_dds__Time_Seq ( ::CORBA::tk_alias, "IDL:builtin_interfaces/msg/dds_/Time_Seq:1.0", "Time_Seq", &TAO::TypeCode::tc_builtin_interfaces_msg_dds__Time_Seq_0); namespace builtin_interfaces { namespace msg { namespace dds_ { ::CORBA::TypeCode_ptr const _tc_Time_Seq = &_tao_tc_builtin_interfaces_msg_dds__Time_Seq; } } } // TAO_IDL - Generated from // be/be_visitor_interface/interface_cs.cpp:51 // Traits specializations for builtin_interfaces::msg::dds_::Time_TypeSupport. builtin_interfaces::msg::dds_::Time_TypeSupport_ptr TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_TypeSupport>::duplicate ( builtin_interfaces::msg::dds_::Time_TypeSupport_ptr p) { return builtin_interfaces::msg::dds_::Time_TypeSupport::_duplicate (p); } void TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_TypeSupport>::release ( builtin_interfaces::msg::dds_::Time_TypeSupport_ptr p) { ::CORBA::release (p); } builtin_interfaces::msg::dds_::Time_TypeSupport_ptr TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_TypeSupport>::nil (void) { return builtin_interfaces::msg::dds_::Time_TypeSupport::_nil (); } ::CORBA::Boolean TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_TypeSupport>::marshal ( const builtin_interfaces::msg::dds_::Time_TypeSupport_ptr p, TAO_OutputCDR & cdr) { return ::CORBA::Object::marshal (p, cdr); } builtin_interfaces::msg::dds_::Time_TypeSupport::Time_TypeSupport (void) {} builtin_interfaces::msg::dds_::Time_TypeSupport::~Time_TypeSupport (void) { } void builtin_interfaces::msg::dds_::Time_TypeSupport::_tao_any_destructor (void *_tao_void_pointer) { Time_TypeSupport *_tao_tmp_pointer = static_cast<Time_TypeSupport *> (_tao_void_pointer); ::CORBA::release (_tao_tmp_pointer); } builtin_interfaces::msg::dds_::Time_TypeSupport_ptr builtin_interfaces::msg::dds_::Time_TypeSupport::_narrow ( ::CORBA::Object_ptr _tao_objref) { return Time_TypeSupport::_duplicate ( dynamic_cast<Time_TypeSupport_ptr> (_tao_objref) ); } builtin_interfaces::msg::dds_::Time_TypeSupport_ptr builtin_interfaces::msg::dds_::Time_TypeSupport::_unchecked_narrow ( ::CORBA::Object_ptr _tao_objref) { return Time_TypeSupport::_duplicate ( dynamic_cast<Time_TypeSupport_ptr> (_tao_objref) ); } builtin_interfaces::msg::dds_::Time_TypeSupport_ptr builtin_interfaces::msg::dds_::Time_TypeSupport::_nil (void) { return 0; } builtin_interfaces::msg::dds_::Time_TypeSupport_ptr builtin_interfaces::msg::dds_::Time_TypeSupport::_duplicate (Time_TypeSupport_ptr obj) { if (! ::CORBA::is_nil (obj)) { obj->_add_ref (); } return obj; } void builtin_interfaces::msg::dds_::Time_TypeSupport::_tao_release (Time_TypeSupport_ptr obj) { ::CORBA::release (obj); } ::CORBA::Boolean builtin_interfaces::msg::dds_::Time_TypeSupport::_is_a (const char *value) { if ( ACE_OS::strcmp ( value, "IDL:DDS/TypeSupport:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:OpenDDS/DCPS/TypeSupport:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:builtin_interfaces/msg/dds_/Time_TypeSupport:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:omg.org/CORBA/LocalObject:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:omg.org/CORBA/Object:1.0" ) == 0 ) { return true; // success using local knowledge } else { return false; } } const char* builtin_interfaces::msg::dds_::Time_TypeSupport::_interface_repository_id (void) const { return "IDL:builtin_interfaces/msg/dds_/Time_TypeSupport:1.0"; } ::CORBA::Boolean builtin_interfaces::msg::dds_::Time_TypeSupport::marshal (TAO_OutputCDR & /* cdr */) { return false; } // TAO_IDL - Generated from // be/be_visitor_typecode/objref_typecode.cpp:72 static TAO::TypeCode::Objref<char const *, TAO::Null_RefCount_Policy> _tao_tc_builtin_interfaces_msg_dds__Time_TypeSupport ( ::CORBA::tk_local_interface, "IDL:builtin_interfaces/msg/dds_/Time_TypeSupport:1.0", "Time_TypeSupport"); namespace builtin_interfaces { namespace msg { namespace dds_ { ::CORBA::TypeCode_ptr const _tc_Time_TypeSupport = &_tao_tc_builtin_interfaces_msg_dds__Time_TypeSupport; } } } // TAO_IDL - Generated from // be/be_visitor_interface/interface_cs.cpp:51 // Traits specializations for builtin_interfaces::msg::dds_::Time_DataWriter. builtin_interfaces::msg::dds_::Time_DataWriter_ptr TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_DataWriter>::duplicate ( builtin_interfaces::msg::dds_::Time_DataWriter_ptr p) { return builtin_interfaces::msg::dds_::Time_DataWriter::_duplicate (p); } void TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_DataWriter>::release ( builtin_interfaces::msg::dds_::Time_DataWriter_ptr p) { ::CORBA::release (p); } builtin_interfaces::msg::dds_::Time_DataWriter_ptr TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_DataWriter>::nil (void) { return builtin_interfaces::msg::dds_::Time_DataWriter::_nil (); } ::CORBA::Boolean TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_DataWriter>::marshal ( const builtin_interfaces::msg::dds_::Time_DataWriter_ptr p, TAO_OutputCDR & cdr) { return ::CORBA::Object::marshal (p, cdr); } builtin_interfaces::msg::dds_::Time_DataWriter::Time_DataWriter (void) {} builtin_interfaces::msg::dds_::Time_DataWriter::~Time_DataWriter (void) { } void builtin_interfaces::msg::dds_::Time_DataWriter::_tao_any_destructor (void *_tao_void_pointer) { Time_DataWriter *_tao_tmp_pointer = static_cast<Time_DataWriter *> (_tao_void_pointer); ::CORBA::release (_tao_tmp_pointer); } builtin_interfaces::msg::dds_::Time_DataWriter_ptr builtin_interfaces::msg::dds_::Time_DataWriter::_narrow ( ::CORBA::Object_ptr _tao_objref) { return Time_DataWriter::_duplicate ( dynamic_cast<Time_DataWriter_ptr> (_tao_objref) ); } builtin_interfaces::msg::dds_::Time_DataWriter_ptr builtin_interfaces::msg::dds_::Time_DataWriter::_unchecked_narrow ( ::CORBA::Object_ptr _tao_objref) { return Time_DataWriter::_duplicate ( dynamic_cast<Time_DataWriter_ptr> (_tao_objref) ); } builtin_interfaces::msg::dds_::Time_DataWriter_ptr builtin_interfaces::msg::dds_::Time_DataWriter::_nil (void) { return 0; } builtin_interfaces::msg::dds_::Time_DataWriter_ptr builtin_interfaces::msg::dds_::Time_DataWriter::_duplicate (Time_DataWriter_ptr obj) { if (! ::CORBA::is_nil (obj)) { obj->_add_ref (); } return obj; } void builtin_interfaces::msg::dds_::Time_DataWriter::_tao_release (Time_DataWriter_ptr obj) { ::CORBA::release (obj); } ::CORBA::Boolean builtin_interfaces::msg::dds_::Time_DataWriter::_is_a (const char *value) { if ( ACE_OS::strcmp ( value, "IDL:DDS/Entity:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:DDS/DataWriter:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:builtin_interfaces/msg/dds_/Time_DataWriter:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:omg.org/CORBA/LocalObject:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:omg.org/CORBA/Object:1.0" ) == 0 ) { return true; // success using local knowledge } else { return false; } } const char* builtin_interfaces::msg::dds_::Time_DataWriter::_interface_repository_id (void) const { return "IDL:builtin_interfaces/msg/dds_/Time_DataWriter:1.0"; } ::CORBA::Boolean builtin_interfaces::msg::dds_::Time_DataWriter::marshal (TAO_OutputCDR & /* cdr */) { return false; } // TAO_IDL - Generated from // be/be_visitor_typecode/objref_typecode.cpp:72 static TAO::TypeCode::Objref<char const *, TAO::Null_RefCount_Policy> _tao_tc_builtin_interfaces_msg_dds__Time_DataWriter ( ::CORBA::tk_local_interface, "IDL:builtin_interfaces/msg/dds_/Time_DataWriter:1.0", "Time_DataWriter"); namespace builtin_interfaces { namespace msg { namespace dds_ { ::CORBA::TypeCode_ptr const _tc_Time_DataWriter = &_tao_tc_builtin_interfaces_msg_dds__Time_DataWriter; } } } // TAO_IDL - Generated from // be/be_visitor_interface/interface_cs.cpp:51 // Traits specializations for builtin_interfaces::msg::dds_::Time_DataReader. builtin_interfaces::msg::dds_::Time_DataReader_ptr TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_DataReader>::duplicate ( builtin_interfaces::msg::dds_::Time_DataReader_ptr p) { return builtin_interfaces::msg::dds_::Time_DataReader::_duplicate (p); } void TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_DataReader>::release ( builtin_interfaces::msg::dds_::Time_DataReader_ptr p) { ::CORBA::release (p); } builtin_interfaces::msg::dds_::Time_DataReader_ptr TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_DataReader>::nil (void) { return builtin_interfaces::msg::dds_::Time_DataReader::_nil (); } ::CORBA::Boolean TAO::Objref_Traits<builtin_interfaces::msg::dds_::Time_DataReader>::marshal ( const builtin_interfaces::msg::dds_::Time_DataReader_ptr p, TAO_OutputCDR & cdr) { return ::CORBA::Object::marshal (p, cdr); } builtin_interfaces::msg::dds_::Time_DataReader::Time_DataReader (void) {} builtin_interfaces::msg::dds_::Time_DataReader::~Time_DataReader (void) { } void builtin_interfaces::msg::dds_::Time_DataReader::_tao_any_destructor (void *_tao_void_pointer) { Time_DataReader *_tao_tmp_pointer = static_cast<Time_DataReader *> (_tao_void_pointer); ::CORBA::release (_tao_tmp_pointer); } builtin_interfaces::msg::dds_::Time_DataReader_ptr builtin_interfaces::msg::dds_::Time_DataReader::_narrow ( ::CORBA::Object_ptr _tao_objref) { return Time_DataReader::_duplicate ( dynamic_cast<Time_DataReader_ptr> (_tao_objref) ); } builtin_interfaces::msg::dds_::Time_DataReader_ptr builtin_interfaces::msg::dds_::Time_DataReader::_unchecked_narrow ( ::CORBA::Object_ptr _tao_objref) { return Time_DataReader::_duplicate ( dynamic_cast<Time_DataReader_ptr> (_tao_objref) ); } builtin_interfaces::msg::dds_::Time_DataReader_ptr builtin_interfaces::msg::dds_::Time_DataReader::_nil (void) { return 0; } builtin_interfaces::msg::dds_::Time_DataReader_ptr builtin_interfaces::msg::dds_::Time_DataReader::_duplicate (Time_DataReader_ptr obj) { if (! ::CORBA::is_nil (obj)) { obj->_add_ref (); } return obj; } void builtin_interfaces::msg::dds_::Time_DataReader::_tao_release (Time_DataReader_ptr obj) { ::CORBA::release (obj); } ::CORBA::Boolean builtin_interfaces::msg::dds_::Time_DataReader::_is_a (const char *value) { if ( ACE_OS::strcmp ( value, "IDL:DDS/Entity:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:DDS/DataReader:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:OpenDDS/DCPS/DataReaderEx:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:builtin_interfaces/msg/dds_/Time_DataReader:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:omg.org/CORBA/LocalObject:1.0" ) == 0 || ACE_OS::strcmp ( value, "IDL:omg.org/CORBA/Object:1.0" ) == 0 ) { return true; // success using local knowledge } else { return false; } } const char* builtin_interfaces::msg::dds_::Time_DataReader::_interface_repository_id (void) const { return "IDL:builtin_interfaces/msg/dds_/Time_DataReader:1.0"; } ::CORBA::Boolean builtin_interfaces::msg::dds_::Time_DataReader::marshal (TAO_OutputCDR & /* cdr */) { return false; } // TAO_IDL - Generated from // be/be_visitor_typecode/objref_typecode.cpp:72 static TAO::TypeCode::Objref<char const *, TAO::Null_RefCount_Policy> _tao_tc_builtin_interfaces_msg_dds__Time_DataReader ( ::CORBA::tk_local_interface, "IDL:builtin_interfaces/msg/dds_/Time_DataReader:1.0", "Time_DataReader"); namespace builtin_interfaces { namespace msg { namespace dds_ { ::CORBA::TypeCode_ptr const _tc_Time_DataReader = &_tao_tc_builtin_interfaces_msg_dds__Time_DataReader; } } } // TAO_IDL - Generated from // be/be_visitor_interface/any_op_cs.cpp:41 TAO_BEGIN_VERSIONED_NAMESPACE_DECL namespace TAO { template<> ::CORBA::Boolean Any_Impl_T<builtin_interfaces::msg::dds_::Time_TypeSupport>::to_object ( ::CORBA::Object_ptr &_tao_elem) const { _tao_elem = ::CORBA::Object::_duplicate (this->value_); return true; } } namespace TAO { template<> ::CORBA::Boolean Any_Impl_T<builtin_interfaces::msg::dds_::Time_TypeSupport>::marshal_value (TAO_OutputCDR &) { return false; } template<> ::CORBA::Boolean Any_Impl_T<builtin_interfaces::msg::dds_::Time_TypeSupport>::demarshal_value (TAO_InputCDR &) { return false; } } TAO_END_VERSIONED_NAMESPACE_DECL #if defined (ACE_ANY_OPS_USE_NAMESPACE) namespace builtin_interfaces { namespace msg { namespace dds_ { /// Copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, Time_TypeSupport_ptr _tao_elem) { Time_TypeSupport_ptr _tao_objptr = Time_TypeSupport::_duplicate (_tao_elem); _tao_any <<= &_tao_objptr; } /// Non-copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, Time_TypeSupport_ptr *_tao_elem) { TAO::Any_Impl_T<Time_TypeSupport>::insert ( _tao_any, Time_TypeSupport::_tao_any_destructor, _tc_Time_TypeSupport, *_tao_elem); } ::CORBA::Boolean operator>>= ( const ::CORBA::Any &_tao_any, Time_TypeSupport_ptr &_tao_elem) { return TAO::Any_Impl_T<Time_TypeSupport>::extract ( _tao_any, Time_TypeSupport::_tao_any_destructor, _tc_Time_TypeSupport, _tao_elem); } } } } #else TAO_BEGIN_VERSIONED_NAMESPACE_DECL /// Copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, builtin_interfaces::msg::dds_::Time_TypeSupport_ptr _tao_elem) { builtin_interfaces::msg::dds_::Time_TypeSupport_ptr _tao_objptr = builtin_interfaces::msg::dds_::Time_TypeSupport::_duplicate (_tao_elem); _tao_any <<= &_tao_objptr; } /// Non-copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, builtin_interfaces::msg::dds_::Time_TypeSupport_ptr *_tao_elem) { TAO::Any_Impl_T<builtin_interfaces::msg::dds_::Time_TypeSupport>::insert ( _tao_any, builtin_interfaces::msg::dds_::Time_TypeSupport::_tao_any_destructor, builtin_interfaces::msg::dds_::_tc_Time_TypeSupport, *_tao_elem); } ::CORBA::Boolean operator>>= ( const ::CORBA::Any &_tao_any, builtin_interfaces::msg::dds_::Time_TypeSupport_ptr &_tao_elem) { return TAO::Any_Impl_T<builtin_interfaces::msg::dds_::Time_TypeSupport>::extract ( _tao_any, builtin_interfaces::msg::dds_::Time_TypeSupport::_tao_any_destructor, builtin_interfaces::msg::dds_::_tc_Time_TypeSupport, _tao_elem); } TAO_END_VERSIONED_NAMESPACE_DECL #endif // TAO_IDL - Generated from // be/be_visitor_interface/any_op_cs.cpp:41 TAO_BEGIN_VERSIONED_NAMESPACE_DECL namespace TAO { template<> ::CORBA::Boolean Any_Impl_T<builtin_interfaces::msg::dds_::Time_DataWriter>::to_object ( ::CORBA::Object_ptr &_tao_elem) const { _tao_elem = ::CORBA::Object::_duplicate (this->value_); return true; } } namespace TAO { template<> ::CORBA::Boolean Any_Impl_T<builtin_interfaces::msg::dds_::Time_DataWriter>::marshal_value (TAO_OutputCDR &) { return false; } template<> ::CORBA::Boolean Any_Impl_T<builtin_interfaces::msg::dds_::Time_DataWriter>::demarshal_value (TAO_InputCDR &) { return false; } } TAO_END_VERSIONED_NAMESPACE_DECL #if defined (ACE_ANY_OPS_USE_NAMESPACE) namespace builtin_interfaces { namespace msg { namespace dds_ { /// Copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, Time_DataWriter_ptr _tao_elem) { Time_DataWriter_ptr _tao_objptr = Time_DataWriter::_duplicate (_tao_elem); _tao_any <<= &_tao_objptr; } /// Non-copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, Time_DataWriter_ptr *_tao_elem) { TAO::Any_Impl_T<Time_DataWriter>::insert ( _tao_any, Time_DataWriter::_tao_any_destructor, _tc_Time_DataWriter, *_tao_elem); } ::CORBA::Boolean operator>>= ( const ::CORBA::Any &_tao_any, Time_DataWriter_ptr &_tao_elem) { return TAO::Any_Impl_T<Time_DataWriter>::extract ( _tao_any, Time_DataWriter::_tao_any_destructor, _tc_Time_DataWriter, _tao_elem); } } } } #else TAO_BEGIN_VERSIONED_NAMESPACE_DECL /// Copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, builtin_interfaces::msg::dds_::Time_DataWriter_ptr _tao_elem) { builtin_interfaces::msg::dds_::Time_DataWriter_ptr _tao_objptr = builtin_interfaces::msg::dds_::Time_DataWriter::_duplicate (_tao_elem); _tao_any <<= &_tao_objptr; } /// Non-copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, builtin_interfaces::msg::dds_::Time_DataWriter_ptr *_tao_elem) { TAO::Any_Impl_T<builtin_interfaces::msg::dds_::Time_DataWriter>::insert ( _tao_any, builtin_interfaces::msg::dds_::Time_DataWriter::_tao_any_destructor, builtin_interfaces::msg::dds_::_tc_Time_DataWriter, *_tao_elem); } ::CORBA::Boolean operator>>= ( const ::CORBA::Any &_tao_any, builtin_interfaces::msg::dds_::Time_DataWriter_ptr &_tao_elem) { return TAO::Any_Impl_T<builtin_interfaces::msg::dds_::Time_DataWriter>::extract ( _tao_any, builtin_interfaces::msg::dds_::Time_DataWriter::_tao_any_destructor, builtin_interfaces::msg::dds_::_tc_Time_DataWriter, _tao_elem); } TAO_END_VERSIONED_NAMESPACE_DECL #endif // TAO_IDL - Generated from // be/be_visitor_interface/any_op_cs.cpp:41 TAO_BEGIN_VERSIONED_NAMESPACE_DECL namespace TAO { template<> ::CORBA::Boolean Any_Impl_T<builtin_interfaces::msg::dds_::Time_DataReader>::to_object ( ::CORBA::Object_ptr &_tao_elem) const { _tao_elem = ::CORBA::Object::_duplicate (this->value_); return true; } } namespace TAO { template<> ::CORBA::Boolean Any_Impl_T<builtin_interfaces::msg::dds_::Time_DataReader>::marshal_value (TAO_OutputCDR &) { return false; } template<> ::CORBA::Boolean Any_Impl_T<builtin_interfaces::msg::dds_::Time_DataReader>::demarshal_value (TAO_InputCDR &) { return false; } } TAO_END_VERSIONED_NAMESPACE_DECL #if defined (ACE_ANY_OPS_USE_NAMESPACE) namespace builtin_interfaces { namespace msg { namespace dds_ { /// Copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, Time_DataReader_ptr _tao_elem) { Time_DataReader_ptr _tao_objptr = Time_DataReader::_duplicate (_tao_elem); _tao_any <<= &_tao_objptr; } /// Non-copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, Time_DataReader_ptr *_tao_elem) { TAO::Any_Impl_T<Time_DataReader>::insert ( _tao_any, Time_DataReader::_tao_any_destructor, _tc_Time_DataReader, *_tao_elem); } ::CORBA::Boolean operator>>= ( const ::CORBA::Any &_tao_any, Time_DataReader_ptr &_tao_elem) { return TAO::Any_Impl_T<Time_DataReader>::extract ( _tao_any, Time_DataReader::_tao_any_destructor, _tc_Time_DataReader, _tao_elem); } } } } #else TAO_BEGIN_VERSIONED_NAMESPACE_DECL /// Copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, builtin_interfaces::msg::dds_::Time_DataReader_ptr _tao_elem) { builtin_interfaces::msg::dds_::Time_DataReader_ptr _tao_objptr = builtin_interfaces::msg::dds_::Time_DataReader::_duplicate (_tao_elem); _tao_any <<= &_tao_objptr; } /// Non-copying insertion. void operator<<= ( ::CORBA::Any &_tao_any, builtin_interfaces::msg::dds_::Time_DataReader_ptr *_tao_elem) { TAO::Any_Impl_T<builtin_interfaces::msg::dds_::Time_DataReader>::insert ( _tao_any, builtin_interfaces::msg::dds_::Time_DataReader::_tao_any_destructor, builtin_interfaces::msg::dds_::_tc_Time_DataReader, *_tao_elem); } ::CORBA::Boolean operator>>= ( const ::CORBA::Any &_tao_any, builtin_interfaces::msg::dds_::Time_DataReader_ptr &_tao_elem) { return TAO::Any_Impl_T<builtin_interfaces::msg::dds_::Time_DataReader>::extract ( _tao_any, builtin_interfaces::msg::dds_::Time_DataReader::_tao_any_destructor, builtin_interfaces::msg::dds_::_tc_Time_DataReader, _tao_elem); } TAO_END_VERSIONED_NAMESPACE_DECL #endif
23.888557
98
0.681481
[ "object" ]
bbddfc7711a3e21647a318f093bf2ab41540f6a0
7,501
cpp
C++
projects/Sandbox/source/Erosion.cpp
TKscoot/Ivy
3b0a09d719e28c260c8eb5d7fbeb52be876e2af8
[ "Apache-2.0" ]
2
2021-11-04T04:01:26.000Z
2021-11-04T04:05:12.000Z
projects/Sandbox/source/Erosion.cpp
TKscoot/Ivy
3b0a09d719e28c260c8eb5d7fbeb52be876e2af8
[ "Apache-2.0" ]
null
null
null
projects/Sandbox/source/Erosion.cpp
TKscoot/Ivy
3b0a09d719e28c260c8eb5d7fbeb52be876e2af8
[ "Apache-2.0" ]
null
null
null
#include "Erosion.h" /*#include <cmath> #include <iostream> #include <omp.h> template <compute_mode_e COMPUTE_MODE> Erosion<COMPUTE_MODE>::Erosion(unsigned mapSize) : mapSize(mapSize) { initializeBrushIndices(); } template <compute_mode_e COMPUTE_MODE> void Erosion<COMPUTE_MODE>::setSeed(int newSeed) { seed = newSeed; Random::seed(seed); } template <compute_mode_e COMPUTE_MODE> void Erosion<COMPUTE_MODE>::erode(std::vector<float> &map, unsigned numIterations) { #pragma omp parallel for schedule(static) if (COMPUTE_MODE == compute_mode_e::parallel) for(unsigned iteration = 0; iteration < numIterations; iteration++) { // Creates the droplet at a random X and Y on the map float posX = Random::get<float>(0, mapSize - 1); float posY = Random::get<float>(0, mapSize - 1); float dirX = 0; float dirY = 0; float speed = initialSpeed; float water = initialWaterVolume; float sediment = 0; // Simulates the droplet only up to it's max lifetime, prevents an infite loop for(unsigned lifetime = 0; lifetime < maxDropletLifetime; lifetime++) { int nodeX = (int)posX; int nodeY = (int)posY; int dropletIndex = nodeY * mapSize + nodeX; // Calculates the droplet offset inside the cell float cellOffsetX = posX - nodeX; float cellOffsetY = posY - nodeY; // Calculate droplet's height and direction of flow with bilinear interpolation of surrounding heights HeightAndGradient heightAndGradient = calculateHeightAndGradient(map, posX, posY); // Update the droplet's direction and position (move position 1 unit regardless of speed) dirX = (dirX * inertia - heightAndGradient.gradientX * (1 - inertia)); dirY = (dirY * inertia - heightAndGradient.gradientY * (1 - inertia)); // Normalize direction float len = std::sqrt(dirX * dirX + dirY * dirY); if(len != 0) { dirX /= len; dirY /= len; } posX += dirX; posY += dirY; // Stop simulating droplet if it's not moving or has flowed over edge of map if((dirX == 0 && dirY == 0) || posX < 0 || posX >= mapSize - 1 || posY < 0 || posY >= mapSize - 1) break; // Find the droplet's new height and calculate the deltaHeight float deltaHeight = calculateHeightAndGradient(map, posX, posY).height - heightAndGradient.height; // Calculate the droplet's sediment capacity (higher when moving fast down a slope and contains lots of water) float sedimentCapacity = std::max(-deltaHeight * speed * water * sedimentCapacityFactor, minSedimentCapacity); // If carrying more sediment than capacity, or if flowing uphill: if(sediment > sedimentCapacity || deltaHeight > 0) { // If moving uphill (deltaHeight > 0) try fill up to the current height, otherwise deposit a fraction of the excess sediment float amountToDeposit = (deltaHeight > 0) ? std::min(deltaHeight, sediment) : (sediment - sedimentCapacity) * depositSpeed; sediment -= amountToDeposit; // Add the sediment to the four nodes of the current cell using bilinear interpolation // Deposition is not distributed over a radius (like erosion) so that it can fill small pits map.at(dropletIndex) += amountToDeposit * (1 - cellOffsetX) * (1 - cellOffsetY); map.at(dropletIndex + 1) += amountToDeposit * cellOffsetX * (1 - cellOffsetY); map.at(dropletIndex + mapSize) += amountToDeposit * (1 - cellOffsetX) * cellOffsetY; map.at(dropletIndex + mapSize + 1) += amountToDeposit * cellOffsetX * cellOffsetY; } else { // Erode a fraction of the droplet's current carry capacity. // Clamp the erosion to the change in height so that it doesn't dig a hole in the terrain behind the droplet float amountToErode = std::min((sedimentCapacity - sediment) * erodeSpeed, -deltaHeight); // Use erosion brush to erode from all nodes inside the droplet's erosion radius for(unsigned brushPointIndex = 0; brushPointIndex < erosionBrushIndices[dropletIndex]->size(); brushPointIndex++) { unsigned nodeIndex = (*erosionBrushIndices[dropletIndex])[brushPointIndex]; if(nodeIndex >= map.size()) continue; float weighedErodeAmount = amountToErode * (*erosionBrushWeights[dropletIndex])[brushPointIndex]; float deltaSediment = (map.at(nodeIndex) < weighedErodeAmount) ? map.at(nodeIndex) : weighedErodeAmount; map.at(nodeIndex) -= deltaSediment; sediment += deltaSediment; } } speed = std::sqrt(speed * speed + std::abs(deltaHeight) * gravity); water *= (1 - evaporateSpeed); } } } template <compute_mode_e COMPUTE_MODE> HeightAndGradient Erosion<COMPUTE_MODE>::calculateHeightAndGradient(std::vector<float> &nodes, float posX, float posY) { int coordX = (int)posX; int coordY = (int)posY; // Calculate droplet's offset inside the cell float x = posX - coordX; float y = posY - coordY; // Calculate heights of the nodes int nodeIndexNW = coordY * mapSize + coordX; float heightNW = nodes[nodeIndexNW]; float heightNE = nodes[nodeIndexNW + 1]; float heightSW = nodes[nodeIndexNW + mapSize]; float heightSE = nodes[nodeIndexNW + mapSize + 1]; // Calculate droplet's direction of flow with bilinear interpolation of height difference along the edges float gradientX = (heightNE - heightNW) * (1 - y) + (heightSE - heightSW) * y; float gradientY = (heightSW - heightNW) * (1 - x) + (heightSE - heightNE) * x; // Calculate height with bilinear interpolation of the heights of the nodes of the cell float height = heightNW * (1 - x) * (1 - y) + heightNE * x * (1 - y) + heightSW * (1 - x) * y + heightSE * x * y; HeightAndGradient hag{ height, gradientX, gradientY }; return hag; } template <compute_mode_e COMPUTE_MODE> void Erosion<COMPUTE_MODE>::initializeBrushIndices() { erosionBrushIndices.resize(mapSize * mapSize); erosionBrushWeights.resize(mapSize * mapSize); std::vector<unsigned> xOffsets((erosionRadius + erosionRadius + 1) * (erosionRadius + erosionRadius + 1)); std::vector<unsigned> yOffsets((erosionRadius + erosionRadius + 1) * (erosionRadius + erosionRadius + 1)); std::vector<float> weights((erosionRadius + erosionRadius + 1) * (erosionRadius + erosionRadius + 1)); #pragma omp parallel for schedule(static) if (COMPUTE_MODE == compute_mode_e::parallel) for(unsigned i = 0; i < (mapSize * mapSize) - 1; i++) { float weightSum = 0; unsigned addIndex = 0; unsigned centerX = i % mapSize; unsigned centerY = i / mapSize; for(int y = -erosionRadius; y <= (int)erosionRadius; y++) { for(int x = -erosionRadius; x <= (int)erosionRadius; x++) { float sqrDst = x * x + y * y; if(sqrDst < erosionRadius * erosionRadius) { int coordX = centerX + x; int coordY = centerY + y; if(0 <= coordX && coordX < (int)mapSize && 0 <= coordY && coordY < (int)mapSize) { float weight = 1 - std::sqrt(sqrDst) / erosionRadius; weightSum += weight; weights[addIndex] = weight; xOffsets[addIndex] = x; yOffsets[addIndex] = y; addIndex++; } } } } unsigned numEntries = addIndex; erosionBrushIndices[i] = new std::vector<unsigned>(numEntries); erosionBrushWeights[i] = new std::vector<float>(numEntries); for(unsigned j = 0; j < numEntries; j++) { (*erosionBrushIndices[i])[j] = (yOffsets[j] + centerY) * mapSize + xOffsets[j] + centerX; (*erosionBrushWeights[i])[j] = weights[j] / weightSum; } } } // Guarantees that all class templates are compiled template class Erosion<compute_mode_e::serial>; template class Erosion<compute_mode_e::parallel>; */
38.466667
128
0.696574
[ "vector" ]
bbe343648b06b3856241fb9ae97ccb47a33e05a4
3,854
cpp
C++
src/wsjcpp_package_downloader_http.cpp
sea-kg/cppspm
3f394dabbb28cbc2c957eed038f3eda260039b84
[ "MIT" ]
21
2020-03-27T17:49:16.000Z
2020-10-11T10:29:37.000Z
src/wsjcpp_package_downloader_http.cpp
sea-kg/cppspm
3f394dabbb28cbc2c957eed038f3eda260039b84
[ "MIT" ]
104
2019-11-22T20:29:47.000Z
2021-10-06T03:38:16.000Z
src/wsjcpp_package_downloader_http.cpp
sea-kg/cppspm
3f394dabbb28cbc2c957eed038f3eda260039b84
[ "MIT" ]
1
2020-05-25T13:54:13.000Z
2020-05-25T13:54:13.000Z
#include "wsjcpp_package_downloader_http.h" #include <wsjcpp_core.h> #include <wsjcpp_hashes.h> #include <wsjcpp_package_manager.h> // --------------------------------------------------------------------- // WsjcppPackageDownloaderHttp WsjcppPackageDownloaderHttp::WsjcppPackageDownloaderHttp() : WsjcppPackageDownloaderBase("http") { TAG = "WsjcppPackageDownloaderHttp"; m_sHttpPrefix = "http://"; // from some http:// m_sHttpsPrefix = "https://"; } // --------------------------------------------------------------------- bool WsjcppPackageDownloaderHttp::canDownload(const std::string &sPackage) { return sPackage.compare(0, m_sHttpPrefix.size(), m_sHttpPrefix) == 0 || sPackage.compare(0, m_sHttpsPrefix.size(), m_sHttpsPrefix) == 0; } // --------------------------------------------------------------------- bool WsjcppPackageDownloaderHttp::downloadToCache( const std::string &sPackage, const std::string &sCacheDir, WsjcppPackageManagerDependence &dep, std::string &sError ) { std::cout << "Download package from " << sPackage << " ..." << std::endl; std::string sWsjcppBaseUrl = sPackage; std::string sDownloadedWsjCppYml2 = sCacheDir + "/wsjcpp.yml"; if (!WsjcppPackageDownloaderBase::downloadFileOverHttps(sWsjcppBaseUrl + "/wsjcpp.yml", sDownloadedWsjCppYml2)) { sError = "Could not download " + sWsjcppBaseUrl; return false; } WsjcppPackageManager pkg(sCacheDir); if (!pkg.load()) { sError = "Could not load " + sCacheDir; return false; } // sources std::vector<WsjcppPackageManagerDistributionFile> vSources = pkg.getListOfDistributionFiles(); for (int i = 0; i < vSources.size(); i++) { WsjcppPackageManagerDistributionFile src = vSources[i]; std::cout << " - " << src.getSourceFile() << ": " << std::endl; if (!WsjcppPackageDownloaderBase::prepareCacheSubdirForFile(sCacheDir, src.getSourceFile(), sError)) { return false; } std::string sDownloadedWsjCppSourceFrom = sWsjcppBaseUrl + "/" + src.getSourceFile(); std::string sDownloadedWsjCppSourceTo = sCacheDir + "/" + src.getSourceFile(); std::cout << " Downloading file from '" << sDownloadedWsjCppSourceFrom << "'" << " to '" << sDownloadedWsjCppSourceTo << "'." << std::endl; if (!WsjcppPackageDownloaderBase::downloadFileOverHttps(sDownloadedWsjCppSourceFrom, sDownloadedWsjCppSourceTo)) { sError = "Could not download " + sDownloadedWsjCppSourceFrom; return false; } else { std::cout << " Completed." << std::endl; } std::string sContent = ""; if (!WsjcppCore::readTextFile(sDownloadedWsjCppSourceTo, sContent)) { sError = "Could not read file " + sDownloadedWsjCppSourceTo; return false; } if (!pkg.updateSourceFile(src.getSourceFile(), false)) { sError = "Could not download " + sDownloadedWsjCppSourceFrom; return false; } } pkg.save(); std::string sInstallationDir = "./src.wsjcpp/" + WsjcppPackageDownloaderBase::prepareCacheSubFolderName(pkg.getName()); dep.setName(pkg.getName()); dep.setVersion(pkg.getVersion()); dep.setUrl(sPackage); dep.setInstallationDir(sInstallationDir); // remove package/version from url std::vector<std::string> vSubdirs = WsjcppCore::split(sPackage, "/"); if (vSubdirs[vSubdirs.size()-1] == "") { vSubdirs.pop_back(); } vSubdirs.pop_back(); // version vSubdirs.pop_back(); // package-name std::string sOrigin = WsjcppCore::join(vSubdirs, "/"); dep.setOrigin(sOrigin); return true; } // ---------------------------------------------------------------------
37.057692
130
0.596264
[ "vector" ]
bbed0d7d428e3eb5ab7ee108f3cf75928dfd8969
5,205
cpp
C++
src/Network.cpp
shans96/basic-neural-network
a9f1aa02f2802cd7f923d88316c9731784b8c4d9
[ "MIT" ]
null
null
null
src/Network.cpp
shans96/basic-neural-network
a9f1aa02f2802cd7f923d88316c9731784b8c4d9
[ "MIT" ]
null
null
null
src/Network.cpp
shans96/basic-neural-network
a9f1aa02f2802cd7f923d88316c9731784b8c4d9
[ "MIT" ]
null
null
null
#include "Network.hpp" Network::Network(const std::vector<int> layer_data) : weights(0), biases(0) { initialize_layers(layer_data); generate_weights(); generate_biases(); } Network::Network(const std::vector<int> layer_data, std::vector<Eigen::MatrixXd> network_weights, std::vector<Eigen::MatrixXd> network_biases) { initialize_layers(layer_data); weights = network_weights; biases = network_biases; } void Network::initialize_layers(std::vector<int> layer_data) { layers = layer_data; non_input_layers = std::vector<int>(layers.begin() + 1, layers.end()); } void Network::generate_biases() { biases.reserve(non_input_layers.size()); for (size_t i = 0; i < non_input_layers.size(); i++) { biases.push_back(Eigen::MatrixXd::Random(non_input_layers[i], 1)); } } void Network::generate_weights() { weights.reserve(layers.size() - 1); for (auto it = layers.begin(); it != layers.end() - 1; it++) { weights.push_back(Eigen::MatrixXd::Random(*next(it), *it)); } } std::tuple<Eigen::MatrixXd, std::vector<Eigen::MatrixXd>, std::vector<Eigen::MatrixXd>> Network::feed_forward(Eigen::VectorXd input) { std::vector<Eigen::MatrixXd> net_inputs; std::vector<Eigen::MatrixXd> activations; net_inputs.reserve(non_input_layers.size() - 1); activations.reserve(non_input_layers.size()); activations.push_back(input); for (size_t i = 0; i < non_input_layers.size(); i++) { input = network_calc::multiply_matrices(weights[i], input) + biases[i]; net_inputs.push_back(input); input = input.unaryExpr([] (double x) { return 1.0 / (1.0 + exp(-x)); }); activations.push_back(input); } return std::make_tuple(input, net_inputs, activations); } std::pair<std::vector<Eigen::MatrixXd>, std::vector<Eigen::MatrixXd>> Network::backpropagate(Eigen::MatrixXd input, Eigen::MatrixXd expected_output) { auto feed_forward_results = (*this).feed_forward(input); Eigen::MatrixXd calculated_output = std::get<0>(feed_forward_results); std::vector<Eigen::MatrixXd> net_inputs = std::get<1>(feed_forward_results); std::vector<Eigen::MatrixXd> activations = std::get<2>(feed_forward_results); std::vector<Eigen::MatrixXd> cloned_weights(weights); std::vector<Eigen::MatrixXd> cloned_biases(biases); for (size_t i = 0; i < layers[layers.size() - 1]; i++) { cloned_biases[cloned_biases.size() - 1](i, 0) = network_calc::result_difference(expected_output(i, 0), calculated_output(i, 0)) * network_calc::sigmoid_derivative(net_inputs[net_inputs.size() - 1](i)); } Eigen::MatrixXd delta = cloned_biases[cloned_biases.size() - 1]; cloned_weights[cloned_weights.size() - 1] = network_calc::multiply_matrices(delta, activations[activations.size() - 2].transpose()); for (size_t i = non_input_layers.size() - 1; !(i == 0); i--) { Eigen::MatrixXd partial_calc = net_inputs[i - 1].unaryExpr([] (double x) { return network_calc::sigmoid_derivative(x); }); delta = network_calc::multiply_matrices(weights[i].transpose(), delta).cwiseProduct(partial_calc); cloned_biases[i - 1] = delta; cloned_weights[i - 1] = network_calc::multiply_matrices(delta, activations[i - 1].transpose()); } return std::make_pair(cloned_biases, cloned_weights); } void Network::mini_batch_gradient_descent(double alpha, int epochs, int batch_size, std::vector<xy_data> training_data) { auto rng = std::default_random_engine{}; std::vector<xy_data> mini_batch; mini_batch.reserve(batch_size); if (training_data.size() < batch_size) { std::cout << "Warning: training data size is less than the batch size. Batch size will be changed to match training data size.\n"; batch_size = training_data.size(); } for (size_t i = 0; i < epochs; i++) { std::shuffle(std::begin(training_data), std::end(training_data), rng); for (size_t j = 0; j < batch_size; j++) { mini_batch.push_back(training_data[j]);; } update_weights_biases(mini_batch, alpha); // Perform prediction on the last example just to check Eigen::MatrixXd new_predicted_output = std::get<2>((*this).feed_forward(training_data.back().first)).back(); std::cout << "Epoch " << std::to_string(i) << ", " << "SSE: " << std::to_string(network_calc::sum_squared_error(new_predicted_output, training_data.back().second)) << ".\n"; } } std::vector<Eigen::MatrixXd> Network::get_weights() { return weights; } std::vector<Eigen::MatrixXd> Network::get_biases() { return biases; } std::vector<int> Network::get_layers() { return layers; } void Network::update_weights_biases(std::vector<xy_data> batch, double alpha) { std::vector<Eigen::MatrixXd> delta_weights = network_calc::created_zeroed_layers(&weights); std::vector<Eigen::MatrixXd> delta_biases = network_calc::created_zeroed_layers(&biases); for (size_t i = 0; i < batch.size(); i++) { auto backprop_output_pair = (*this).backpropagate(batch[i].first, batch[i].second); for (size_t j = 0; j < backprop_output_pair.first.size(); j++) { delta_weights[j] += backprop_output_pair.second[j]; delta_biases[j] += backprop_output_pair.first[j]; } } for (size_t i = 0; i < weights.size(); i++) { weights[i] -= (alpha / batch.size()) * delta_weights[i]; biases[i] -= (alpha / batch.size()) * delta_biases[i]; } }
32.735849
148
0.708934
[ "vector" ]
bbeea1d782b54d11d58a84422f7655845c5074c9
4,152
cpp
C++
src/modules/adc_readout/test/UDPClientTest.cpp
ess-dmsc/event-formation-un
62a2842ea7140162ab9625d22b96f6df369ec07c
[ "BSD-2-Clause" ]
8
2017-12-02T09:20:26.000Z
2022-03-28T08:17:40.000Z
src/modules/adc_readout/test/UDPClientTest.cpp
ess-dmsc/event-formation-un
62a2842ea7140162ab9625d22b96f6df369ec07c
[ "BSD-2-Clause" ]
296
2017-10-24T09:06:10.000Z
2022-03-31T07:31:06.000Z
src/modules/adc_readout/test/UDPClientTest.cpp
ess-dmsc/event-formation-un
62a2842ea7140162ab9625d22b96f6df369ec07c
[ "BSD-2-Clause" ]
8
2018-04-08T15:35:50.000Z
2021-04-12T05:06:15.000Z
/** Copyright (C) 2018-2020 European Spallation Source ERIC */ /** @file * * \brief Unit tests. */ #include <adc_readout/UDPClient.h> #include <common/testutils/TestUDPServer.h> #include <chrono> #include <gtest/gtest.h> using namespace std::chrono_literals; class UDPClientTest : public ::testing::Test { public: void SetUp() override { Service = std::make_shared<asio::io_service>(); } void TearDown() override {} std::shared_ptr<asio::io_service> Service; }; TEST_F(UDPClientTest, DISABLED_SingleUDPPacket) { int BytesToTransmit = 1470; std::uint16_t ListenOnPort = GetPortNumber(); auto SendToPort = ListenOnPort; TestUDPServer Server(GetPortNumber(), SendToPort, BytesToTransmit); int BytesReceived = 0; int PacketsHandled = 0; std::function<void(InData const &Packet)> PacketHandler = [&BytesReceived, &PacketsHandled](auto &Packet) { BytesReceived += Packet.Length; ++PacketsHandled; }; UDPClient TestClient(Service, "0.0.0.0", ListenOnPort, PacketHandler); Server.startPacketTransmission(1, 0); Service->run_for(100ms); EXPECT_EQ(BytesReceived, BytesToTransmit); EXPECT_EQ(PacketsHandled, 1); } TEST_F(UDPClientTest, MultipleUDPPackets) { int BytesToTransmit = 1470; std::uint16_t ListenOnPort = GetPortNumber(); auto SendToPort = ListenOnPort; TestUDPServer Server(GetPortNumber(), SendToPort, BytesToTransmit); int BytesReceived = 0; int PacketsHandled = 0; std::function<void(InData const &Packet)> PacketHandler = [&BytesReceived, &PacketsHandled](auto &Packet) { BytesReceived += Packet.Length; ++PacketsHandled; }; auto NrOfPackets = 5; UDPClient TestClient(Service, "0.0.0.0", ListenOnPort, PacketHandler); Server.startPacketTransmission(NrOfPackets, 5); Service->run_for(100ms); EXPECT_EQ(BytesReceived, BytesToTransmit * NrOfPackets); EXPECT_EQ(PacketsHandled, NrOfPackets); } class UDPClientStandIn : UDPClient { public: UDPClientStandIn(std::shared_ptr<asio::io_service> const &IOService, std::string const &Interface, std::uint16_t Port, std::function<void(InData const &Packet)> Handler) : UDPClient(IOService, Interface, Port, std::move(Handler)){}; using UDPClient::Socket; }; TEST_F(UDPClientTest, PortInUseError) { int BytesToTransmit = 1470; std::uint16_t ListenOnPort = GetPortNumber(); auto SendToPort = ListenOnPort; TestUDPServer Server(GetPortNumber(), SendToPort, BytesToTransmit); int BytesReceived = 0; int PacketsHandled = 0; std::function<void(InData const &Packet)> PacketHandler = [&BytesReceived, &PacketsHandled](auto &Packet) { BytesReceived += Packet.Length; ++PacketsHandled; }; UDPClientStandIn TestClient1(Service, "0.0.0.0", ListenOnPort, PacketHandler); Service->run_for(100ms); EXPECT_TRUE(TestClient1.Socket.is_open()); UDPClientStandIn TestClient2(Service, "0.0.0.0", ListenOnPort, PacketHandler); Service->run_for(100ms); EXPECT_FALSE(TestClient2.Socket.is_open()); } TEST_F(UDPClientTest, DISABLED_MultipleUDPPacketContent) { auto NrOfValues = 100u; std::vector<std::uint8_t> TestData(NrOfValues); for (std::size_t i = 0; i < TestData.size(); i++) { TestData[i] = static_cast<std::uint8_t>(i); } auto BytesToTransmit = NrOfValues * sizeof(TestData[0]); std::uint16_t ListenOnPort = GetPortNumber(); auto SendToPort = ListenOnPort; TestUDPServer Server(GetPortNumber(), SendToPort, &TestData[0], BytesToTransmit); auto BytesReceived = 0u; auto PacketsHandled = 0u; std::function<void(InData const &Packet)> PacketHandler = [&BytesReceived, &PacketsHandled, &TestData](auto &Packet) { EXPECT_EQ(std::memcmp(&Packet.Data[0], &TestData[0], Packet.Length), 0); BytesReceived += Packet.Length; ++PacketsHandled; }; auto NrOfPackets = 5u; UDPClient TestClient(Service, "0.0.0.0", ListenOnPort, PacketHandler); Server.startPacketTransmission(NrOfPackets, 5); Service->run_for(100ms); EXPECT_EQ(BytesReceived, BytesToTransmit * NrOfPackets); EXPECT_EQ(PacketsHandled, NrOfPackets); }
35.487179
80
0.713391
[ "vector" ]
bbf4c243801bef5452611b49ad027887ef174c27
45,879
cpp
C++
Genesis/LifeOfGaben.cpp
andrewpham/Genesis-Engine
7e3f35fbb21ffb3820b4ea39c030f0db5eb8f8d5
[ "MIT" ]
6
2015-07-30T00:21:19.000Z
2018-01-08T09:11:55.000Z
Genesis/LifeOfGaben.cpp
andrewpham/Genesis-Engine
7e3f35fbb21ffb3820b4ea39c030f0db5eb8f8d5
[ "MIT" ]
null
null
null
Genesis/LifeOfGaben.cpp
andrewpham/Genesis-Engine
7e3f35fbb21ffb3820b4ea39c030f0db5eb8f8d5
[ "MIT" ]
null
null
null
// GL includes #include <gengine/Model.h> #include "LifeOfGaben.h" genesis::InputManager _gabenGameInputManager; genesis::ResourceManager _gabenGameResourceManager; static GLfloat _health = 100.0f; static GLfloat _secondsSinceDamaged = 0.0f; Direction vectorDirection(glm::vec2); glm::quat rotationBetweenVectors(glm::vec3, glm::vec3); GLboolean checkCollision(genesis::GameObject3D&, genesis::InputManager&); GLboolean checkTrapCollision(genesis::GameObject3D&, genesis::GameObject3D&); GLboolean checkBulletCollision(genesis::Enemy&, genesis::InputManager&); void resolveCollision(genesis::GameObject3D&, genesis::InputManager&); void resolveEnemyInteractions(genesis::Enemy&, genesis::InputManager&, GLfloat, GLuint); void resolveWallCollisions(GLfloat, GLfloat, GLfloat, GLfloat, genesis::InputManager&); static inline float random_float() { static unsigned int seed = 0x13371337; float res; unsigned int tmp; seed *= 16807; tmp = seed ^ (seed >> 4) ^ (seed << 15); *((unsigned int *)&res) = (tmp >> 9) | 0x3F800000; return (res - 1.0f); } // Courtesy of the fine people over at StackOverflow static inline float random_range(float a, float b) { float random = ((float)rand()) / (float)RAND_MAX; float diff = b - a; float r = random * diff; return a + r; } void run_gaben_game(GLFWwindow* window) { // Define the viewport dimensions glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); // Setup and compile our shaders genesis::Shader shader = _gabenGameResourceManager.loadShader("../Genesis/Shaders/Life of Gaben/object.vs", "Shaders/Life of Gaben/object.frag", "object"); genesis::Shader skyboxShader = _gabenGameResourceManager.loadShader("../Genesis/Shaders/Life of Gaben/skybox.vs", "Shaders/Life of Gaben/skybox.frag", "skybox"); genesis::Shader flockShader = _gabenGameResourceManager.loadShader("../Genesis/Shaders/Life of Gaben/flock.vs", "Shaders/Life of Gaben/flock.frag", "flock"); genesis::Shader flockUpdateShader = _gabenGameResourceManager.loadShader("../Genesis/Shaders/Life of Gaben/flock.comp", "flockUpdate"); // Flock data and state GLuint flockBuffers[2], flockVAO[2], geometryVBO; // Box data and state GLuint boxVAO, boxVBO; // Floor data and state GLuint floorVAO, floorVBO; // Wall data and state GLuint wallVAO, wallVBO; // Square data and state GLuint squareVAO, squareVBO; // Skybox data and state GLuint skyboxVAO, skyboxVBO; // Uniforms for the various shaders struct { struct { GLint view; GLint projection; GLint lightPos; GLint viewPos; } object; struct { GLint view; GLint projection; } skybox; struct { GLuint mvp; } flock; struct { GLint goal; } flockUpdate; } uniforms; // Cache the uniform locations shader.Use(); uniforms.object.view = glGetUniformLocation(shader.ID, "view"); uniforms.object.projection = glGetUniformLocation(shader.ID, "projection"); uniforms.object.lightPos = glGetUniformLocation(shader.ID, "lightPos"); uniforms.object.viewPos = glGetUniformLocation(shader.ID, "viewPos"); // Set the light source properties in the fragment shader glUniform3f(uniforms.object.lightPos, LIGHT_POS.x, LIGHT_POS.y, LIGHT_POS.z); skyboxShader.Use(); uniforms.skybox.view = glGetUniformLocation(skyboxShader.ID, "view"); uniforms.skybox.projection = glGetUniformLocation(skyboxShader.ID, "projection"); flockShader.Use(); uniforms.flock.mvp = glGetUniformLocation(flockShader.ID, "mvp"); flockUpdateShader.Use(); uniforms.flockUpdate.goal = glGetUniformLocation(flockUpdateShader.ID, "goal"); // Index to swap flock buffers with one another to be used in the rendering and computation/data upload stages and vice versa GLuint frameIndex = 0; // Used to pace the spawning of objects at regular intervals GLfloat secondsSincePickup = 0.0f; GLfloat secondsSinceEnemy = 0.0f; GLfloat secondsSinceTrap = 0.0f; GLfloat attackCooldown = 0.0f; GLint numTrapsAvailable = 0; #pragma region "object_initialization" /** Setup box VAO */ glGenVertexArrays(1, &boxVAO); glGenBuffers(1, &boxVBO); glBindVertexArray(boxVAO); glBindBuffer(GL_ARRAY_BUFFER, boxVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(BOX_VERTICES), &BOX_VERTICES, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glBindVertexArray(0); /** Setup floor VAO */ // Floor quad positions glm::vec3 floorPos1(-30.0f, 30.0f, 0.0f); glm::vec3 floorPos2(-30.0f, -30.0f, 0.0f); glm::vec3 floorPos3(30.0f, -30.0f, 0.0f); glm::vec3 floorPos4(30.0f, 30.0f, 0.0f); // Quad texture coordinates glm::vec2 floorUV1(0.0f, 30.0f); glm::vec2 floorUV2(0.0f, 0.0f); glm::vec2 floorUV3(30.0f, 0.0f); glm::vec2 floorUV4(30.0f, 30.0f); // Quad normal vector glm::vec3 nm(0.0, 0.0, 1.0); // Calculate tangent/bitangent vectors of both triangles glm::vec3 floorTangent1, floorBitangent1; glm::vec3 floorTangent2, floorBitangent2; genesis::computeTangentBasis(floorPos1, floorPos2, floorPos3, floorPos4, floorUV1, floorUV2, floorUV3, floorUV4, nm, floorTangent1, floorBitangent1, floorTangent2, floorBitangent2); GLfloat floorVertices[] = { // Positions // Normal // TexCoords // Tangent // Bitangent floorPos1.x, floorPos1.y, floorPos1.z, nm.x, nm.y, nm.z, floorUV1.x, floorUV1.y, floorTangent1.x, floorTangent1.y, floorTangent1.z, floorBitangent1.x, floorBitangent1.y, floorBitangent1.z, floorPos2.x, floorPos2.y, floorPos2.z, nm.x, nm.y, nm.z, floorUV2.x, floorUV2.y, floorTangent1.x, floorTangent1.y, floorTangent1.z, floorBitangent1.x, floorBitangent1.y, floorBitangent1.z, floorPos3.x, floorPos3.y, floorPos3.z, nm.x, nm.y, nm.z, floorUV3.x, floorUV3.y, floorTangent1.x, floorTangent1.y, floorTangent1.z, floorBitangent1.x, floorBitangent1.y, floorBitangent1.z, floorPos1.x, floorPos1.y, floorPos1.z, nm.x, nm.y, nm.z, floorUV1.x, floorUV1.y, floorTangent2.x, floorTangent2.y, floorTangent2.z, floorBitangent2.x, floorBitangent2.y, floorBitangent2.z, floorPos3.x, floorPos3.y, floorPos3.z, nm.x, nm.y, nm.z, floorUV3.x, floorUV3.y, floorTangent2.x, floorTangent2.y, floorTangent2.z, floorBitangent2.x, floorBitangent2.y, floorBitangent2.z, floorPos4.x, floorPos4.y, floorPos4.z, nm.x, nm.y, nm.z, floorUV4.x, floorUV4.y, floorTangent2.x, floorTangent2.y, floorTangent2.z, floorBitangent2.x, floorBitangent2.y, floorBitangent2.z }; glGenVertexArrays(1, &floorVAO); glGenBuffers(1, &floorVBO); glBindVertexArray(floorVAO); glBindBuffer(GL_ARRAY_BUFFER, floorVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(floorVertices), &floorVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(8 * sizeof(GLfloat))); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(11 * sizeof(GLfloat))); glBindVertexArray(0); /** Setup wall VAO */ // Wall quad positions glm::vec3 wallPos1(-40.0f, 1.0f, 0.0f); glm::vec3 wallPos2(-40.0f, -1.0f, 0.0f); glm::vec3 wallPos3(40.0f, -1.0f, 0.0f); glm::vec3 wallPos4(40.0f, 1.0f, 0.0f); // Wall texture coordinates glm::vec2 wallUV1(0.0f, 1.0f); glm::vec2 wallUV2(0.0f, 0.0f); glm::vec2 wallUV3(40.0f, 0.0f); glm::vec2 wallUV4(40.0f, 1.0f); // Calculate tangent/bitangent vectors of both triangles glm::vec3 wallTangent1, wallBitangent1; glm::vec3 wallTangent2, wallBitangent2; genesis::computeTangentBasis(wallPos1, wallPos2, wallPos3, wallPos4, wallUV1, wallUV2, wallUV3, wallUV4, nm, wallTangent1, wallBitangent1, wallTangent2, wallBitangent2); GLfloat wallVertices[] = { // Positions // Normal // TexCoords // Tangent // Bitangent wallPos1.x, wallPos1.y, wallPos1.z, nm.x, nm.y, nm.z, wallUV1.x, wallUV1.y, wallTangent1.x, wallTangent1.y, wallTangent1.z, wallBitangent1.x, wallBitangent1.y, wallBitangent1.z, wallPos2.x, wallPos2.y, wallPos2.z, nm.x, nm.y, nm.z, wallUV2.x, wallUV2.y, wallTangent1.x, wallTangent1.y, wallTangent1.z, wallBitangent1.x, wallBitangent1.y, wallBitangent1.z, wallPos3.x, wallPos3.y, wallPos3.z, nm.x, nm.y, nm.z, wallUV3.x, wallUV3.y, wallTangent1.x, wallTangent1.y, wallTangent1.z, wallBitangent1.x, wallBitangent1.y, wallBitangent1.z, wallPos1.x, wallPos1.y, wallPos1.z, nm.x, nm.y, nm.z, wallUV1.x, wallUV1.y, wallTangent2.x, wallTangent2.y, wallTangent2.z, wallBitangent2.x, wallBitangent2.y, wallBitangent2.z, wallPos3.x, wallPos3.y, wallPos3.z, nm.x, nm.y, nm.z, wallUV3.x, wallUV3.y, wallTangent2.x, wallTangent2.y, wallTangent2.z, wallBitangent2.x, wallBitangent2.y, wallBitangent2.z, wallPos4.x, wallPos4.y, wallPos4.z, nm.x, nm.y, nm.z, wallUV4.x, wallUV4.y, wallTangent2.x, wallTangent2.y, wallTangent2.z, wallBitangent2.x, wallBitangent2.y, wallBitangent2.z }; glGenVertexArrays(1, &wallVAO); glGenBuffers(1, &wallVBO); glBindVertexArray(wallVAO); glBindBuffer(GL_ARRAY_BUFFER, wallVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(wallVertices), &wallVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(8 * sizeof(GLfloat))); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(11 * sizeof(GLfloat))); glBindVertexArray(0); /** Setup square VAO */ // Square quad positions glm::vec3 squarePos1(-0.35f, 0.35f, 0.0f); glm::vec3 squarePos2(-0.35f, -0.35f, 0.0f); glm::vec3 squarePos3(0.35f, -0.35f, 0.0f); glm::vec3 squarePos4(0.35f, 0.35f, 0.0f); // Square texture coordinates glm::vec2 squareUV1(0.0f, 1.0f); glm::vec2 squareUV2(0.0f, 0.0f); glm::vec2 squareUV3(1.0f, 0.0f); glm::vec2 squareUV4(1.0f, 1.0f); // Calculate tangent/bitangent vectors of both triangles glm::vec3 squareTangent1, squareBitangent1; glm::vec3 squareTangent2, squareBitangent2; genesis::computeTangentBasis(squarePos1, squarePos2, squarePos3, squarePos4, squareUV1, squareUV2, squareUV3, squareUV4, nm, squareTangent1, squareBitangent1, squareTangent2, squareBitangent2); GLfloat squareVertices[] = { // Positions // Normal // TexCoords // Tangent // Bitangent squarePos1.x, squarePos1.y, squarePos1.z, nm.x, nm.y, nm.z, squareUV1.x, squareUV1.y, squareTangent1.x, squareTangent1.y, squareTangent1.z, squareBitangent1.x, squareBitangent1.y, squareBitangent1.z, squarePos2.x, squarePos2.y, squarePos2.z, nm.x, nm.y, nm.z, squareUV2.x, squareUV2.y, squareTangent1.x, squareTangent1.y, squareTangent1.z, squareBitangent1.x, squareBitangent1.y, squareBitangent1.z, squarePos3.x, squarePos3.y, squarePos3.z, nm.x, nm.y, nm.z, squareUV3.x, squareUV3.y, squareTangent1.x, squareTangent1.y, squareTangent1.z, squareBitangent1.x, squareBitangent1.y, squareBitangent1.z, squarePos1.x, squarePos1.y, squarePos1.z, nm.x, nm.y, nm.z, squareUV1.x, squareUV1.y, squareTangent2.x, squareTangent2.y, squareTangent2.z, squareBitangent2.x, squareBitangent2.y, squareBitangent2.z, squarePos3.x, squarePos3.y, squarePos3.z, nm.x, nm.y, nm.z, squareUV3.x, squareUV3.y, squareTangent2.x, squareTangent2.y, squareTangent2.z, squareBitangent2.x, squareBitangent2.y, squareBitangent2.z, squarePos4.x, squarePos4.y, squarePos4.z, nm.x, nm.y, nm.z, squareUV4.x, squareUV4.y, squareTangent2.x, squareTangent2.y, squareTangent2.z, squareBitangent2.x, squareBitangent2.y, squareBitangent2.z }; glGenVertexArrays(1, &squareVAO); glGenBuffers(1, &squareVBO); glBindVertexArray(squareVAO); glBindBuffer(GL_ARRAY_BUFFER, squareVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(squareVertices), &squareVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(8 * sizeof(GLfloat))); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(11 * sizeof(GLfloat))); glBindVertexArray(0); /** Setup skybox VAO */ glGenVertexArrays(1, &skyboxVAO); glGenBuffers(1, &skyboxVBO); glBindVertexArray(skyboxVAO); glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(SKYBOX_VERTICES), &SKYBOX_VERTICES, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glBindVertexArray(0); #pragma endregion #pragma region "flock_initialization" // Allocate space for shader storage buffer objects to store and retrieve data pertaining to members of the flock; also bind those objects to the current context glGenBuffers(2, flockBuffers); glBindBuffer(GL_SHADER_STORAGE_BUFFER, flockBuffers[0]); glBufferData(GL_SHADER_STORAGE_BUFFER, FLOCK_SIZE * sizeof(Fish), NULL, GL_DYNAMIC_COPY); glBindBuffer(GL_SHADER_STORAGE_BUFFER, flockBuffers[1]); glBufferData(GL_SHADER_STORAGE_BUFFER, FLOCK_SIZE * sizeof(Fish), NULL, GL_DYNAMIC_COPY); // Upload flock member vertex data to be used during the rendering stage glGenBuffers(1, &geometryVBO); glBindBuffer(GL_ARRAY_BUFFER, geometryVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(FISH_VERTICES), FISH_VERTICES, GL_STATIC_DRAW); // Setup flock VAO glGenVertexArrays(2, flockVAO); int i; for (i = 0; i < 2; i++) { // Bind the geometry data of a flock member to the shaders glBindVertexArray(flockVAO[i]); glBindBuffer(GL_ARRAY_BUFFER, geometryVBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void *)(6 * sizeof(glm::vec3))); // Bind the storage into which the shaders can write computed data glBindBuffer(GL_ARRAY_BUFFER, flockBuffers[i]); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Fish), NULL); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Fish), (void *)sizeof(glm::vec4)); glVertexAttribDivisor(2, 1); glVertexAttribDivisor(3, 1); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); } // Map the entirety of a buffer object's data store into the client's address space so we can write data to it glBindBuffer(GL_ARRAY_BUFFER, flockBuffers[0]); Fish * ptr = reinterpret_cast<Fish *>(glMapBufferRange(GL_ARRAY_BUFFER, 0, FLOCK_SIZE * sizeof(Fish), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT)); for (i = 0; i < FLOCK_SIZE; i++) { ptr[i].position = (glm::vec3(random_float(), random_float(), random_float()) - glm::vec3(0.5f)) * 300.0f; ptr[i].velocity = (glm::vec3(random_float(), random_float(), random_float()) - glm::vec3(0.5f)); } glUnmapBuffer(GL_ARRAY_BUFFER); #pragma endregion // Load textures _gabenGameResourceManager.loadTexture("../Genesis/Textures/Life of Gaben/ground.jpg", false, "floor"); GLuint floorTexture = _gabenGameResourceManager.getTexture("floor").ID; _gabenGameResourceManager.loadTexture("../Genesis/Textures/Life of Gaben/ground_normal.jpg", false, "floorNormalMap"); GLuint floorNormalMap = _gabenGameResourceManager.getTexture("floorNormalMap").ID; _gabenGameResourceManager.loadTexture("../Genesis/Textures/Life of Gaben/brickwall.jpg", false, "wall"); GLuint wallTexture = _gabenGameResourceManager.getTexture("wall").ID; _gabenGameResourceManager.loadTexture("../Genesis/Textures/Life of Gaben/brickwall_normal.jpg", false, "wallNormalMap"); GLuint wallNormalMap = _gabenGameResourceManager.getTexture("wallNormalMap").ID; _gabenGameResourceManager.loadTexture("../Genesis/Textures/container.jpg", false, "tower"); GLuint towerTexture = _gabenGameResourceManager.getTexture("tower").ID; _gabenGameResourceManager.loadTexture("../Genesis/Textures/Life of Gaben/tower_head.jpg", false, "towerHead"); GLuint towerHeadTexture = _gabenGameResourceManager.getTexture("towerHead").ID; _gabenGameResourceManager.loadTexture("../Genesis/Textures/Life of Gaben/square.png", false, "square"); GLuint squareTexture = _gabenGameResourceManager.getTexture("square").ID; // Cubemap (Skybox) vector<const GLchar*> faces; faces.push_back("../Genesis/Textures/Skybox/Life of Gaben/right.jpg"); faces.push_back("../Genesis/Textures/Skybox/Life of Gaben/left.jpg"); faces.push_back("../Genesis/Textures/Skybox/Life of Gaben/top.jpg"); faces.push_back("../Genesis/Textures/Skybox/Life of Gaben/bottom.jpg"); faces.push_back("../Genesis/Textures/Skybox/Life of Gaben/back.jpg"); faces.push_back("../Genesis/Textures/Skybox/Life of Gaben/front.jpg"); _gabenGameResourceManager.loadCubemap(faces); GLuint cubemapTexture = _gabenGameResourceManager.getCubemap(); // Load models genesis::Model house("../Genesis/Objects/Life of Gaben/House/Farmhouse OBJ.obj"); genesis::Model rock("../Genesis/Objects/Rock/rock.obj"); genesis::Model pickup("../Genesis/Objects/Life of Gaben/Pickup/cup OBJ.obj"); genesis::Model enemy("../Genesis/Objects/Nanosuit/nanosuit.obj"); genesis::Model crosshair("../Genesis/Objects/Life of Gaben/Crosshair/sphere.obj"); genesis::Model gun("../Genesis/Objects/Life of Gaben/Gun/M4A1.obj"); // Create game objects genesis::GameObject3D floorObject(shader, floorTexture, floorVAO, 6, glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(1.0f), 90.0f, glm::vec3(1.0f, 0.0f, 0.0f)); floorObject.setNormalMap(floorNormalMap); floorObject.setHasNormalMap(true); genesis::GameObject3D houseObject(shader, house, glm::vec3(-30.0f, -1.05f, 5.0f), glm::vec3(0.55f, 0.55f, 0.55f)); vector<genesis::Enemy> enemyObjects; vector<genesis::GameObject3D> pickupObjects; // Little hack to ensure that the wall textures actually render - not sure why this works! pickupObjects.push_back(genesis::GameObject3D(shader, pickup, glm::vec3(20.0f, 0.0f, 30.0f), glm::vec3(0.025f, 0.025f, 0.025f), 0.0f, glm::vec3(0.0f, 1.0f, 0.0f))); vector<genesis::GameObject3D> wallObjects; GLfloat west = -12.f, east = 14.f, south = 25.f, north = -10.f; wallObjects.push_back(genesis::GameObject3D(shader, wallTexture, wallVAO, 6, glm::vec3(east, 0.0f, 0.0f), glm::vec3(1.0f), 90.f, glm::vec3(0.0f, 1.0f, 0.0f))); wallObjects.push_back(genesis::GameObject3D(shader, wallTexture, wallVAO, 6, glm::vec3(west, 0.0f, 0.0f), glm::vec3(1.0f), 270.f, glm::vec3(0.0f, 1.0f, 0.0f))); wallObjects.push_back(genesis::GameObject3D(shader, wallTexture, wallVAO, 6, glm::vec3(0.0f, 0.0f, north), glm::vec3(1.0f), 180.f, glm::vec3(0.0f, 1.0f, 0.0f))); wallObjects.push_back(genesis::GameObject3D(shader, wallTexture, wallVAO, 6, glm::vec3(0.0f, 0.0f, south))); for (genesis::GameObject3D &wallObject : wallObjects) { wallObject.setNormalMap(wallNormalMap); wallObject.setHasNormalMap(true); } vector<genesis::GameObject3D> rockObjects; rockObjects.push_back(genesis::GameObject3D(shader, rock, glm::vec3(0.0f, -0.95f, 19.0f), glm::vec3(0.25f, 0.25f, 0.25f))); rockObjects.push_back(genesis::GameObject3D(shader, rock, glm::vec3(0.0f, -0.95f, 8.0f), glm::vec3(0.25f, 0.25f, 0.25f), 45.f, glm::vec3(0.0f, 1.0f, 0.0f))); rockObjects.push_back(genesis::GameObject3D(shader, rock, glm::vec3(-4.5f, -0.95f, 13.0f), glm::vec3(0.25f, 0.25f, 0.25f), 90.f, glm::vec3(0.0f, 1.0f, 0.0f))); rockObjects.push_back(genesis::GameObject3D(shader, rock, glm::vec3(5.0f, -0.95f, 13.0f), glm::vec3(0.25f, 0.25f, 0.25f), 135.f, glm::vec3(0.0f, 1.0f, 0.0f))); rockObjects.push_back(genesis::GameObject3D(shader, rock, glm::vec3(-3.0f, -0.95f, 10.0f), glm::vec3(0.25f, 0.25f, 0.25f), 180.f, glm::vec3(0.0f, 1.0f, 0.0f))); rockObjects.push_back(genesis::GameObject3D(shader, rock, glm::vec3(3.5f, -0.95f, 10.0f), glm::vec3(0.25f, 0.25f, 0.25f), 235.f, glm::vec3(0.0f, 1.0f, 0.0f))); rockObjects.push_back(genesis::GameObject3D(shader, rock, glm::vec3(-3.0f, -0.95f, 17.0f), glm::vec3(0.25f, 0.25f, 0.25f), 22.5f, glm::vec3(0.0f, 1.0f, 0.0f))); rockObjects.push_back(genesis::GameObject3D(shader, rock, glm::vec3(3.5f, -0.95f, 17.0f), glm::vec3(0.25f, 0.25f, 0.25f), 67.5f, glm::vec3(0.0f, 1.0f, 0.0f))); for (genesis::GameObject3D &rockObject : rockObjects) { rockObject.setHitboxRadius(0.46f); rockObject.setHitboxOffset(glm::vec3(0.0f, -0.1f, 0.0f)); } vector<genesis::GameObject3D> boxObjects; boxObjects.push_back(genesis::GameObject3D(shader, wallTexture, boxVAO, 36, glm::vec3(-11.0f, 0.0f, -9.0f))); boxObjects.push_back(genesis::GameObject3D(shader, wallTexture, boxVAO, 36, glm::vec3(-11.0f, 0.0f, 24.0f))); boxObjects.push_back(genesis::GameObject3D(shader, wallTexture, boxVAO, 36, glm::vec3(13.0f, 0.0f, 24.0f))); boxObjects.push_back(genesis::GameObject3D(shader, wallTexture, boxVAO, 36, glm::vec3(13.0f, 0.0f, -9.0f))); boxObjects.push_back(genesis::GameObject3D(shader, wallTexture, boxVAO, 36, glm::vec3(6.0f, 0.0f, -3.0f))); boxObjects.push_back(genesis::GameObject3D(shader, wallTexture, boxVAO, 36, glm::vec3(-5.0f, 0.0f, -2.0f))); boxObjects.push_back(genesis::GameObject3D(shader, wallTexture, boxVAO, 36, glm::vec3(0.0f, 0.0f, -7.0f))); for (genesis::GameObject3D &boxObject : boxObjects) { boxObject.setHitboxRadius(1.5f); boxObject.setHitboxOffset(glm::vec3(0.0f)); } vector<genesis::GameObject3D> towerObjects; vector<genesis::GameObject3D> towerHeadObjects; genesis::GameObject3D squareObject(shader, squareTexture, squareVAO, 6, glm::vec3(0.0f, -0.99f, 0.0f), glm::vec3(1.0f), 90.0f, glm::vec3(1.0f, 0.0f, 0.0f)); genesis::GameObject3D crossHairObject(shader, crosshair, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.01f, 0.01f, 0.01f)); genesis::GameObject3D gunObject(shader, gun, glm::vec3(0.2f, -0.2f, -0.5f), glm::vec3(0.03f)); glEnable(GL_DEPTH_TEST); // Play theme song _gabenGameInputManager.getSoundEngine()->play2D("../Genesis/Audio/Life of Gaben/theme.mp3", GL_TRUE); // Game loop while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); _gabenGameInputManager.setDeltaTime(currentFrame - _gabenGameInputManager.getLastFrame()); _gabenGameInputManager.setLastFrame(currentFrame); // Check and call events glfwPollEvents(); _gabenGameInputManager.checkKeysPressed(); // Clear buffers glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Slowly decays the movement speed of Gaben if greater than base speed if (_gabenGameInputManager._camera.MovementSpeed > 3.0f) _gabenGameInputManager._camera.MovementSpeed -= _gabenGameInputManager.getDeltaTime() / 7.0f; // Sets the maximum movement speed of the player if (_gabenGameInputManager._camera.MovementSpeed > 12.0f) _gabenGameInputManager._camera.MovementSpeed = 12.0f; // Controls the gunshot cooldown and later resets the cooldown timer once it expires if (_gabenGameInputManager._keys[GLFW_KEY_SPACE]) attackCooldown += _gabenGameInputManager.getDeltaTime(); // Plays the gunshot sound every time we fire a bullet if (attackCooldown > 0.075f) _gabenGameInputManager.getSoundEngine()->play2D("../Genesis/Audio/Life of Gaben/gunshot.mp3", GL_FALSE); // Set the view position property in the fragment shader shader.Use(); glUniform3f(uniforms.object.viewPos, _gabenGameInputManager._camera.Position.x, _gabenGameInputManager._camera.Position.y, _gabenGameInputManager._camera.Position.z); // Draw skybox first glDepthMask(GL_FALSE); // Remember to turn depth writing off skyboxShader.Use(); glm::mat4 view = glm::mat4(glm::mat3(_gabenGameInputManager._camera.GetViewMatrix())); // Remove any translation component of the view matrix glm::mat4 projection = glm::perspective(_gabenGameInputManager._camera.Zoom, (GLfloat)SCREEN_WIDTH / (GLfloat)SCREEN_HEIGHT, 0.1f, 100.0f); glUniformMatrix4fv(uniforms.skybox.view, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(uniforms.skybox.projection, 1, GL_FALSE, glm::value_ptr(projection)); glBindVertexArray(skyboxVAO); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glDepthMask(GL_TRUE); // Turn depth writing back on // Then draw scene as normal shader.Use(); view = _gabenGameInputManager._camera.GetViewMatrix(); glUniformMatrix4fv(uniforms.object.view, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(uniforms.object.projection, 1, GL_FALSE, glm::value_ptr(projection)); // Floor floorObject.render(); // House houseObject.render(); // Enemy Spawns secondsSinceEnemy += _gabenGameInputManager.getDeltaTime(); if (secondsSinceEnemy >= 4.0f) { secondsSinceEnemy = 0.0f; GLfloat x_rand = random_range(west + 2, east - 2); GLfloat z_rand = random_range(0.0f, south - 2); enemyObjects.push_back(genesis::Enemy(shader, enemy, glm::vec3(x_rand, -0.2f, z_rand), glm::vec3(0.10f, 0.10f, 0.10f))); enemyObjects.back().setHitboxRadius(0.4f); enemyObjects.back().setHitboxOffset(glm::vec3(0.0f, 0.8f, 0.0f)); enemyObjects.back().setAggroRadius(5.0f); enemyObjects.back().setDamageRadius(2.0f); } for (genesis::Enemy &enemyObject : enemyObjects) { if (!enemyObject.getDestroyed()) { enemyObject.setPositionY(-0.2f + sinf(currentFrame) / 4); enemyObject.render(); resolveCollision(enemyObject, _gabenGameInputManager); resolveEnemyInteractions(enemyObject, _gabenGameInputManager, _gabenGameInputManager.getDeltaTime(), DAMAGE); // Checks any bullet collisions with the enemy actor if the F key is pressed if (_gabenGameInputManager._keys[GLFW_KEY_SPACE] && attackCooldown > 0.075f && checkBulletCollision(enemyObject, _gabenGameInputManager)) { enemyObject.setHealth(enemyObject.getHealth() - 1); if (enemyObject.getHealth() < 1) { enemyObject.setDestroyed(true); _gabenGameInputManager.getSoundEngine()->play2D("../Genesis/Audio/Life of Gaben/death.wav", GL_FALSE); } } } } // Print the health of the player //std::cout << _health << std::endl; // Pickup Spawns secondsSincePickup += _gabenGameInputManager.getDeltaTime(); if (secondsSincePickup >= 20.0f) { secondsSincePickup = 0.0f; GLfloat x_rand = random_range(west + 2, east - 2); GLfloat z_rand = random_range(0.0f, south - 2); GLfloat theta_rand = random_range(0.0f, 360.0f); pickupObjects.push_back(genesis::GameObject3D(shader, pickup, glm::vec3(x_rand, -0.75f, z_rand), glm::vec3(0.025f, 0.025f, 0.025f), theta_rand, glm::vec3(0.0f, 1.0f, 0.0f))); pickupObjects.back().setHitboxRadius(0.22f); pickupObjects.back().setHitboxOffset(glm::vec3(0.0f, 0.0f, 0.0f)); } for (genesis::GameObject3D &pickupObject : pickupObjects) { if (!pickupObject.getDestroyed()) { if (pickupObject._rotationAngle > 360.f) pickupObject._rotationAngle = 0.0f; pickupObject._rotationAngle = pickupObject._rotationAngle + _gabenGameInputManager.getDeltaTime(); pickupObject.render(); } if (!pickupObject.getDestroyed() && checkCollision(pickupObject, _gabenGameInputManager)) { pickupObject.setDestroyed(true); _gabenGameInputManager._camera.MovementSpeed *= 2.0f; _gabenGameInputManager.getSoundEngine()->play2D("../Genesis/Audio/Life of Gaben/stim.wav", GL_FALSE); } } // Walls for (genesis::GameObject3D &wallObject : wallObjects) { wallObject.render(); } resolveWallCollisions(north, south, east, west, _gabenGameInputManager); // Rocks for (genesis::GameObject3D &rockObject : rockObjects) { rockObject.render(); resolveCollision(rockObject, _gabenGameInputManager); } // Boxes for (genesis::GameObject3D &boxObject : boxObjects) { boxObject.render(); resolveCollision(boxObject, _gabenGameInputManager); } // Towers // Calculates the world position of where the player is looking at at most one unit away from the player GLfloat x_ray = _gabenGameInputManager._camera.Position.x + 3 * _gabenGameInputManager._camera.Front.x; GLfloat y_ray = _gabenGameInputManager._camera.Position.y + 3 * _gabenGameInputManager._camera.Front.y; GLfloat z_ray = _gabenGameInputManager._camera.Position.z + 3 * _gabenGameInputManager._camera.Front.z; // Keeps track of when we can spawn a new tower defense (once every 15 seconds by default) secondsSinceTrap += _gabenGameInputManager.getDeltaTime(); if (secondsSinceTrap > TOWER_SPAWN_RATE) { secondsSinceTrap = 0.0f; numTrapsAvailable += 1; } if (numTrapsAvailable > 0 && _gabenGameInputManager._keys[GLFW_KEY_E]) { numTrapsAvailable -= 1; towerObjects.push_back(genesis::GameObject3D(shader, towerTexture, boxVAO, 36, glm::vec3(x_ray, 0.0f, z_ray), glm::vec3(0.1f, 1.0f, 0.1f))); towerObjects.back().setHitboxRadius(0.35f); towerObjects.back().setHitboxOffset(glm::vec3(0.0f, 0.0f, 0.0f)); towerHeadObjects.push_back(genesis::GameObject3D(shader, towerHeadTexture, boxVAO, 36, glm::vec3(x_ray, 0.8f, z_ray), glm::vec3(0.2f, 0.2f, 0.2f))); _gabenGameInputManager.getSoundEngine()->play2D("../Genesis/Audio/Life of Gaben/towerplc.wav", GL_FALSE); } for (int i = 0; i < towerObjects.size(); i++) { if (!towerObjects[i].getDestroyed()) { if (towerObjects[i]._rotationAngle > 360.f) towerObjects[i]._rotationAngle = 0.0f; towerObjects[i]._rotationAngle = towerObjects[i]._rotationAngle + _gabenGameInputManager.getDeltaTime(); towerObjects[i].render(); resolveCollision(towerObjects[i], _gabenGameInputManager); if (towerHeadObjects[i]._rotationAngle < -360.f) towerHeadObjects[i]._rotationAngle = 0.0f; towerHeadObjects[i]._rotationAngle = towerHeadObjects[i]._rotationAngle - _gabenGameInputManager.getDeltaTime(); towerHeadObjects[i].render(); resolveCollision(towerHeadObjects[i], _gabenGameInputManager); } for (genesis::Enemy &enemyObject : enemyObjects) { if (!towerObjects[i].getDestroyed() && checkTrapCollision(towerObjects[i], enemyObject)) { towerObjects[i].setDestroyed(true); towerHeadObjects[i].setDestroyed(true); enemyObject.setDestroyed(true); _gabenGameInputManager.getSoundEngine()->play2D("../Genesis/Audio/Life of Gaben/explosion.wav", GL_FALSE); _gabenGameInputManager.getSoundEngine()->play2D("../Genesis/Audio/Life of Gaben/death.wav", GL_FALSE); } } } // Print the number of traps available to place std::cout << numTrapsAvailable << std::endl; // Square squareObject.setPosition(glm::vec3(x_ray, -0.99f, z_ray)); squareObject.render(); // Crosshair crossHairObject.setPosition(glm::vec3(x_ray, y_ray, z_ray)); crossHairObject.render(); // Gun view = glm::mat4(); glUniformMatrix4fv(uniforms.object.view, 1, GL_FALSE, glm::value_ptr(view)); gunObject.render(); // Resets the cooldown tracker once the variable for the current attack cooldown is used in this frame if (attackCooldown > 0.075f) attackCooldown = 0.0f; view = _gabenGameInputManager._camera.GetViewMatrix(); #pragma region "flock_render" flockUpdateShader.Use(); // Shift the flock convergence point over time to create a more dynamic simulation glm::vec3 goal = glm::vec3(sinf(currentFrame * 0.34f * PI_F / 180.f), cosf(currentFrame * 0.29f * PI_F / 180.f), sinf(currentFrame * 0.12f * PI_F / 180.f) * cosf(currentFrame * 0.5f * PI_F / 180.f)); goal = goal * glm::vec3(35.0f, 105.0f, 60.0f); glUniform3fv(uniforms.flockUpdate.goal, 1, glm::value_ptr(goal)); // Swap the flock buffers (one will be used for rendering and the other will be written // into from the shader for the next frame, when it will be used for rendering) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, flockBuffers[frameIndex]); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, flockBuffers[frameIndex ^ 1]); glDispatchCompute(NUM_WORKGROUPS, 1, 1); flockShader.Use(); glm::mat4 mvp = projection * view; glUniformMatrix4fv(uniforms.flock.mvp, 1, GL_FALSE, glm::value_ptr(mvp)); // Render the flock glBindVertexArray(flockVAO[frameIndex]); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 6, FLOCK_SIZE); frameIndex ^= 1; #pragma endregion // Swap the buffers glfwSwapBuffers(window); } glfwTerminate(); } /** Calculates which direction a vector is facing (N,E,S or W) */ Direction vectorDirection(glm::vec2 _target) { glm::vec2 compass[] = { glm::vec2(0.0f, 1.0f), // up glm::vec2(1.0f, 0.0f), // right glm::vec2(0.0f, -1.0f), // down glm::vec2(-1.0f, 0.0f) // left }; GLfloat max = 0.0f; GLuint best_match = -1; for (GLuint i = 0; i < 4; i++) { GLfloat dot_product = glm::dot(glm::normalize(_target), compass[i]); if (dot_product > max) { max = dot_product; best_match = i; } } return (Direction)best_match; } /** http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/ */ glm::quat rotationBetweenVectors(glm::vec3 _start, glm::vec3 _dest) { _start = glm::normalize(_start); _dest = glm::normalize(_dest); float cosTheta = dot(_start, _dest); glm::vec3 rotationAxis; if (cosTheta < -1 + 0.001f) { // special case when vectors in opposite directions: // there is no "ideal" rotation axis // So guess one; any will do as long as it's perpendicular to _start rotationAxis = glm::cross(glm::vec3(0.0f, 0.0f, 1.0f), _start); if (glm::length2(rotationAxis) < 0.01) // bad luck, they were parallel, try again! rotationAxis = glm::cross(glm::vec3(1.0f, 0.0f, 0.0f), _start); rotationAxis = normalize(rotationAxis); return glm::angleAxis(180.0f, rotationAxis); } rotationAxis = cross(_start, _dest); float s = sqrt((1 + cosTheta) * 2); float invs = 1 / s; return glm::quat(s * 0.5f, rotationAxis.x * invs, rotationAxis.y * invs, rotationAxis.z * invs); } GLboolean checkCollision(genesis::GameObject3D &_object, genesis::InputManager &_inputManager) { glm::vec3 hitboxPosition = _object.getPosition() + _object.getHitboxOffset(); glm::vec3 cameraPosition = _inputManager._camera.Position; /** Collision detection booleans */ // Collision right of the hitbox? bool collisionX = hitboxPosition.x + _object.getHitboxRadius() >= cameraPosition.x && cameraPosition.x >= hitboxPosition.x; // Collision behind the hitbox? bool collisionZ = hitboxPosition.z + _object.getHitboxRadius() >= cameraPosition.z && cameraPosition.z >= hitboxPosition.z; // Collision left of the hitbox? bool collisionX2 = hitboxPosition.x - _object.getHitboxRadius() <= cameraPosition.x && cameraPosition.x <= hitboxPosition.x; // Collision in front of the hitbox? bool collisionZ2 = hitboxPosition.z - _object.getHitboxRadius() <= cameraPosition.z && cameraPosition.z <= hitboxPosition.z; return (collisionX && collisionZ) || (collisionX2 && collisionZ) || (collisionX && collisionZ2) || (collisionX2 && collisionZ2); } GLboolean checkTrapCollision(genesis::GameObject3D &_object1, genesis::GameObject3D &_object2) { glm::vec3 hitboxPosition1 = _object1.getPosition() + _object1.getHitboxOffset(); glm::vec3 hitboxPosition2 = _object2.getPosition() + _object2.getHitboxOffset(); GLfloat object1XMax = hitboxPosition1.x + _object1.getHitboxRadius() + 0.15f; GLfloat object1XMin = hitboxPosition1.x - _object1.getHitboxRadius() - 0.15f; GLfloat object1ZMax = hitboxPosition1.z + _object1.getHitboxRadius() + 0.15f; GLfloat object1ZMin = hitboxPosition1.z - _object1.getHitboxRadius() - 0.15f; GLfloat object2XMax = hitboxPosition2.x + _object2.getHitboxRadius(); GLfloat object2XMin = hitboxPosition2.x - _object2.getHitboxRadius(); GLfloat object2ZMax = hitboxPosition2.z + _object2.getHitboxRadius(); GLfloat object2ZMin = hitboxPosition2.z - _object2.getHitboxRadius(); /** Collision detection booleans */ // Collision right of the hitbox? bool collisionX = object1XMax >= object2XMin && object2XMin >= hitboxPosition1.x; // Collision behind the hitbox? bool collisionZ = object1ZMax >= object2ZMin && object2ZMin >= hitboxPosition1.z; // Collision left of the hitbox? bool collisionX2 = object1XMin <= object2XMax && object2XMax <= hitboxPosition1.x; // Collision in front of the hitbox? bool collisionZ2 = object1ZMin <= object2ZMax && object2ZMax <= hitboxPosition1.z; return (collisionX && collisionZ) || (collisionX2 && collisionZ) || (collisionX && collisionZ2) || (collisionX2 && collisionZ2); } /** http://gamedev.stackexchange.com/questions/18436/most-efficient-aabb-vs-ray-collision-algorithms */ GLboolean checkBulletCollision(genesis::Enemy &_enemy, genesis::InputManager &_inputManager) { // dir is the unit direction vector of the ray glm::vec3 dir = _inputManager._camera.Front; glm::vec3 dirfrac; dirfrac.x = 1.0f / dir.x; dirfrac.y = 1.0f / dir.y; dirfrac.z = 1.0f / dir.z; // lb is the corner of the AABB with minimal coordinates, rt is the maximal corner glm::vec3 enemyPos = _enemy.getPosition(); GLfloat hitboxRadius = _enemy.getHitboxRadius(); glm::vec3 hitboxOffset = _enemy.getHitboxOffset(); glm::vec3 lb = glm::vec3(enemyPos.x + hitboxOffset.x - hitboxRadius, enemyPos.y + hitboxOffset.y - (hitboxRadius + 0.4f), enemyPos.z + hitboxOffset.z - hitboxRadius); glm::vec3 rt = glm::vec3(enemyPos.x + hitboxOffset.x + hitboxRadius, enemyPos.y + hitboxOffset.y + (hitboxRadius + 0.4f), enemyPos.z + hitboxOffset.z + hitboxRadius); // org is the origin of the ray glm::vec3 org = _inputManager._camera.Position; float t1 = (lb.x - org.x) * dirfrac.x; float t2 = (rt.x - org.x) * dirfrac.x; float t3 = (lb.y - org.y) * dirfrac.y; float t4 = (rt.y - org.y) * dirfrac.y; float t5 = (lb.z - org.z) * dirfrac.z; float t6 = (rt.z - org.z) * dirfrac.z; float tmin = max(max(min(t1, t2), min(t3, t4)), min(t5, t6)); float tmax = min(min(max(t1, t2), max(t3, t4)), max(t5, t6)); // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us if (tmax < 0) { return false; } // if tmin > tmax, ray doesn't intersect AABB if (tmin > tmax) { return false; } return true; } void resolveCollision(genesis::GameObject3D &_object, genesis::InputManager &_inputManager) { glm::vec3 hitboxPosition = _object.getPosition() + _object.getHitboxOffset(); glm::vec3 cameraPosition = _inputManager._camera.Position; /** Collision detection booleans */ // Collision right of the hitbox? bool collisionX = hitboxPosition.x + _object.getHitboxRadius() >= cameraPosition.x && cameraPosition.x >= hitboxPosition.x; // Collision behind the hitbox? bool collisionZ = hitboxPosition.z + _object.getHitboxRadius() >= cameraPosition.z && cameraPosition.z >= hitboxPosition.z; // Collision left of the hitbox? bool collisionX2 = hitboxPosition.x - _object.getHitboxRadius() <= cameraPosition.x && cameraPosition.x <= hitboxPosition.x; // Collision in front of the hitbox? bool collisionZ2 = hitboxPosition.z - _object.getHitboxRadius() <= cameraPosition.z && cameraPosition.z <= hitboxPosition.z; Direction dir = vectorDirection(glm::vec2(cameraPosition.x - hitboxPosition.x, cameraPosition.z - hitboxPosition.z)); if (collisionX && collisionZ) { GLfloat penetrationX = hitboxPosition.x + _object.getHitboxRadius() - cameraPosition.x; GLfloat penetrationZ = hitboxPosition.z + _object.getHitboxRadius() - cameraPosition.z; if (dir == LEFT || dir == RIGHT) _inputManager._camera.Position.x += penetrationX; else _inputManager._camera.Position.z += penetrationZ; } else if (collisionX2 && collisionZ) { GLfloat penetrationX = cameraPosition.x - (hitboxPosition.x - _object.getHitboxRadius()); GLfloat penetrationZ = hitboxPosition.z + _object.getHitboxRadius() - cameraPosition.z; if (dir == LEFT || dir == RIGHT) _inputManager._camera.Position.x -= penetrationX; else _inputManager._camera.Position.z += penetrationZ; } else if (collisionX && collisionZ2) { GLfloat penetrationX = hitboxPosition.x + _object.getHitboxRadius() - cameraPosition.x; GLfloat penetrationZ = cameraPosition.z - (hitboxPosition.z - _object.getHitboxRadius()); if (dir == LEFT || dir == RIGHT) _inputManager._camera.Position.x += penetrationX; else _inputManager._camera.Position.z -= penetrationZ; } else if (collisionX2 && collisionZ2) { GLfloat penetrationX = cameraPosition.x - (hitboxPosition.x - _object.getHitboxRadius()); GLfloat penetrationZ = cameraPosition.z - (hitboxPosition.z - _object.getHitboxRadius()); if (dir == LEFT || dir == RIGHT) _inputManager._camera.Position.x -= penetrationX; else _inputManager._camera.Position.z -= penetrationZ; } } void resolveEnemyInteractions(genesis::Enemy &_object, genesis::InputManager &_inputManager, GLfloat _velocity, GLuint _damage) { glm::vec3 hitboxPosition = _object.getPosition() + _object.getHitboxOffset(); glm::vec3 cameraPosition = _inputManager._camera.Position; if (_object.getIsAggroed()) { // Make the enemy move towards the player glm::vec3 dir = _inputManager._camera.Position - _object.getPosition(); dir = glm::normalize(dir); _object.setPosition(_object.getPosition() + 3 * _velocity * dir); // Make the enemy rotate towards the player dir = glm::vec3(dir.x, 0.0f, dir.z); dir = glm::normalize(dir); // Find the rotation between the front of the object (that we assume towards +Z, // but this depends on your model) and the desired direction glm::quat targetOrientation = rotationBetweenVectors(glm::vec3(0.0f, 0.0f, 1.0f), dir); // Interpolate between start orientation and target orientation _object.setOrientation(glm::slerp(_object.getOrientation(), targetOrientation, _velocity)); _object._rotationAngle = 2 * acosf(_object.getOrientation().w); /** Collision detection booleans */ // Collision right of the hitbox? bool collisionX = hitboxPosition.x + _object.getDamageRadius() >= cameraPosition.x && cameraPosition.x >= hitboxPosition.x; // Collision behind the hitbox? bool collisionZ = hitboxPosition.z + _object.getDamageRadius() >= cameraPosition.z && cameraPosition.z >= hitboxPosition.z; // Collision left of the hitbox? bool collisionX2 = hitboxPosition.x - _object.getDamageRadius() <= cameraPosition.x && cameraPosition.x <= hitboxPosition.x; // Collision in front of the hitbox? bool collisionZ2 = hitboxPosition.z - _object.getDamageRadius() <= cameraPosition.z && cameraPosition.z <= hitboxPosition.z; if (_health > 0 && ((collisionX && collisionZ) || (collisionX2 && collisionZ) || (collisionX && collisionZ2) || (collisionX2 && collisionZ2))) { if (_secondsSinceDamaged > 1.0f) { _secondsSinceDamaged = 0.0f; _health -= _damage; _gabenGameInputManager.getSoundEngine()->play2D("../Genesis/Audio/Life of Gaben/hit.wav", GL_FALSE); } else _secondsSinceDamaged += _velocity; } return; } /** Aggro detection booleans */ // Collision right of the hitbox? bool collisionX = hitboxPosition.x + _object.getAggroRadius() >= cameraPosition.x && cameraPosition.x >= hitboxPosition.x; // Collision behind the hitbox? bool collisionZ = hitboxPosition.z + _object.getAggroRadius() >= cameraPosition.z && cameraPosition.z >= hitboxPosition.z; // Collision left of the hitbox? bool collisionX2 = hitboxPosition.x - _object.getAggroRadius() <= cameraPosition.x && cameraPosition.x <= hitboxPosition.x; // Collision in front of the hitbox? bool collisionZ2 = hitboxPosition.z - _object.getAggroRadius() <= cameraPosition.z && cameraPosition.z <= hitboxPosition.z; Direction dir = vectorDirection(glm::vec2(cameraPosition.x - hitboxPosition.x, cameraPosition.z - hitboxPosition.z)); if (!_object.getIsAggroed() && ((collisionX && collisionZ) || (collisionX2 && collisionZ) || (collisionX && collisionZ2) || (collisionX2 && collisionZ2))) { _object.setIsAggroed(true); _gabenGameInputManager.getSoundEngine()->play2D("../Genesis/Audio/Life of Gaben/aggro.ogg", GL_FALSE); } } /** Note the coordinate bounds within the game world and ensure proper collision resolution at those limits */ void resolveWallCollisions(GLfloat _north, GLfloat _south, GLfloat _east, GLfloat _west, genesis::InputManager &_inputManager) { glm::vec3 cameraPosition = _inputManager._camera.Position; GLfloat southBoundary = _south - 0.5f, northBoundary = _north + 0.5f, westBoundary = _west + 0.5f, eastBoundary = _east - 0.5f; if (cameraPosition.z >= southBoundary) { GLfloat penetration = cameraPosition.z - southBoundary; _inputManager._camera.Position.z -= penetration; } else if (cameraPosition.z <= northBoundary) { GLfloat penetration = northBoundary - cameraPosition.z; _inputManager._camera.Position.z += penetration; } else if (cameraPosition.x >= eastBoundary) { GLfloat penetration = cameraPosition.x - eastBoundary; _inputManager._camera.Position.x -= penetration; } else if (cameraPosition.x <= westBoundary) { GLfloat penetration = westBoundary - cameraPosition.x; _inputManager._camera.Position.x += penetration; } }
47.200617
201
0.735086
[ "geometry", "render", "object", "vector", "model" ]
bbfaed82f6a95280fb1295e28ada173649fe31b3
1,250
cpp
C++
TopicWiseQuestions/DP/Cses/BookShop/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
TopicWiseQuestions/DP/Cses/BookShop/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
TopicWiseQuestions/DP/Cses/BookShop/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long double ld; typedef long long int ll; #define endl "\n" vector<vector<ll>> adjlist; ll max(ll x, ll y) { return (x > y) ? x : y; } ll min(ll x, ll y) { return (x > y) ? y : x; } #define mod 1000000007 ll cases = 1, n, sum, m; ll x, y; void solveCase() { cin >> n >> sum; vector<pair<ll, ll>> bookProps(n + 1); vector<vector<ll>> maxPagesWithPriceI(n + 1, vector<ll>(sum + 1, 0)); for (ll i = 1; i <= n; i++) { cin >> bookProps[i].first; } for (ll i = 1; i <= n; i++) { cin >> bookProps[i].second; } for (ll i = 1; i <= n; i++) { for (ll j = 1; j <= sum; j++) { if (bookProps[i].first <= j) { maxPagesWithPriceI[i][j] = bookProps[i].second + maxPagesWithPriceI[i - 1][j - bookProps[i].first]; } maxPagesWithPriceI[i][j] = max(maxPagesWithPriceI[i - 1][j], maxPagesWithPriceI[i][j]); // cout << "idxs: " << i << " " << j << endl; } // cout << endl; } cout << maxPagesWithPriceI[n][sum] << endl; } int main() { // cin >> cases; for (ll t = 1; t <= cases; t++) { solveCase(); } return 0; }
24.509804
115
0.4832
[ "vector" ]
bbfc01eacaf536f85d3e67134835b146737e37cf
591,846
cpp
C++
cisco-ios-xe/ydk/models/cisco_ios_xe/fragmented/Cisco_IOS_XE_native_11.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/fragmented/Cisco_IOS_XE_native_11.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/fragmented/Cisco_IOS_XE_native_11.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "Cisco_IOS_XE_native_11.hpp" #include "Cisco_IOS_XE_native_12.hpp" using namespace ydk; namespace cisco_ios_xe { namespace Cisco_IOS_XE_native { Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::Custom() : name{YType::str, "name"}, help{YType::str, "help"} { yang_name = "custom"; yang_parent_name = "application-group"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::~Custom() { } bool Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::has_data() const { if (is_presence_container) return true; return name.is_set || help.is_set; } bool Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || ydk::is_set(help.yfilter); } std::string Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/attribute/application-group/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "custom"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); if (help.is_set || is_set(help.yfilter)) leaf_name_data.push_back(help.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } if(value_path == "help") { help = value; help.value_namespace = name_space; help.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } if(value_path == "help") { help.yfilter = yfilter; } } bool Native::Ip::Nbar::Attribute::ApplicationGroup::Custom::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name" || name == "help") return true; return false; } Native::Ip::Nbar::Attribute::ApplicationSet::ApplicationSet() : custom(this, {"name"}) { yang_name = "application-set"; yang_parent_name = "attribute"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Attribute::ApplicationSet::~ApplicationSet() { } bool Native::Ip::Nbar::Attribute::ApplicationSet::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<custom.len(); index++) { if(custom[index]->has_data()) return true; } return false; } bool Native::Ip::Nbar::Attribute::ApplicationSet::has_operation() const { for (std::size_t index=0; index<custom.len(); index++) { if(custom[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Nbar::Attribute::ApplicationSet::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/attribute/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Attribute::ApplicationSet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "application-set"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Attribute::ApplicationSet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Attribute::ApplicationSet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "custom") { auto ent_ = std::make_shared<Native::Ip::Nbar::Attribute::ApplicationSet::Custom>(); ent_->parent = this; custom.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Attribute::ApplicationSet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : custom.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Nbar::Attribute::ApplicationSet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Attribute::ApplicationSet::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Attribute::ApplicationSet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "custom") return true; return false; } Native::Ip::Nbar::Attribute::ApplicationSet::Custom::Custom() : name{YType::str, "name"}, help{YType::str, "help"} { yang_name = "custom"; yang_parent_name = "application-set"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Attribute::ApplicationSet::Custom::~Custom() { } bool Native::Ip::Nbar::Attribute::ApplicationSet::Custom::has_data() const { if (is_presence_container) return true; return name.is_set || help.is_set; } bool Native::Ip::Nbar::Attribute::ApplicationSet::Custom::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || ydk::is_set(help.yfilter); } std::string Native::Ip::Nbar::Attribute::ApplicationSet::Custom::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/attribute/application-set/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Attribute::ApplicationSet::Custom::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "custom"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Attribute::ApplicationSet::Custom::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); if (help.is_set || is_set(help.yfilter)) leaf_name_data.push_back(help.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Attribute::ApplicationSet::Custom::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Attribute::ApplicationSet::Custom::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Attribute::ApplicationSet::Custom::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } if(value_path == "help") { help = value; help.value_namespace = name_space; help.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Attribute::ApplicationSet::Custom::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } if(value_path == "help") { help.yfilter = yfilter; } } bool Native::Ip::Nbar::Attribute::ApplicationSet::Custom::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name" || name == "help") return true; return false; } Native::Ip::Nbar::Attribute::Category::Category() : custom(this, {"name"}) { yang_name = "category"; yang_parent_name = "attribute"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Attribute::Category::~Category() { } bool Native::Ip::Nbar::Attribute::Category::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<custom.len(); index++) { if(custom[index]->has_data()) return true; } return false; } bool Native::Ip::Nbar::Attribute::Category::has_operation() const { for (std::size_t index=0; index<custom.len(); index++) { if(custom[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Nbar::Attribute::Category::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/attribute/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Attribute::Category::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "category"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Attribute::Category::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Attribute::Category::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "custom") { auto ent_ = std::make_shared<Native::Ip::Nbar::Attribute::Category::Custom>(); ent_->parent = this; custom.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Attribute::Category::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : custom.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Nbar::Attribute::Category::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Attribute::Category::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Attribute::Category::has_leaf_or_child_of_name(const std::string & name) const { if(name == "custom") return true; return false; } Native::Ip::Nbar::Attribute::Category::Custom::Custom() : name{YType::str, "name"}, help{YType::str, "help"} { yang_name = "custom"; yang_parent_name = "category"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Attribute::Category::Custom::~Custom() { } bool Native::Ip::Nbar::Attribute::Category::Custom::has_data() const { if (is_presence_container) return true; return name.is_set || help.is_set; } bool Native::Ip::Nbar::Attribute::Category::Custom::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || ydk::is_set(help.yfilter); } std::string Native::Ip::Nbar::Attribute::Category::Custom::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/attribute/category/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Attribute::Category::Custom::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "custom"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Attribute::Category::Custom::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); if (help.is_set || is_set(help.yfilter)) leaf_name_data.push_back(help.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Attribute::Category::Custom::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Attribute::Category::Custom::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Attribute::Category::Custom::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } if(value_path == "help") { help = value; help.value_namespace = name_space; help.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Attribute::Category::Custom::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } if(value_path == "help") { help.yfilter = yfilter; } } bool Native::Ip::Nbar::Attribute::Category::Custom::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name" || name == "help") return true; return false; } Native::Ip::Nbar::Attribute::SubCategory::SubCategory() : custom(this, {"name"}) { yang_name = "sub-category"; yang_parent_name = "attribute"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Attribute::SubCategory::~SubCategory() { } bool Native::Ip::Nbar::Attribute::SubCategory::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<custom.len(); index++) { if(custom[index]->has_data()) return true; } return false; } bool Native::Ip::Nbar::Attribute::SubCategory::has_operation() const { for (std::size_t index=0; index<custom.len(); index++) { if(custom[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Nbar::Attribute::SubCategory::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/attribute/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Attribute::SubCategory::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "sub-category"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Attribute::SubCategory::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Attribute::SubCategory::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "custom") { auto ent_ = std::make_shared<Native::Ip::Nbar::Attribute::SubCategory::Custom>(); ent_->parent = this; custom.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Attribute::SubCategory::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : custom.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Nbar::Attribute::SubCategory::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Attribute::SubCategory::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Attribute::SubCategory::has_leaf_or_child_of_name(const std::string & name) const { if(name == "custom") return true; return false; } Native::Ip::Nbar::Attribute::SubCategory::Custom::Custom() : name{YType::str, "name"}, help{YType::str, "help"} { yang_name = "custom"; yang_parent_name = "sub-category"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Attribute::SubCategory::Custom::~Custom() { } bool Native::Ip::Nbar::Attribute::SubCategory::Custom::has_data() const { if (is_presence_container) return true; return name.is_set || help.is_set; } bool Native::Ip::Nbar::Attribute::SubCategory::Custom::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || ydk::is_set(help.yfilter); } std::string Native::Ip::Nbar::Attribute::SubCategory::Custom::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/attribute/sub-category/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Attribute::SubCategory::Custom::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "custom"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Attribute::SubCategory::Custom::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); if (help.is_set || is_set(help.yfilter)) leaf_name_data.push_back(help.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Attribute::SubCategory::Custom::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Attribute::SubCategory::Custom::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Attribute::SubCategory::Custom::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } if(value_path == "help") { help = value; help.value_namespace = name_space; help.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Attribute::SubCategory::Custom::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } if(value_path == "help") { help.yfilter = yfilter; } } bool Native::Ip::Nbar::Attribute::SubCategory::Custom::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name" || name == "help") return true; return false; } Native::Ip::Nbar::AttributeMap::AttributeMap() : name{YType::str, "name"} , attribute(std::make_shared<Native::Ip::Nbar::AttributeMap::Attribute>()) { attribute->parent = this; yang_name = "attribute-map"; yang_parent_name = "nbar"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::AttributeMap::~AttributeMap() { } bool Native::Ip::Nbar::AttributeMap::has_data() const { if (is_presence_container) return true; return name.is_set || (attribute != nullptr && attribute->has_data()); } bool Native::Ip::Nbar::AttributeMap::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || (attribute != nullptr && attribute->has_operation()); } std::string Native::Ip::Nbar::AttributeMap::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::AttributeMap::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "attribute-map"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::AttributeMap::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::AttributeMap::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "attribute") { if(attribute == nullptr) { attribute = std::make_shared<Native::Ip::Nbar::AttributeMap::Attribute>(); } return attribute; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::AttributeMap::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(attribute != nullptr) { _children["attribute"] = attribute; } return _children; } void Native::Ip::Nbar::AttributeMap::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::AttributeMap::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Native::Ip::Nbar::AttributeMap::has_leaf_or_child_of_name(const std::string & name) const { if(name == "attribute" || name == "name") return true; return false; } Native::Ip::Nbar::AttributeMap::Attribute::Attribute() : application_group{YType::str, "application-group"}, application_set{YType::str, "application-set"}, business_relevance{YType::str, "business-relevance"}, category{YType::str, "category"}, encrypted{YType::str, "encrypted"}, sub_category{YType::str, "sub-category"}, traffic_class{YType::str, "traffic-class"}, tunnel{YType::str, "tunnel"} { yang_name = "attribute"; yang_parent_name = "attribute-map"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::AttributeMap::Attribute::~Attribute() { } bool Native::Ip::Nbar::AttributeMap::Attribute::has_data() const { if (is_presence_container) return true; return application_group.is_set || application_set.is_set || business_relevance.is_set || category.is_set || encrypted.is_set || sub_category.is_set || traffic_class.is_set || tunnel.is_set; } bool Native::Ip::Nbar::AttributeMap::Attribute::has_operation() const { return is_set(yfilter) || ydk::is_set(application_group.yfilter) || ydk::is_set(application_set.yfilter) || ydk::is_set(business_relevance.yfilter) || ydk::is_set(category.yfilter) || ydk::is_set(encrypted.yfilter) || ydk::is_set(sub_category.yfilter) || ydk::is_set(traffic_class.yfilter) || ydk::is_set(tunnel.yfilter); } std::string Native::Ip::Nbar::AttributeMap::Attribute::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "attribute"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::AttributeMap::Attribute::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (application_group.is_set || is_set(application_group.yfilter)) leaf_name_data.push_back(application_group.get_name_leafdata()); if (application_set.is_set || is_set(application_set.yfilter)) leaf_name_data.push_back(application_set.get_name_leafdata()); if (business_relevance.is_set || is_set(business_relevance.yfilter)) leaf_name_data.push_back(business_relevance.get_name_leafdata()); if (category.is_set || is_set(category.yfilter)) leaf_name_data.push_back(category.get_name_leafdata()); if (encrypted.is_set || is_set(encrypted.yfilter)) leaf_name_data.push_back(encrypted.get_name_leafdata()); if (sub_category.is_set || is_set(sub_category.yfilter)) leaf_name_data.push_back(sub_category.get_name_leafdata()); if (traffic_class.is_set || is_set(traffic_class.yfilter)) leaf_name_data.push_back(traffic_class.get_name_leafdata()); if (tunnel.is_set || is_set(tunnel.yfilter)) leaf_name_data.push_back(tunnel.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::AttributeMap::Attribute::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::AttributeMap::Attribute::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::AttributeMap::Attribute::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "application-group") { application_group = value; application_group.value_namespace = name_space; application_group.value_namespace_prefix = name_space_prefix; } if(value_path == "application-set") { application_set = value; application_set.value_namespace = name_space; application_set.value_namespace_prefix = name_space_prefix; } if(value_path == "business-relevance") { business_relevance = value; business_relevance.value_namespace = name_space; business_relevance.value_namespace_prefix = name_space_prefix; } if(value_path == "category") { category = value; category.value_namespace = name_space; category.value_namespace_prefix = name_space_prefix; } if(value_path == "encrypted") { encrypted = value; encrypted.value_namespace = name_space; encrypted.value_namespace_prefix = name_space_prefix; } if(value_path == "sub-category") { sub_category = value; sub_category.value_namespace = name_space; sub_category.value_namespace_prefix = name_space_prefix; } if(value_path == "traffic-class") { traffic_class = value; traffic_class.value_namespace = name_space; traffic_class.value_namespace_prefix = name_space_prefix; } if(value_path == "tunnel") { tunnel = value; tunnel.value_namespace = name_space; tunnel.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::AttributeMap::Attribute::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "application-group") { application_group.yfilter = yfilter; } if(value_path == "application-set") { application_set.yfilter = yfilter; } if(value_path == "business-relevance") { business_relevance.yfilter = yfilter; } if(value_path == "category") { category.yfilter = yfilter; } if(value_path == "encrypted") { encrypted.yfilter = yfilter; } if(value_path == "sub-category") { sub_category.yfilter = yfilter; } if(value_path == "traffic-class") { traffic_class.yfilter = yfilter; } if(value_path == "tunnel") { tunnel.yfilter = yfilter; } } bool Native::Ip::Nbar::AttributeMap::Attribute::has_leaf_or_child_of_name(const std::string & name) const { if(name == "application-group" || name == "application-set" || name == "business-relevance" || name == "category" || name == "encrypted" || name == "sub-category" || name == "traffic-class" || name == "tunnel") return true; return false; } Native::Ip::Nbar::AttributeSet::AttributeSet() : protocol_name{YType::str, "protocol-name"}, profile_name{YType::str, "profile-name"} { yang_name = "attribute-set"; yang_parent_name = "nbar"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::AttributeSet::~AttributeSet() { } bool Native::Ip::Nbar::AttributeSet::has_data() const { if (is_presence_container) return true; return protocol_name.is_set || profile_name.is_set; } bool Native::Ip::Nbar::AttributeSet::has_operation() const { return is_set(yfilter) || ydk::is_set(protocol_name.yfilter) || ydk::is_set(profile_name.yfilter); } std::string Native::Ip::Nbar::AttributeSet::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::AttributeSet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "attribute-set"; ADD_KEY_TOKEN(protocol_name, "protocol-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::AttributeSet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (protocol_name.is_set || is_set(protocol_name.yfilter)) leaf_name_data.push_back(protocol_name.get_name_leafdata()); if (profile_name.is_set || is_set(profile_name.yfilter)) leaf_name_data.push_back(profile_name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::AttributeSet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::AttributeSet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::AttributeSet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "protocol-name") { protocol_name = value; protocol_name.value_namespace = name_space; protocol_name.value_namespace_prefix = name_space_prefix; } if(value_path == "profile-name") { profile_name = value; profile_name.value_namespace = name_space; profile_name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::AttributeSet::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "protocol-name") { protocol_name.yfilter = yfilter; } if(value_path == "profile-name") { profile_name.yfilter = yfilter; } } bool Native::Ip::Nbar::AttributeSet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "protocol-name" || name == "profile-name") return true; return false; } Native::Ip::Nbar::Classification::Classification() : auto_learn(nullptr) // presence node , dns(std::make_shared<Native::Ip::Nbar::Classification::Dns>()) , granularity(std::make_shared<Native::Ip::Nbar::Classification::Granularity>()) , tunneled_traffic(std::make_shared<Native::Ip::Nbar::Classification::TunneledTraffic>()) { dns->parent = this; granularity->parent = this; tunneled_traffic->parent = this; yang_name = "classification"; yang_parent_name = "nbar"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::~Classification() { } bool Native::Ip::Nbar::Classification::has_data() const { if (is_presence_container) return true; return (auto_learn != nullptr && auto_learn->has_data()) || (dns != nullptr && dns->has_data()) || (granularity != nullptr && granularity->has_data()) || (tunneled_traffic != nullptr && tunneled_traffic->has_data()); } bool Native::Ip::Nbar::Classification::has_operation() const { return is_set(yfilter) || (auto_learn != nullptr && auto_learn->has_operation()) || (dns != nullptr && dns->has_operation()) || (granularity != nullptr && granularity->has_operation()) || (tunneled_traffic != nullptr && tunneled_traffic->has_operation()); } std::string Native::Ip::Nbar::Classification::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "classification"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "auto-learn") { if(auto_learn == nullptr) { auto_learn = std::make_shared<Native::Ip::Nbar::Classification::AutoLearn>(); } return auto_learn; } if(child_yang_name == "dns") { if(dns == nullptr) { dns = std::make_shared<Native::Ip::Nbar::Classification::Dns>(); } return dns; } if(child_yang_name == "granularity") { if(granularity == nullptr) { granularity = std::make_shared<Native::Ip::Nbar::Classification::Granularity>(); } return granularity; } if(child_yang_name == "tunneled-traffic") { if(tunneled_traffic == nullptr) { tunneled_traffic = std::make_shared<Native::Ip::Nbar::Classification::TunneledTraffic>(); } return tunneled_traffic; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(auto_learn != nullptr) { _children["auto-learn"] = auto_learn; } if(dns != nullptr) { _children["dns"] = dns; } if(granularity != nullptr) { _children["granularity"] = granularity; } if(tunneled_traffic != nullptr) { _children["tunneled-traffic"] = tunneled_traffic; } return _children; } void Native::Ip::Nbar::Classification::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Classification::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Classification::has_leaf_or_child_of_name(const std::string & name) const { if(name == "auto-learn" || name == "dns" || name == "granularity" || name == "tunneled-traffic") return true; return false; } Native::Ip::Nbar::Classification::AutoLearn::AutoLearn() : top_asymmetric_socket{YType::empty, "top-asymmetric-socket"} , top_hosts(nullptr) // presence node , top_ports(nullptr) // presence node { yang_name = "auto-learn"; yang_parent_name = "classification"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } Native::Ip::Nbar::Classification::AutoLearn::~AutoLearn() { } bool Native::Ip::Nbar::Classification::AutoLearn::has_data() const { if (is_presence_container) return true; return top_asymmetric_socket.is_set || (top_hosts != nullptr && top_hosts->has_data()) || (top_ports != nullptr && top_ports->has_data()); } bool Native::Ip::Nbar::Classification::AutoLearn::has_operation() const { return is_set(yfilter) || ydk::is_set(top_asymmetric_socket.yfilter) || (top_hosts != nullptr && top_hosts->has_operation()) || (top_ports != nullptr && top_ports->has_operation()); } std::string Native::Ip::Nbar::Classification::AutoLearn::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::AutoLearn::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "auto-learn"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::AutoLearn::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (top_asymmetric_socket.is_set || is_set(top_asymmetric_socket.yfilter)) leaf_name_data.push_back(top_asymmetric_socket.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::AutoLearn::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "top-hosts") { if(top_hosts == nullptr) { top_hosts = std::make_shared<Native::Ip::Nbar::Classification::AutoLearn::TopHosts>(); } return top_hosts; } if(child_yang_name == "top-ports") { if(top_ports == nullptr) { top_ports = std::make_shared<Native::Ip::Nbar::Classification::AutoLearn::TopPorts>(); } return top_ports; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::AutoLearn::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(top_hosts != nullptr) { _children["top-hosts"] = top_hosts; } if(top_ports != nullptr) { _children["top-ports"] = top_ports; } return _children; } void Native::Ip::Nbar::Classification::AutoLearn::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "top-asymmetric-socket") { top_asymmetric_socket = value; top_asymmetric_socket.value_namespace = name_space; top_asymmetric_socket.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::AutoLearn::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "top-asymmetric-socket") { top_asymmetric_socket.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::AutoLearn::has_leaf_or_child_of_name(const std::string & name) const { if(name == "top-hosts" || name == "top-ports" || name == "top-asymmetric-socket") return true; return false; } Native::Ip::Nbar::Classification::AutoLearn::TopHosts::TopHosts() : sample_rate{YType::uint16, "sample-rate"} { yang_name = "top-hosts"; yang_parent_name = "auto-learn"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } Native::Ip::Nbar::Classification::AutoLearn::TopHosts::~TopHosts() { } bool Native::Ip::Nbar::Classification::AutoLearn::TopHosts::has_data() const { if (is_presence_container) return true; return sample_rate.is_set; } bool Native::Ip::Nbar::Classification::AutoLearn::TopHosts::has_operation() const { return is_set(yfilter) || ydk::is_set(sample_rate.yfilter); } std::string Native::Ip::Nbar::Classification::AutoLearn::TopHosts::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/auto-learn/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::AutoLearn::TopHosts::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "top-hosts"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::AutoLearn::TopHosts::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (sample_rate.is_set || is_set(sample_rate.yfilter)) leaf_name_data.push_back(sample_rate.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::AutoLearn::TopHosts::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::AutoLearn::TopHosts::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::AutoLearn::TopHosts::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "sample-rate") { sample_rate = value; sample_rate.value_namespace = name_space; sample_rate.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::AutoLearn::TopHosts::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "sample-rate") { sample_rate.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::AutoLearn::TopHosts::has_leaf_or_child_of_name(const std::string & name) const { if(name == "sample-rate") return true; return false; } Native::Ip::Nbar::Classification::AutoLearn::TopPorts::TopPorts() : sample_rate{YType::uint16, "sample-rate"} { yang_name = "top-ports"; yang_parent_name = "auto-learn"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } Native::Ip::Nbar::Classification::AutoLearn::TopPorts::~TopPorts() { } bool Native::Ip::Nbar::Classification::AutoLearn::TopPorts::has_data() const { if (is_presence_container) return true; return sample_rate.is_set; } bool Native::Ip::Nbar::Classification::AutoLearn::TopPorts::has_operation() const { return is_set(yfilter) || ydk::is_set(sample_rate.yfilter); } std::string Native::Ip::Nbar::Classification::AutoLearn::TopPorts::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/auto-learn/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::AutoLearn::TopPorts::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "top-ports"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::AutoLearn::TopPorts::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (sample_rate.is_set || is_set(sample_rate.yfilter)) leaf_name_data.push_back(sample_rate.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::AutoLearn::TopPorts::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::AutoLearn::TopPorts::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::AutoLearn::TopPorts::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "sample-rate") { sample_rate = value; sample_rate.value_namespace = name_space; sample_rate.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::AutoLearn::TopPorts::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "sample-rate") { sample_rate.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::AutoLearn::TopPorts::has_leaf_or_child_of_name(const std::string & name) const { if(name == "sample-rate") return true; return false; } Native::Ip::Nbar::Classification::Dns::Dns() : classify_by_domain{YType::empty, "classify-by-domain"} , learning(nullptr) // presence node { yang_name = "dns"; yang_parent_name = "classification"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Dns::~Dns() { } bool Native::Ip::Nbar::Classification::Dns::has_data() const { if (is_presence_container) return true; return classify_by_domain.is_set || (learning != nullptr && learning->has_data()); } bool Native::Ip::Nbar::Classification::Dns::has_operation() const { return is_set(yfilter) || ydk::is_set(classify_by_domain.yfilter) || (learning != nullptr && learning->has_operation()); } std::string Native::Ip::Nbar::Classification::Dns::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Dns::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dns"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Dns::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (classify_by_domain.is_set || is_set(classify_by_domain.yfilter)) leaf_name_data.push_back(classify_by_domain.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Dns::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "learning") { if(learning == nullptr) { learning = std::make_shared<Native::Ip::Nbar::Classification::Dns::Learning>(); } return learning; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Dns::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(learning != nullptr) { _children["learning"] = learning; } return _children; } void Native::Ip::Nbar::Classification::Dns::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "classify-by-domain") { classify_by_domain = value; classify_by_domain.value_namespace = name_space; classify_by_domain.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Dns::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "classify-by-domain") { classify_by_domain.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Dns::has_leaf_or_child_of_name(const std::string & name) const { if(name == "learning" || name == "classify-by-domain") return true; return false; } Native::Ip::Nbar::Classification::Dns::Learning::Learning() : guard{YType::empty, "guard"} { yang_name = "learning"; yang_parent_name = "dns"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } Native::Ip::Nbar::Classification::Dns::Learning::~Learning() { } bool Native::Ip::Nbar::Classification::Dns::Learning::has_data() const { if (is_presence_container) return true; return guard.is_set; } bool Native::Ip::Nbar::Classification::Dns::Learning::has_operation() const { return is_set(yfilter) || ydk::is_set(guard.yfilter); } std::string Native::Ip::Nbar::Classification::Dns::Learning::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/dns/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Dns::Learning::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "learning"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Dns::Learning::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (guard.is_set || is_set(guard.yfilter)) leaf_name_data.push_back(guard.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Dns::Learning::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Dns::Learning::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::Dns::Learning::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "guard") { guard = value; guard.value_namespace = name_space; guard.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Dns::Learning::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "guard") { guard.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Dns::Learning::has_leaf_or_child_of_name(const std::string & name) const { if(name == "guard") return true; return false; } Native::Ip::Nbar::Classification::Granularity::Granularity() : coarse_grain{YType::empty, "coarse-grain"} , fine_grain(nullptr) // presence node { yang_name = "granularity"; yang_parent_name = "classification"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::~Granularity() { } bool Native::Ip::Nbar::Classification::Granularity::has_data() const { if (is_presence_container) return true; return coarse_grain.is_set || (fine_grain != nullptr && fine_grain->has_data()); } bool Native::Ip::Nbar::Classification::Granularity::has_operation() const { return is_set(yfilter) || ydk::is_set(coarse_grain.yfilter) || (fine_grain != nullptr && fine_grain->has_operation()); } std::string Native::Ip::Nbar::Classification::Granularity::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "granularity"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (coarse_grain.is_set || is_set(coarse_grain.yfilter)) leaf_name_data.push_back(coarse_grain.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "fine-grain") { if(fine_grain == nullptr) { fine_grain = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain>(); } return fine_grain; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(fine_grain != nullptr) { _children["fine-grain"] = fine_grain; } return _children; } void Native::Ip::Nbar::Classification::Granularity::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "coarse-grain") { coarse_grain = value; coarse_grain.value_namespace = name_space; coarse_grain.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Granularity::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "coarse-grain") { coarse_grain.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Granularity::has_leaf_or_child_of_name(const std::string & name) const { if(name == "fine-grain" || name == "coarse-grain") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::FineGrain() : attribute(std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute>()) , protocol(std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol>()) { attribute->parent = this; protocol->parent = this; yang_name = "fine-grain"; yang_parent_name = "granularity"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } Native::Ip::Nbar::Classification::Granularity::FineGrain::~FineGrain() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::has_data() const { if (is_presence_container) return true; return (attribute != nullptr && attribute->has_data()) || (protocol != nullptr && protocol->has_data()); } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::has_operation() const { return is_set(yfilter) || (attribute != nullptr && attribute->has_operation()) || (protocol != nullptr && protocol->has_operation()); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "fine-grain"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "attribute") { if(attribute == nullptr) { attribute = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute>(); } return attribute; } if(child_yang_name == "protocol") { if(protocol == nullptr) { protocol = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol>(); } return protocol; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(attribute != nullptr) { _children["attribute"] = attribute; } if(protocol != nullptr) { _children["protocol"] = protocol; } return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Classification::Granularity::FineGrain::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::has_leaf_or_child_of_name(const std::string & name) const { if(name == "attribute" || name == "protocol") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Attribute() : application_group(this, {"name"}) , application_set(this, {"name"}) , business_relevance(this, {"name"}) , category(this, {"name"}) , encrypted(this, {"name"}) , sub_category(this, {"name"}) , traffic_class(this, {"name"}) , tunnel(this, {"name"}) { yang_name = "attribute"; yang_parent_name = "fine-grain"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::~Attribute() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<application_group.len(); index++) { if(application_group[index]->has_data()) return true; } for (std::size_t index=0; index<application_set.len(); index++) { if(application_set[index]->has_data()) return true; } for (std::size_t index=0; index<business_relevance.len(); index++) { if(business_relevance[index]->has_data()) return true; } for (std::size_t index=0; index<category.len(); index++) { if(category[index]->has_data()) return true; } for (std::size_t index=0; index<encrypted.len(); index++) { if(encrypted[index]->has_data()) return true; } for (std::size_t index=0; index<sub_category.len(); index++) { if(sub_category[index]->has_data()) return true; } for (std::size_t index=0; index<traffic_class.len(); index++) { if(traffic_class[index]->has_data()) return true; } for (std::size_t index=0; index<tunnel.len(); index++) { if(tunnel[index]->has_data()) return true; } return false; } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::has_operation() const { for (std::size_t index=0; index<application_group.len(); index++) { if(application_group[index]->has_operation()) return true; } for (std::size_t index=0; index<application_set.len(); index++) { if(application_set[index]->has_operation()) return true; } for (std::size_t index=0; index<business_relevance.len(); index++) { if(business_relevance[index]->has_operation()) return true; } for (std::size_t index=0; index<category.len(); index++) { if(category[index]->has_operation()) return true; } for (std::size_t index=0; index<encrypted.len(); index++) { if(encrypted[index]->has_operation()) return true; } for (std::size_t index=0; index<sub_category.len(); index++) { if(sub_category[index]->has_operation()) return true; } for (std::size_t index=0; index<traffic_class.len(); index++) { if(traffic_class[index]->has_operation()) return true; } for (std::size_t index=0; index<tunnel.len(); index++) { if(tunnel[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/fine-grain/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "attribute"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "application-group") { auto ent_ = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup>(); ent_->parent = this; application_group.append(ent_); return ent_; } if(child_yang_name == "application-set") { auto ent_ = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet>(); ent_->parent = this; application_set.append(ent_); return ent_; } if(child_yang_name == "business-relevance") { auto ent_ = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance>(); ent_->parent = this; business_relevance.append(ent_); return ent_; } if(child_yang_name == "category") { auto ent_ = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category>(); ent_->parent = this; category.append(ent_); return ent_; } if(child_yang_name == "encrypted") { auto ent_ = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted>(); ent_->parent = this; encrypted.append(ent_); return ent_; } if(child_yang_name == "sub-category") { auto ent_ = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory>(); ent_->parent = this; sub_category.append(ent_); return ent_; } if(child_yang_name == "traffic-class") { auto ent_ = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass>(); ent_->parent = this; traffic_class.append(ent_); return ent_; } if(child_yang_name == "tunnel") { auto ent_ = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel>(); ent_->parent = this; tunnel.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : application_group.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } count_ = 0; for (auto ent_ : application_set.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } count_ = 0; for (auto ent_ : business_relevance.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } count_ = 0; for (auto ent_ : category.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } count_ = 0; for (auto ent_ : encrypted.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } count_ = 0; for (auto ent_ : sub_category.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } count_ = 0; for (auto ent_ : traffic_class.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } count_ = 0; for (auto ent_ : tunnel.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::has_leaf_or_child_of_name(const std::string & name) const { if(name == "application-group" || name == "application-set" || name == "business-relevance" || name == "category" || name == "encrypted" || name == "sub-category" || name == "traffic-class" || name == "tunnel") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::ApplicationGroup() : name{YType::str, "name"} { yang_name = "application-group"; yang_parent_name = "attribute"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::~ApplicationGroup() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::has_data() const { if (is_presence_container) return true; return name.is_set; } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/fine-grain/attribute/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "application-group"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationGroup::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::ApplicationSet() : name{YType::str, "name"} { yang_name = "application-set"; yang_parent_name = "attribute"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::~ApplicationSet() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::has_data() const { if (is_presence_container) return true; return name.is_set; } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/fine-grain/attribute/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "application-set"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::ApplicationSet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::BusinessRelevance() : name{YType::str, "name"} { yang_name = "business-relevance"; yang_parent_name = "attribute"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::~BusinessRelevance() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::has_data() const { if (is_presence_container) return true; return name.is_set; } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/fine-grain/attribute/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "business-relevance"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::BusinessRelevance::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::Category() : name{YType::str, "name"} { yang_name = "category"; yang_parent_name = "attribute"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::~Category() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::has_data() const { if (is_presence_container) return true; return name.is_set; } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/fine-grain/attribute/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "category"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Category::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::Encrypted() : name{YType::str, "name"} { yang_name = "encrypted"; yang_parent_name = "attribute"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::~Encrypted() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::has_data() const { if (is_presence_container) return true; return name.is_set; } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/fine-grain/attribute/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "encrypted"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Encrypted::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::SubCategory() : name{YType::str, "name"} { yang_name = "sub-category"; yang_parent_name = "attribute"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::~SubCategory() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::has_data() const { if (is_presence_container) return true; return name.is_set; } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/fine-grain/attribute/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "sub-category"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::SubCategory::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::TrafficClass() : name{YType::str, "name"} { yang_name = "traffic-class"; yang_parent_name = "attribute"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::~TrafficClass() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::has_data() const { if (is_presence_container) return true; return name.is_set; } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/fine-grain/attribute/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "traffic-class"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::TrafficClass::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::Tunnel() : name{YType::str, "name"} { yang_name = "tunnel"; yang_parent_name = "attribute"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::~Tunnel() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::has_data() const { if (is_presence_container) return true; return name.is_set; } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/fine-grain/attribute/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "tunnel"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Attribute::Tunnel::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::Protocol() : protocols_list(this, {"name"}) { yang_name = "protocol"; yang_parent_name = "fine-grain"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::~Protocol() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<protocols_list.len(); index++) { if(protocols_list[index]->has_data()) return true; } return false; } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::has_operation() const { for (std::size_t index=0; index<protocols_list.len(); index++) { if(protocols_list[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/fine-grain/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "protocol"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "protocols-list") { auto ent_ = std::make_shared<Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList>(); ent_->parent = this; protocols_list.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : protocols_list.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::has_leaf_or_child_of_name(const std::string & name) const { if(name == "protocols-list") return true; return false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::ProtocolsList() : name{YType::str, "name"} { yang_name = "protocols-list"; yang_parent_name = "protocol"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::~ProtocolsList() { } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::has_data() const { if (is_presence_container) return true; return name.is_set; } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/granularity/fine-grain/protocol/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "protocols-list"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::Granularity::FineGrain::Protocol::ProtocolsList::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name") return true; return false; } Native::Ip::Nbar::Classification::TunneledTraffic::TunneledTraffic() : capwap{YType::empty, "capwap"}, ipv6inip{YType::empty, "ipv6inip"}, teredo{YType::empty, "teredo"} { yang_name = "tunneled-traffic"; yang_parent_name = "classification"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Classification::TunneledTraffic::~TunneledTraffic() { } bool Native::Ip::Nbar::Classification::TunneledTraffic::has_data() const { if (is_presence_container) return true; return capwap.is_set || ipv6inip.is_set || teredo.is_set; } bool Native::Ip::Nbar::Classification::TunneledTraffic::has_operation() const { return is_set(yfilter) || ydk::is_set(capwap.yfilter) || ydk::is_set(ipv6inip.yfilter) || ydk::is_set(teredo.yfilter); } std::string Native::Ip::Nbar::Classification::TunneledTraffic::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/classification/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Classification::TunneledTraffic::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "tunneled-traffic"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Classification::TunneledTraffic::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (capwap.is_set || is_set(capwap.yfilter)) leaf_name_data.push_back(capwap.get_name_leafdata()); if (ipv6inip.is_set || is_set(ipv6inip.yfilter)) leaf_name_data.push_back(ipv6inip.get_name_leafdata()); if (teredo.is_set || is_set(teredo.yfilter)) leaf_name_data.push_back(teredo.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Classification::TunneledTraffic::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Classification::TunneledTraffic::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Classification::TunneledTraffic::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "capwap") { capwap = value; capwap.value_namespace = name_space; capwap.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6inip") { ipv6inip = value; ipv6inip.value_namespace = name_space; ipv6inip.value_namespace_prefix = name_space_prefix; } if(value_path == "teredo") { teredo = value; teredo.value_namespace = name_space; teredo.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Classification::TunneledTraffic::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "capwap") { capwap.yfilter = yfilter; } if(value_path == "ipv6inip") { ipv6inip.yfilter = yfilter; } if(value_path == "teredo") { teredo.yfilter = yfilter; } } bool Native::Ip::Nbar::Classification::TunneledTraffic::has_leaf_or_child_of_name(const std::string & name) const { if(name == "capwap" || name == "ipv6inip" || name == "teredo") return true; return false; } Native::Ip::Nbar::Custom::Custom() : name{YType::str, "name"} , composite(std::make_shared<Native::Ip::Nbar::Custom::Composite>()) , dns(std::make_shared<Native::Ip::Nbar::Custom::Dns>()) , http(std::make_shared<Native::Ip::Nbar::Custom::Http>()) , ssl(std::make_shared<Native::Ip::Nbar::Custom::Ssl>()) , transport(std::make_shared<Native::Ip::Nbar::Custom::Transport>()) , ip(std::make_shared<Native::Ip::Nbar::Custom::Ip_>()) { composite->parent = this; dns->parent = this; http->parent = this; ssl->parent = this; transport->parent = this; ip->parent = this; yang_name = "custom"; yang_parent_name = "nbar"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::Custom::~Custom() { } bool Native::Ip::Nbar::Custom::has_data() const { if (is_presence_container) return true; return name.is_set || (composite != nullptr && composite->has_data()) || (dns != nullptr && dns->has_data()) || (http != nullptr && http->has_data()) || (ssl != nullptr && ssl->has_data()) || (transport != nullptr && transport->has_data()) || (ip != nullptr && ip->has_data()); } bool Native::Ip::Nbar::Custom::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || (composite != nullptr && composite->has_operation()) || (dns != nullptr && dns->has_operation()) || (http != nullptr && http->has_operation()) || (ssl != nullptr && ssl->has_operation()) || (transport != nullptr && transport->has_operation()) || (ip != nullptr && ip->has_operation()); } std::string Native::Ip::Nbar::Custom::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::Custom::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "custom"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "composite") { if(composite == nullptr) { composite = std::make_shared<Native::Ip::Nbar::Custom::Composite>(); } return composite; } if(child_yang_name == "dns") { if(dns == nullptr) { dns = std::make_shared<Native::Ip::Nbar::Custom::Dns>(); } return dns; } if(child_yang_name == "http") { if(http == nullptr) { http = std::make_shared<Native::Ip::Nbar::Custom::Http>(); } return http; } if(child_yang_name == "ssl") { if(ssl == nullptr) { ssl = std::make_shared<Native::Ip::Nbar::Custom::Ssl>(); } return ssl; } if(child_yang_name == "transport") { if(transport == nullptr) { transport = std::make_shared<Native::Ip::Nbar::Custom::Transport>(); } return transport; } if(child_yang_name == "ip") { if(ip == nullptr) { ip = std::make_shared<Native::Ip::Nbar::Custom::Ip_>(); } return ip; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(composite != nullptr) { _children["composite"] = composite; } if(dns != nullptr) { _children["dns"] = dns; } if(http != nullptr) { _children["http"] = http; } if(ssl != nullptr) { _children["ssl"] = ssl; } if(transport != nullptr) { _children["transport"] = transport; } if(ip != nullptr) { _children["ip"] = ip; } return _children; } void Native::Ip::Nbar::Custom::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::has_leaf_or_child_of_name(const std::string & name) const { if(name == "composite" || name == "dns" || name == "http" || name == "ssl" || name == "transport" || name == "ip" || name == "name") return true; return false; } Native::Ip::Nbar::Custom::Composite::Composite() : server_name(this, {"name"}) { yang_name = "composite"; yang_parent_name = "custom"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Composite::~Composite() { } bool Native::Ip::Nbar::Custom::Composite::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<server_name.len(); index++) { if(server_name[index]->has_data()) return true; } return false; } bool Native::Ip::Nbar::Custom::Composite::has_operation() const { for (std::size_t index=0; index<server_name.len(); index++) { if(server_name[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Nbar::Custom::Composite::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "composite"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Composite::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Composite::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "server-name") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Composite::ServerName>(); ent_->parent = this; server_name.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Composite::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : server_name.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Nbar::Custom::Composite::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Composite::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Composite::has_leaf_or_child_of_name(const std::string & name) const { if(name == "server-name") return true; return false; } Native::Ip::Nbar::Custom::Composite::ServerName::ServerName() : name{YType::str, "name"}, id{YType::uint16, "id"}, extends{YType::str, "extends"} { yang_name = "server-name"; yang_parent_name = "composite"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Composite::ServerName::~ServerName() { } bool Native::Ip::Nbar::Custom::Composite::ServerName::has_data() const { if (is_presence_container) return true; return name.is_set || id.is_set || extends.is_set; } bool Native::Ip::Nbar::Custom::Composite::ServerName::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || ydk::is_set(id.yfilter) || ydk::is_set(extends.yfilter); } std::string Native::Ip::Nbar::Custom::Composite::ServerName::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "server-name"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Composite::ServerName::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); if (id.is_set || is_set(id.yfilter)) leaf_name_data.push_back(id.get_name_leafdata()); if (extends.is_set || is_set(extends.yfilter)) leaf_name_data.push_back(extends.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Composite::ServerName::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Composite::ServerName::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Composite::ServerName::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } if(value_path == "id") { id = value; id.value_namespace = name_space; id.value_namespace_prefix = name_space_prefix; } if(value_path == "extends") { extends = value; extends.value_namespace = name_space; extends.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Composite::ServerName::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } if(value_path == "id") { id.yfilter = yfilter; } if(value_path == "extends") { extends.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Composite::ServerName::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name" || name == "id" || name == "extends") return true; return false; } Native::Ip::Nbar::Custom::Dns::Dns() : domain_name(this, {"name"}) { yang_name = "dns"; yang_parent_name = "custom"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Dns::~Dns() { } bool Native::Ip::Nbar::Custom::Dns::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<domain_name.len(); index++) { if(domain_name[index]->has_data()) return true; } return false; } bool Native::Ip::Nbar::Custom::Dns::has_operation() const { for (std::size_t index=0; index<domain_name.len(); index++) { if(domain_name[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Nbar::Custom::Dns::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dns"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Dns::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Dns::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "domain-name") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Dns::DomainName>(); ent_->parent = this; domain_name.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Dns::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : domain_name.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Nbar::Custom::Dns::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Dns::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Dns::has_leaf_or_child_of_name(const std::string & name) const { if(name == "domain-name") return true; return false; } Native::Ip::Nbar::Custom::Dns::DomainName::DomainName() : name{YType::str, "name"}, id{YType::uint16, "id"}, extends{YType::str, "extends"} { yang_name = "domain-name"; yang_parent_name = "dns"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Dns::DomainName::~DomainName() { } bool Native::Ip::Nbar::Custom::Dns::DomainName::has_data() const { if (is_presence_container) return true; return name.is_set || id.is_set || extends.is_set; } bool Native::Ip::Nbar::Custom::Dns::DomainName::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || ydk::is_set(id.yfilter) || ydk::is_set(extends.yfilter); } std::string Native::Ip::Nbar::Custom::Dns::DomainName::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "domain-name"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Dns::DomainName::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); if (id.is_set || is_set(id.yfilter)) leaf_name_data.push_back(id.get_name_leafdata()); if (extends.is_set || is_set(extends.yfilter)) leaf_name_data.push_back(extends.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Dns::DomainName::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Dns::DomainName::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Dns::DomainName::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } if(value_path == "id") { id = value; id.value_namespace = name_space; id.value_namespace_prefix = name_space_prefix; } if(value_path == "extends") { extends = value; extends.value_namespace = name_space; extends.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Dns::DomainName::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } if(value_path == "id") { id.yfilter = yfilter; } if(value_path == "extends") { extends.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Dns::DomainName::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name" || name == "id" || name == "extends") return true; return false; } Native::Ip::Nbar::Custom::Http::Http() : cookie{YType::str, "cookie"}, host{YType::str, "host"}, method{YType::str, "method"}, referer{YType::str, "referer"}, url{YType::str, "url"}, user_agent{YType::str, "user-agent"}, version{YType::str, "version"}, via{YType::str, "via"}, id{YType::uint16, "id"} { yang_name = "http"; yang_parent_name = "custom"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Http::~Http() { } bool Native::Ip::Nbar::Custom::Http::has_data() const { if (is_presence_container) return true; return cookie.is_set || host.is_set || method.is_set || referer.is_set || url.is_set || user_agent.is_set || version.is_set || via.is_set || id.is_set; } bool Native::Ip::Nbar::Custom::Http::has_operation() const { return is_set(yfilter) || ydk::is_set(cookie.yfilter) || ydk::is_set(host.yfilter) || ydk::is_set(method.yfilter) || ydk::is_set(referer.yfilter) || ydk::is_set(url.yfilter) || ydk::is_set(user_agent.yfilter) || ydk::is_set(version.yfilter) || ydk::is_set(via.yfilter) || ydk::is_set(id.yfilter); } std::string Native::Ip::Nbar::Custom::Http::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "http"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Http::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (cookie.is_set || is_set(cookie.yfilter)) leaf_name_data.push_back(cookie.get_name_leafdata()); if (host.is_set || is_set(host.yfilter)) leaf_name_data.push_back(host.get_name_leafdata()); if (method.is_set || is_set(method.yfilter)) leaf_name_data.push_back(method.get_name_leafdata()); if (referer.is_set || is_set(referer.yfilter)) leaf_name_data.push_back(referer.get_name_leafdata()); if (url.is_set || is_set(url.yfilter)) leaf_name_data.push_back(url.get_name_leafdata()); if (user_agent.is_set || is_set(user_agent.yfilter)) leaf_name_data.push_back(user_agent.get_name_leafdata()); if (version.is_set || is_set(version.yfilter)) leaf_name_data.push_back(version.get_name_leafdata()); if (via.is_set || is_set(via.yfilter)) leaf_name_data.push_back(via.get_name_leafdata()); if (id.is_set || is_set(id.yfilter)) leaf_name_data.push_back(id.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Http::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Http::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Http::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "cookie") { cookie = value; cookie.value_namespace = name_space; cookie.value_namespace_prefix = name_space_prefix; } if(value_path == "host") { host = value; host.value_namespace = name_space; host.value_namespace_prefix = name_space_prefix; } if(value_path == "method") { method = value; method.value_namespace = name_space; method.value_namespace_prefix = name_space_prefix; } if(value_path == "referer") { referer = value; referer.value_namespace = name_space; referer.value_namespace_prefix = name_space_prefix; } if(value_path == "url") { url = value; url.value_namespace = name_space; url.value_namespace_prefix = name_space_prefix; } if(value_path == "user-agent") { user_agent = value; user_agent.value_namespace = name_space; user_agent.value_namespace_prefix = name_space_prefix; } if(value_path == "version") { version = value; version.value_namespace = name_space; version.value_namespace_prefix = name_space_prefix; } if(value_path == "via") { via = value; via.value_namespace = name_space; via.value_namespace_prefix = name_space_prefix; } if(value_path == "id") { id = value; id.value_namespace = name_space; id.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Http::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "cookie") { cookie.yfilter = yfilter; } if(value_path == "host") { host.yfilter = yfilter; } if(value_path == "method") { method.yfilter = yfilter; } if(value_path == "referer") { referer.yfilter = yfilter; } if(value_path == "url") { url.yfilter = yfilter; } if(value_path == "user-agent") { user_agent.yfilter = yfilter; } if(value_path == "version") { version.yfilter = yfilter; } if(value_path == "via") { via.yfilter = yfilter; } if(value_path == "id") { id.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Http::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cookie" || name == "host" || name == "method" || name == "referer" || name == "url" || name == "user-agent" || name == "version" || name == "via" || name == "id") return true; return false; } Native::Ip::Nbar::Custom::Ssl::Ssl() : unique_name(this, {"name"}) { yang_name = "ssl"; yang_parent_name = "custom"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ssl::~Ssl() { } bool Native::Ip::Nbar::Custom::Ssl::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<unique_name.len(); index++) { if(unique_name[index]->has_data()) return true; } return false; } bool Native::Ip::Nbar::Custom::Ssl::has_operation() const { for (std::size_t index=0; index<unique_name.len(); index++) { if(unique_name[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Nbar::Custom::Ssl::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ssl"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ssl::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ssl::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "unique-name") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Ssl::UniqueName>(); ent_->parent = this; unique_name.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ssl::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : unique_name.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Nbar::Custom::Ssl::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Ssl::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Ssl::has_leaf_or_child_of_name(const std::string & name) const { if(name == "unique-name") return true; return false; } Native::Ip::Nbar::Custom::Ssl::UniqueName::UniqueName() : name{YType::str, "name"}, id{YType::uint16, "id"} { yang_name = "unique-name"; yang_parent_name = "ssl"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ssl::UniqueName::~UniqueName() { } bool Native::Ip::Nbar::Custom::Ssl::UniqueName::has_data() const { if (is_presence_container) return true; return name.is_set || id.is_set; } bool Native::Ip::Nbar::Custom::Ssl::UniqueName::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || ydk::is_set(id.yfilter); } std::string Native::Ip::Nbar::Custom::Ssl::UniqueName::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "unique-name"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ssl::UniqueName::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); if (id.is_set || is_set(id.yfilter)) leaf_name_data.push_back(id.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ssl::UniqueName::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ssl::UniqueName::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Ssl::UniqueName::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } if(value_path == "id") { id = value; id.value_namespace = name_space; id.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Ssl::UniqueName::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } if(value_path == "id") { id.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Ssl::UniqueName::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name" || name == "id") return true; return false; } Native::Ip::Nbar::Custom::Transport::Transport() : tcp(nullptr) // presence node , udp(nullptr) // presence node , udp_tcp(nullptr) // presence node { yang_name = "transport"; yang_parent_name = "custom"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::~Transport() { } bool Native::Ip::Nbar::Custom::Transport::has_data() const { if (is_presence_container) return true; return (tcp != nullptr && tcp->has_data()) || (udp != nullptr && udp->has_data()) || (udp_tcp != nullptr && udp_tcp->has_data()); } bool Native::Ip::Nbar::Custom::Transport::has_operation() const { return is_set(yfilter) || (tcp != nullptr && tcp->has_operation()) || (udp != nullptr && udp->has_operation()) || (udp_tcp != nullptr && udp_tcp->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "transport"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "tcp") { if(tcp == nullptr) { tcp = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp>(); } return tcp; } if(child_yang_name == "udp") { if(udp == nullptr) { udp = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp>(); } return udp; } if(child_yang_name == "udp-tcp") { if(udp_tcp == nullptr) { udp_tcp = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp>(); } return udp_tcp; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(tcp != nullptr) { _children["tcp"] = tcp; } if(udp != nullptr) { _children["udp"] = udp; } if(udp_tcp != nullptr) { _children["udp-tcp"] = udp_tcp; } return _children; } void Native::Ip::Nbar::Custom::Transport::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Transport::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Transport::has_leaf_or_child_of_name(const std::string & name) const { if(name == "tcp" || name == "udp" || name == "udp-tcp") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Tcp() : id{YType::uint16, "id"} , dscp(std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Dscp>()) , ip(std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Ip_>()) , ipv6(std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6>()) , direction(std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Direction>()) , port(std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Port>()) { dscp->parent = this; ip->parent = this; ipv6->parent = this; direction->parent = this; port->parent = this; yang_name = "tcp"; yang_parent_name = "transport"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Native::Ip::Nbar::Custom::Transport::Tcp::~Tcp() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::has_data() const { if (is_presence_container) return true; return id.is_set || (dscp != nullptr && dscp->has_data()) || (ip != nullptr && ip->has_data()) || (ipv6 != nullptr && ipv6->has_data()) || (direction != nullptr && direction->has_data()) || (port != nullptr && port->has_data()); } bool Native::Ip::Nbar::Custom::Transport::Tcp::has_operation() const { return is_set(yfilter) || ydk::is_set(id.yfilter) || (dscp != nullptr && dscp->has_operation()) || (ip != nullptr && ip->has_operation()) || (ipv6 != nullptr && ipv6->has_operation()) || (direction != nullptr && direction->has_operation()) || (port != nullptr && port->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "tcp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (id.is_set || is_set(id.yfilter)) leaf_name_data.push_back(id.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dscp") { if(dscp == nullptr) { dscp = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Dscp>(); } return dscp; } if(child_yang_name == "ip") { if(ip == nullptr) { ip = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Ip_>(); } return ip; } if(child_yang_name == "ipv6") { if(ipv6 == nullptr) { ipv6 = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6>(); } return ipv6; } if(child_yang_name == "direction") { if(direction == nullptr) { direction = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Direction>(); } return direction; } if(child_yang_name == "port") { if(port == nullptr) { port = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Port>(); } return port; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(dscp != nullptr) { _children["dscp"] = dscp; } if(ip != nullptr) { _children["ip"] = ip; } if(ipv6 != nullptr) { _children["ipv6"] = ipv6; } if(direction != nullptr) { _children["direction"] = direction; } if(port != nullptr) { _children["port"] = port; } return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "id") { id = value; id.value_namespace = name_space; id.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Tcp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "id") { id.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Tcp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dscp" || name == "ip" || name == "ipv6" || name == "direction" || name == "port" || name == "id") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Dscp::Dscp() : range{YType::uint8, "range"}, af11{YType::empty, "af11"}, af12{YType::empty, "af12"}, af13{YType::empty, "af13"}, af21{YType::empty, "af21"}, af22{YType::empty, "af22"}, af23{YType::empty, "af23"}, af31{YType::empty, "af31"}, af32{YType::empty, "af32"}, af33{YType::empty, "af33"}, af41{YType::empty, "af41"}, af42{YType::empty, "af42"}, af43{YType::empty, "af43"}, cs1{YType::empty, "cs1"}, cs2{YType::empty, "cs2"}, cs3{YType::empty, "cs3"}, cs4{YType::empty, "cs4"}, cs5{YType::empty, "cs5"}, cs6{YType::empty, "cs6"}, cs7{YType::empty, "cs7"}, default_{YType::empty, "default"}, ef{YType::empty, "ef"} { yang_name = "dscp"; yang_parent_name = "tcp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Tcp::Dscp::~Dscp() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Dscp::has_data() const { if (is_presence_container) return true; return range.is_set || af11.is_set || af12.is_set || af13.is_set || af21.is_set || af22.is_set || af23.is_set || af31.is_set || af32.is_set || af33.is_set || af41.is_set || af42.is_set || af43.is_set || cs1.is_set || cs2.is_set || cs3.is_set || cs4.is_set || cs5.is_set || cs6.is_set || cs7.is_set || default_.is_set || ef.is_set; } bool Native::Ip::Nbar::Custom::Transport::Tcp::Dscp::has_operation() const { return is_set(yfilter) || ydk::is_set(range.yfilter) || ydk::is_set(af11.yfilter) || ydk::is_set(af12.yfilter) || ydk::is_set(af13.yfilter) || ydk::is_set(af21.yfilter) || ydk::is_set(af22.yfilter) || ydk::is_set(af23.yfilter) || ydk::is_set(af31.yfilter) || ydk::is_set(af32.yfilter) || ydk::is_set(af33.yfilter) || ydk::is_set(af41.yfilter) || ydk::is_set(af42.yfilter) || ydk::is_set(af43.yfilter) || ydk::is_set(cs1.yfilter) || ydk::is_set(cs2.yfilter) || ydk::is_set(cs3.yfilter) || ydk::is_set(cs4.yfilter) || ydk::is_set(cs5.yfilter) || ydk::is_set(cs6.yfilter) || ydk::is_set(cs7.yfilter) || ydk::is_set(default_.yfilter) || ydk::is_set(ef.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::Dscp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dscp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::Dscp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (range.is_set || is_set(range.yfilter)) leaf_name_data.push_back(range.get_name_leafdata()); if (af11.is_set || is_set(af11.yfilter)) leaf_name_data.push_back(af11.get_name_leafdata()); if (af12.is_set || is_set(af12.yfilter)) leaf_name_data.push_back(af12.get_name_leafdata()); if (af13.is_set || is_set(af13.yfilter)) leaf_name_data.push_back(af13.get_name_leafdata()); if (af21.is_set || is_set(af21.yfilter)) leaf_name_data.push_back(af21.get_name_leafdata()); if (af22.is_set || is_set(af22.yfilter)) leaf_name_data.push_back(af22.get_name_leafdata()); if (af23.is_set || is_set(af23.yfilter)) leaf_name_data.push_back(af23.get_name_leafdata()); if (af31.is_set || is_set(af31.yfilter)) leaf_name_data.push_back(af31.get_name_leafdata()); if (af32.is_set || is_set(af32.yfilter)) leaf_name_data.push_back(af32.get_name_leafdata()); if (af33.is_set || is_set(af33.yfilter)) leaf_name_data.push_back(af33.get_name_leafdata()); if (af41.is_set || is_set(af41.yfilter)) leaf_name_data.push_back(af41.get_name_leafdata()); if (af42.is_set || is_set(af42.yfilter)) leaf_name_data.push_back(af42.get_name_leafdata()); if (af43.is_set || is_set(af43.yfilter)) leaf_name_data.push_back(af43.get_name_leafdata()); if (cs1.is_set || is_set(cs1.yfilter)) leaf_name_data.push_back(cs1.get_name_leafdata()); if (cs2.is_set || is_set(cs2.yfilter)) leaf_name_data.push_back(cs2.get_name_leafdata()); if (cs3.is_set || is_set(cs3.yfilter)) leaf_name_data.push_back(cs3.get_name_leafdata()); if (cs4.is_set || is_set(cs4.yfilter)) leaf_name_data.push_back(cs4.get_name_leafdata()); if (cs5.is_set || is_set(cs5.yfilter)) leaf_name_data.push_back(cs5.get_name_leafdata()); if (cs6.is_set || is_set(cs6.yfilter)) leaf_name_data.push_back(cs6.get_name_leafdata()); if (cs7.is_set || is_set(cs7.yfilter)) leaf_name_data.push_back(cs7.get_name_leafdata()); if (default_.is_set || is_set(default_.yfilter)) leaf_name_data.push_back(default_.get_name_leafdata()); if (ef.is_set || is_set(ef.yfilter)) leaf_name_data.push_back(ef.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::Dscp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::Dscp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::Dscp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "range") { range = value; range.value_namespace = name_space; range.value_namespace_prefix = name_space_prefix; } if(value_path == "af11") { af11 = value; af11.value_namespace = name_space; af11.value_namespace_prefix = name_space_prefix; } if(value_path == "af12") { af12 = value; af12.value_namespace = name_space; af12.value_namespace_prefix = name_space_prefix; } if(value_path == "af13") { af13 = value; af13.value_namespace = name_space; af13.value_namespace_prefix = name_space_prefix; } if(value_path == "af21") { af21 = value; af21.value_namespace = name_space; af21.value_namespace_prefix = name_space_prefix; } if(value_path == "af22") { af22 = value; af22.value_namespace = name_space; af22.value_namespace_prefix = name_space_prefix; } if(value_path == "af23") { af23 = value; af23.value_namespace = name_space; af23.value_namespace_prefix = name_space_prefix; } if(value_path == "af31") { af31 = value; af31.value_namespace = name_space; af31.value_namespace_prefix = name_space_prefix; } if(value_path == "af32") { af32 = value; af32.value_namespace = name_space; af32.value_namespace_prefix = name_space_prefix; } if(value_path == "af33") { af33 = value; af33.value_namespace = name_space; af33.value_namespace_prefix = name_space_prefix; } if(value_path == "af41") { af41 = value; af41.value_namespace = name_space; af41.value_namespace_prefix = name_space_prefix; } if(value_path == "af42") { af42 = value; af42.value_namespace = name_space; af42.value_namespace_prefix = name_space_prefix; } if(value_path == "af43") { af43 = value; af43.value_namespace = name_space; af43.value_namespace_prefix = name_space_prefix; } if(value_path == "cs1") { cs1 = value; cs1.value_namespace = name_space; cs1.value_namespace_prefix = name_space_prefix; } if(value_path == "cs2") { cs2 = value; cs2.value_namespace = name_space; cs2.value_namespace_prefix = name_space_prefix; } if(value_path == "cs3") { cs3 = value; cs3.value_namespace = name_space; cs3.value_namespace_prefix = name_space_prefix; } if(value_path == "cs4") { cs4 = value; cs4.value_namespace = name_space; cs4.value_namespace_prefix = name_space_prefix; } if(value_path == "cs5") { cs5 = value; cs5.value_namespace = name_space; cs5.value_namespace_prefix = name_space_prefix; } if(value_path == "cs6") { cs6 = value; cs6.value_namespace = name_space; cs6.value_namespace_prefix = name_space_prefix; } if(value_path == "cs7") { cs7 = value; cs7.value_namespace = name_space; cs7.value_namespace_prefix = name_space_prefix; } if(value_path == "default") { default_ = value; default_.value_namespace = name_space; default_.value_namespace_prefix = name_space_prefix; } if(value_path == "ef") { ef = value; ef.value_namespace = name_space; ef.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Tcp::Dscp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "range") { range.yfilter = yfilter; } if(value_path == "af11") { af11.yfilter = yfilter; } if(value_path == "af12") { af12.yfilter = yfilter; } if(value_path == "af13") { af13.yfilter = yfilter; } if(value_path == "af21") { af21.yfilter = yfilter; } if(value_path == "af22") { af22.yfilter = yfilter; } if(value_path == "af23") { af23.yfilter = yfilter; } if(value_path == "af31") { af31.yfilter = yfilter; } if(value_path == "af32") { af32.yfilter = yfilter; } if(value_path == "af33") { af33.yfilter = yfilter; } if(value_path == "af41") { af41.yfilter = yfilter; } if(value_path == "af42") { af42.yfilter = yfilter; } if(value_path == "af43") { af43.yfilter = yfilter; } if(value_path == "cs1") { cs1.yfilter = yfilter; } if(value_path == "cs2") { cs2.yfilter = yfilter; } if(value_path == "cs3") { cs3.yfilter = yfilter; } if(value_path == "cs4") { cs4.yfilter = yfilter; } if(value_path == "cs5") { cs5.yfilter = yfilter; } if(value_path == "cs6") { cs6.yfilter = yfilter; } if(value_path == "cs7") { cs7.yfilter = yfilter; } if(value_path == "default") { default_.yfilter = yfilter; } if(value_path == "ef") { ef.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Tcp::Dscp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "range" || name == "af11" || name == "af12" || name == "af13" || name == "af21" || name == "af22" || name == "af23" || name == "af31" || name == "af32" || name == "af33" || name == "af41" || name == "af42" || name == "af43" || name == "cs1" || name == "cs2" || name == "cs3" || name == "cs4" || name == "cs5" || name == "cs6" || name == "cs7" || name == "default" || name == "ef") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Ip_() : address(this, {"address0"}) , subnet(std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet>()) { subnet->parent = this; yang_name = "ip"; yang_parent_name = "tcp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::~Ip_() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_data()) return true; } return (subnet != nullptr && subnet->has_data()); } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::has_operation() const { for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_operation()) return true; } return is_set(yfilter) || (subnet != nullptr && subnet->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ip"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "address") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address>(); ent_->parent = this; address.append(ent_); return ent_; } if(child_yang_name == "subnet") { if(subnet == nullptr) { subnet = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet>(); } return subnet; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(subnet != nullptr) { _children["subnet"] = subnet; } return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address" || name == "subnet") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address::Address() : address0{YType::str, "address0"}, address1{YType::str, "address1"}, address2{YType::str, "address2"}, address3{YType::str, "address3"}, address4{YType::str, "address4"}, address5{YType::str, "address5"}, address6{YType::str, "address6"}, address7{YType::str, "address7"} { yang_name = "address"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address::~Address() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address::has_data() const { if (is_presence_container) return true; return address0.is_set || address1.is_set || address2.is_set || address3.is_set || address4.is_set || address5.is_set || address6.is_set || address7.is_set; } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address::has_operation() const { return is_set(yfilter) || ydk::is_set(address0.yfilter) || ydk::is_set(address1.yfilter) || ydk::is_set(address2.yfilter) || ydk::is_set(address3.yfilter) || ydk::is_set(address4.yfilter) || ydk::is_set(address5.yfilter) || ydk::is_set(address6.yfilter) || ydk::is_set(address7.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "address"; ADD_KEY_TOKEN(address0, "address0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (address0.is_set || is_set(address0.yfilter)) leaf_name_data.push_back(address0.get_name_leafdata()); if (address1.is_set || is_set(address1.yfilter)) leaf_name_data.push_back(address1.get_name_leafdata()); if (address2.is_set || is_set(address2.yfilter)) leaf_name_data.push_back(address2.get_name_leafdata()); if (address3.is_set || is_set(address3.yfilter)) leaf_name_data.push_back(address3.get_name_leafdata()); if (address4.is_set || is_set(address4.yfilter)) leaf_name_data.push_back(address4.get_name_leafdata()); if (address5.is_set || is_set(address5.yfilter)) leaf_name_data.push_back(address5.get_name_leafdata()); if (address6.is_set || is_set(address6.yfilter)) leaf_name_data.push_back(address6.get_name_leafdata()); if (address7.is_set || is_set(address7.yfilter)) leaf_name_data.push_back(address7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "address0") { address0 = value; address0.value_namespace = name_space; address0.value_namespace_prefix = name_space_prefix; } if(value_path == "address1") { address1 = value; address1.value_namespace = name_space; address1.value_namespace_prefix = name_space_prefix; } if(value_path == "address2") { address2 = value; address2.value_namespace = name_space; address2.value_namespace_prefix = name_space_prefix; } if(value_path == "address3") { address3 = value; address3.value_namespace = name_space; address3.value_namespace_prefix = name_space_prefix; } if(value_path == "address4") { address4 = value; address4.value_namespace = name_space; address4.value_namespace_prefix = name_space_prefix; } if(value_path == "address5") { address5 = value; address5.value_namespace = name_space; address5.value_namespace_prefix = name_space_prefix; } if(value_path == "address6") { address6 = value; address6.value_namespace = name_space; address6.value_namespace_prefix = name_space_prefix; } if(value_path == "address7") { address7 = value; address7.value_namespace = name_space; address7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "address0") { address0.yfilter = yfilter; } if(value_path == "address1") { address1.yfilter = yfilter; } if(value_path == "address2") { address2.yfilter = yfilter; } if(value_path == "address3") { address3.yfilter = yfilter; } if(value_path == "address4") { address4.yfilter = yfilter; } if(value_path == "address5") { address5.yfilter = yfilter; } if(value_path == "address6") { address6.yfilter = yfilter; } if(value_path == "address7") { address7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Address::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address0" || name == "address1" || name == "address2" || name == "address3" || name == "address4" || name == "address5" || name == "address6" || name == "address7") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet::Subnet() : subnet{YType::str, "subnet"}, mask{YType::uint8, "mask"} { yang_name = "subnet"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet::~Subnet() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet::has_data() const { if (is_presence_container) return true; return subnet.is_set || mask.is_set; } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet::has_operation() const { return is_set(yfilter) || ydk::is_set(subnet.yfilter) || ydk::is_set(mask.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "subnet"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (subnet.is_set || is_set(subnet.yfilter)) leaf_name_data.push_back(subnet.get_name_leafdata()); if (mask.is_set || is_set(mask.yfilter)) leaf_name_data.push_back(mask.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "subnet") { subnet = value; subnet.value_namespace = name_space; subnet.value_namespace_prefix = name_space_prefix; } if(value_path == "mask") { mask = value; mask.value_namespace = name_space; mask.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "subnet") { subnet.yfilter = yfilter; } if(value_path == "mask") { mask.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ip_::Subnet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "subnet" || name == "mask") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Ipv6() : address(this, {"address0"}) , subnet(std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet>()) { subnet->parent = this; yang_name = "ipv6"; yang_parent_name = "tcp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::~Ipv6() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_data()) return true; } return (subnet != nullptr && subnet->has_data()); } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::has_operation() const { for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_operation()) return true; } return is_set(yfilter) || (subnet != nullptr && subnet->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "address") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address>(); ent_->parent = this; address.append(ent_); return ent_; } if(child_yang_name == "subnet") { if(subnet == nullptr) { subnet = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet>(); } return subnet; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(subnet != nullptr) { _children["subnet"] = subnet; } return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address" || name == "subnet") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address::Address() : address0{YType::str, "address0"}, address1{YType::str, "address1"}, address2{YType::str, "address2"}, address3{YType::str, "address3"}, address4{YType::str, "address4"}, address5{YType::str, "address5"}, address6{YType::str, "address6"}, address7{YType::str, "address7"} { yang_name = "address"; yang_parent_name = "ipv6"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address::~Address() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address::has_data() const { if (is_presence_container) return true; return address0.is_set || address1.is_set || address2.is_set || address3.is_set || address4.is_set || address5.is_set || address6.is_set || address7.is_set; } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address::has_operation() const { return is_set(yfilter) || ydk::is_set(address0.yfilter) || ydk::is_set(address1.yfilter) || ydk::is_set(address2.yfilter) || ydk::is_set(address3.yfilter) || ydk::is_set(address4.yfilter) || ydk::is_set(address5.yfilter) || ydk::is_set(address6.yfilter) || ydk::is_set(address7.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "address"; ADD_KEY_TOKEN(address0, "address0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (address0.is_set || is_set(address0.yfilter)) leaf_name_data.push_back(address0.get_name_leafdata()); if (address1.is_set || is_set(address1.yfilter)) leaf_name_data.push_back(address1.get_name_leafdata()); if (address2.is_set || is_set(address2.yfilter)) leaf_name_data.push_back(address2.get_name_leafdata()); if (address3.is_set || is_set(address3.yfilter)) leaf_name_data.push_back(address3.get_name_leafdata()); if (address4.is_set || is_set(address4.yfilter)) leaf_name_data.push_back(address4.get_name_leafdata()); if (address5.is_set || is_set(address5.yfilter)) leaf_name_data.push_back(address5.get_name_leafdata()); if (address6.is_set || is_set(address6.yfilter)) leaf_name_data.push_back(address6.get_name_leafdata()); if (address7.is_set || is_set(address7.yfilter)) leaf_name_data.push_back(address7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "address0") { address0 = value; address0.value_namespace = name_space; address0.value_namespace_prefix = name_space_prefix; } if(value_path == "address1") { address1 = value; address1.value_namespace = name_space; address1.value_namespace_prefix = name_space_prefix; } if(value_path == "address2") { address2 = value; address2.value_namespace = name_space; address2.value_namespace_prefix = name_space_prefix; } if(value_path == "address3") { address3 = value; address3.value_namespace = name_space; address3.value_namespace_prefix = name_space_prefix; } if(value_path == "address4") { address4 = value; address4.value_namespace = name_space; address4.value_namespace_prefix = name_space_prefix; } if(value_path == "address5") { address5 = value; address5.value_namespace = name_space; address5.value_namespace_prefix = name_space_prefix; } if(value_path == "address6") { address6 = value; address6.value_namespace = name_space; address6.value_namespace_prefix = name_space_prefix; } if(value_path == "address7") { address7 = value; address7.value_namespace = name_space; address7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "address0") { address0.yfilter = yfilter; } if(value_path == "address1") { address1.yfilter = yfilter; } if(value_path == "address2") { address2.yfilter = yfilter; } if(value_path == "address3") { address3.yfilter = yfilter; } if(value_path == "address4") { address4.yfilter = yfilter; } if(value_path == "address5") { address5.yfilter = yfilter; } if(value_path == "address6") { address6.yfilter = yfilter; } if(value_path == "address7") { address7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Address::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address0" || name == "address1" || name == "address2" || name == "address3" || name == "address4" || name == "address5" || name == "address6" || name == "address7") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet::Subnet() : subnet{YType::str, "subnet"}, mask{YType::uint8, "mask"} { yang_name = "subnet"; yang_parent_name = "ipv6"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet::~Subnet() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet::has_data() const { if (is_presence_container) return true; return subnet.is_set || mask.is_set; } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet::has_operation() const { return is_set(yfilter) || ydk::is_set(subnet.yfilter) || ydk::is_set(mask.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "subnet"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (subnet.is_set || is_set(subnet.yfilter)) leaf_name_data.push_back(subnet.get_name_leafdata()); if (mask.is_set || is_set(mask.yfilter)) leaf_name_data.push_back(mask.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "subnet") { subnet = value; subnet.value_namespace = name_space; subnet.value_namespace_prefix = name_space_prefix; } if(value_path == "mask") { mask = value; mask.value_namespace = name_space; mask.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "subnet") { subnet.yfilter = yfilter; } if(value_path == "mask") { mask.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Tcp::Ipv6::Subnet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "subnet" || name == "mask") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Direction::Direction() : any{YType::empty, "any"}, destination{YType::empty, "destination"}, source{YType::empty, "source"} { yang_name = "direction"; yang_parent_name = "tcp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Tcp::Direction::~Direction() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Direction::has_data() const { if (is_presence_container) return true; return any.is_set || destination.is_set || source.is_set; } bool Native::Ip::Nbar::Custom::Transport::Tcp::Direction::has_operation() const { return is_set(yfilter) || ydk::is_set(any.yfilter) || ydk::is_set(destination.yfilter) || ydk::is_set(source.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::Direction::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "direction"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::Direction::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (any.is_set || is_set(any.yfilter)) leaf_name_data.push_back(any.get_name_leafdata()); if (destination.is_set || is_set(destination.yfilter)) leaf_name_data.push_back(destination.get_name_leafdata()); if (source.is_set || is_set(source.yfilter)) leaf_name_data.push_back(source.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::Direction::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::Direction::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::Direction::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "any") { any = value; any.value_namespace = name_space; any.value_namespace_prefix = name_space_prefix; } if(value_path == "destination") { destination = value; destination.value_namespace = name_space; destination.value_namespace_prefix = name_space_prefix; } if(value_path == "source") { source = value; source.value_namespace = name_space; source.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Tcp::Direction::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "any") { any.yfilter = yfilter; } if(value_path == "destination") { destination.yfilter = yfilter; } if(value_path == "source") { source.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Tcp::Direction::has_leaf_or_child_of_name(const std::string & name) const { if(name == "any" || name == "destination" || name == "source") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Port::Port() : port_numbers(this, {"port_number0"}) , range(std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range>()) { range->parent = this; yang_name = "port"; yang_parent_name = "tcp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Tcp::Port::~Port() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Port::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<port_numbers.len(); index++) { if(port_numbers[index]->has_data()) return true; } return (range != nullptr && range->has_data()); } bool Native::Ip::Nbar::Custom::Transport::Tcp::Port::has_operation() const { for (std::size_t index=0; index<port_numbers.len(); index++) { if(port_numbers[index]->has_operation()) return true; } return is_set(yfilter) || (range != nullptr && range->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::Port::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "port"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::Port::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::Port::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "port-numbers") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers>(); ent_->parent = this; port_numbers.append(ent_); return ent_; } if(child_yang_name == "range") { if(range == nullptr) { range = std::make_shared<Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range>(); } return range; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::Port::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : port_numbers.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(range != nullptr) { _children["range"] = range; } return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::Port::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Transport::Tcp::Port::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Port::has_leaf_or_child_of_name(const std::string & name) const { if(name == "port-numbers" || name == "range") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers::PortNumbers() : port_number0{YType::uint16, "port-number0"}, port_number1{YType::uint16, "port-number1"}, port_number2{YType::uint16, "port-number2"}, port_number3{YType::uint16, "port-number3"}, port_number4{YType::uint16, "port-number4"}, port_number5{YType::uint16, "port-number5"}, port_number6{YType::uint16, "port-number6"}, port_number7{YType::uint16, "port-number7"} { yang_name = "port-numbers"; yang_parent_name = "port"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers::~PortNumbers() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers::has_data() const { if (is_presence_container) return true; return port_number0.is_set || port_number1.is_set || port_number2.is_set || port_number3.is_set || port_number4.is_set || port_number5.is_set || port_number6.is_set || port_number7.is_set; } bool Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers::has_operation() const { return is_set(yfilter) || ydk::is_set(port_number0.yfilter) || ydk::is_set(port_number1.yfilter) || ydk::is_set(port_number2.yfilter) || ydk::is_set(port_number3.yfilter) || ydk::is_set(port_number4.yfilter) || ydk::is_set(port_number5.yfilter) || ydk::is_set(port_number6.yfilter) || ydk::is_set(port_number7.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "port-numbers"; ADD_KEY_TOKEN(port_number0, "port-number0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (port_number0.is_set || is_set(port_number0.yfilter)) leaf_name_data.push_back(port_number0.get_name_leafdata()); if (port_number1.is_set || is_set(port_number1.yfilter)) leaf_name_data.push_back(port_number1.get_name_leafdata()); if (port_number2.is_set || is_set(port_number2.yfilter)) leaf_name_data.push_back(port_number2.get_name_leafdata()); if (port_number3.is_set || is_set(port_number3.yfilter)) leaf_name_data.push_back(port_number3.get_name_leafdata()); if (port_number4.is_set || is_set(port_number4.yfilter)) leaf_name_data.push_back(port_number4.get_name_leafdata()); if (port_number5.is_set || is_set(port_number5.yfilter)) leaf_name_data.push_back(port_number5.get_name_leafdata()); if (port_number6.is_set || is_set(port_number6.yfilter)) leaf_name_data.push_back(port_number6.get_name_leafdata()); if (port_number7.is_set || is_set(port_number7.yfilter)) leaf_name_data.push_back(port_number7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "port-number0") { port_number0 = value; port_number0.value_namespace = name_space; port_number0.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number1") { port_number1 = value; port_number1.value_namespace = name_space; port_number1.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number2") { port_number2 = value; port_number2.value_namespace = name_space; port_number2.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number3") { port_number3 = value; port_number3.value_namespace = name_space; port_number3.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number4") { port_number4 = value; port_number4.value_namespace = name_space; port_number4.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number5") { port_number5 = value; port_number5.value_namespace = name_space; port_number5.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number6") { port_number6 = value; port_number6.value_namespace = name_space; port_number6.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number7") { port_number7 = value; port_number7.value_namespace = name_space; port_number7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "port-number0") { port_number0.yfilter = yfilter; } if(value_path == "port-number1") { port_number1.yfilter = yfilter; } if(value_path == "port-number2") { port_number2.yfilter = yfilter; } if(value_path == "port-number3") { port_number3.yfilter = yfilter; } if(value_path == "port-number4") { port_number4.yfilter = yfilter; } if(value_path == "port-number5") { port_number5.yfilter = yfilter; } if(value_path == "port-number6") { port_number6.yfilter = yfilter; } if(value_path == "port-number7") { port_number7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Tcp::Port::PortNumbers::has_leaf_or_child_of_name(const std::string & name) const { if(name == "port-number0" || name == "port-number1" || name == "port-number2" || name == "port-number3" || name == "port-number4" || name == "port-number5" || name == "port-number6" || name == "port-number7") return true; return false; } Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range::Range() : start_range{YType::uint16, "start-range"}, end_range{YType::uint16, "end-range"} { yang_name = "range"; yang_parent_name = "port"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range::~Range() { } bool Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range::has_data() const { if (is_presence_container) return true; return start_range.is_set || end_range.is_set; } bool Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range::has_operation() const { return is_set(yfilter) || ydk::is_set(start_range.yfilter) || ydk::is_set(end_range.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "range"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_range.is_set || is_set(start_range.yfilter)) leaf_name_data.push_back(start_range.get_name_leafdata()); if (end_range.is_set || is_set(end_range.yfilter)) leaf_name_data.push_back(end_range.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-range") { start_range = value; start_range.value_namespace = name_space; start_range.value_namespace_prefix = name_space_prefix; } if(value_path == "end-range") { end_range = value; end_range.value_namespace = name_space; end_range.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-range") { start_range.yfilter = yfilter; } if(value_path == "end-range") { end_range.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Tcp::Port::Range::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-range" || name == "end-range") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Udp() : id{YType::uint16, "id"} , dscp(std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Dscp>()) , ip(std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Ip_>()) , ipv6(std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Ipv6>()) , direction(std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Direction>()) , port(std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Port>()) { dscp->parent = this; ip->parent = this; ipv6->parent = this; direction->parent = this; port->parent = this; yang_name = "udp"; yang_parent_name = "transport"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Native::Ip::Nbar::Custom::Transport::Udp::~Udp() { } bool Native::Ip::Nbar::Custom::Transport::Udp::has_data() const { if (is_presence_container) return true; return id.is_set || (dscp != nullptr && dscp->has_data()) || (ip != nullptr && ip->has_data()) || (ipv6 != nullptr && ipv6->has_data()) || (direction != nullptr && direction->has_data()) || (port != nullptr && port->has_data()); } bool Native::Ip::Nbar::Custom::Transport::Udp::has_operation() const { return is_set(yfilter) || ydk::is_set(id.yfilter) || (dscp != nullptr && dscp->has_operation()) || (ip != nullptr && ip->has_operation()) || (ipv6 != nullptr && ipv6->has_operation()) || (direction != nullptr && direction->has_operation()) || (port != nullptr && port->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::Udp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "udp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (id.is_set || is_set(id.yfilter)) leaf_name_data.push_back(id.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dscp") { if(dscp == nullptr) { dscp = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Dscp>(); } return dscp; } if(child_yang_name == "ip") { if(ip == nullptr) { ip = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Ip_>(); } return ip; } if(child_yang_name == "ipv6") { if(ipv6 == nullptr) { ipv6 = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Ipv6>(); } return ipv6; } if(child_yang_name == "direction") { if(direction == nullptr) { direction = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Direction>(); } return direction; } if(child_yang_name == "port") { if(port == nullptr) { port = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Port>(); } return port; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(dscp != nullptr) { _children["dscp"] = dscp; } if(ip != nullptr) { _children["ip"] = ip; } if(ipv6 != nullptr) { _children["ipv6"] = ipv6; } if(direction != nullptr) { _children["direction"] = direction; } if(port != nullptr) { _children["port"] = port; } return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "id") { id = value; id.value_namespace = name_space; id.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Udp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "id") { id.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Udp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dscp" || name == "ip" || name == "ipv6" || name == "direction" || name == "port" || name == "id") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Dscp::Dscp() : range{YType::uint8, "range"}, af11{YType::empty, "af11"}, af12{YType::empty, "af12"}, af13{YType::empty, "af13"}, af21{YType::empty, "af21"}, af22{YType::empty, "af22"}, af23{YType::empty, "af23"}, af31{YType::empty, "af31"}, af32{YType::empty, "af32"}, af33{YType::empty, "af33"}, af41{YType::empty, "af41"}, af42{YType::empty, "af42"}, af43{YType::empty, "af43"}, cs1{YType::empty, "cs1"}, cs2{YType::empty, "cs2"}, cs3{YType::empty, "cs3"}, cs4{YType::empty, "cs4"}, cs5{YType::empty, "cs5"}, cs6{YType::empty, "cs6"}, cs7{YType::empty, "cs7"}, default_{YType::empty, "default"}, ef{YType::empty, "ef"} { yang_name = "dscp"; yang_parent_name = "udp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Udp::Dscp::~Dscp() { } bool Native::Ip::Nbar::Custom::Transport::Udp::Dscp::has_data() const { if (is_presence_container) return true; return range.is_set || af11.is_set || af12.is_set || af13.is_set || af21.is_set || af22.is_set || af23.is_set || af31.is_set || af32.is_set || af33.is_set || af41.is_set || af42.is_set || af43.is_set || cs1.is_set || cs2.is_set || cs3.is_set || cs4.is_set || cs5.is_set || cs6.is_set || cs7.is_set || default_.is_set || ef.is_set; } bool Native::Ip::Nbar::Custom::Transport::Udp::Dscp::has_operation() const { return is_set(yfilter) || ydk::is_set(range.yfilter) || ydk::is_set(af11.yfilter) || ydk::is_set(af12.yfilter) || ydk::is_set(af13.yfilter) || ydk::is_set(af21.yfilter) || ydk::is_set(af22.yfilter) || ydk::is_set(af23.yfilter) || ydk::is_set(af31.yfilter) || ydk::is_set(af32.yfilter) || ydk::is_set(af33.yfilter) || ydk::is_set(af41.yfilter) || ydk::is_set(af42.yfilter) || ydk::is_set(af43.yfilter) || ydk::is_set(cs1.yfilter) || ydk::is_set(cs2.yfilter) || ydk::is_set(cs3.yfilter) || ydk::is_set(cs4.yfilter) || ydk::is_set(cs5.yfilter) || ydk::is_set(cs6.yfilter) || ydk::is_set(cs7.yfilter) || ydk::is_set(default_.yfilter) || ydk::is_set(ef.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Udp::Dscp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dscp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::Dscp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (range.is_set || is_set(range.yfilter)) leaf_name_data.push_back(range.get_name_leafdata()); if (af11.is_set || is_set(af11.yfilter)) leaf_name_data.push_back(af11.get_name_leafdata()); if (af12.is_set || is_set(af12.yfilter)) leaf_name_data.push_back(af12.get_name_leafdata()); if (af13.is_set || is_set(af13.yfilter)) leaf_name_data.push_back(af13.get_name_leafdata()); if (af21.is_set || is_set(af21.yfilter)) leaf_name_data.push_back(af21.get_name_leafdata()); if (af22.is_set || is_set(af22.yfilter)) leaf_name_data.push_back(af22.get_name_leafdata()); if (af23.is_set || is_set(af23.yfilter)) leaf_name_data.push_back(af23.get_name_leafdata()); if (af31.is_set || is_set(af31.yfilter)) leaf_name_data.push_back(af31.get_name_leafdata()); if (af32.is_set || is_set(af32.yfilter)) leaf_name_data.push_back(af32.get_name_leafdata()); if (af33.is_set || is_set(af33.yfilter)) leaf_name_data.push_back(af33.get_name_leafdata()); if (af41.is_set || is_set(af41.yfilter)) leaf_name_data.push_back(af41.get_name_leafdata()); if (af42.is_set || is_set(af42.yfilter)) leaf_name_data.push_back(af42.get_name_leafdata()); if (af43.is_set || is_set(af43.yfilter)) leaf_name_data.push_back(af43.get_name_leafdata()); if (cs1.is_set || is_set(cs1.yfilter)) leaf_name_data.push_back(cs1.get_name_leafdata()); if (cs2.is_set || is_set(cs2.yfilter)) leaf_name_data.push_back(cs2.get_name_leafdata()); if (cs3.is_set || is_set(cs3.yfilter)) leaf_name_data.push_back(cs3.get_name_leafdata()); if (cs4.is_set || is_set(cs4.yfilter)) leaf_name_data.push_back(cs4.get_name_leafdata()); if (cs5.is_set || is_set(cs5.yfilter)) leaf_name_data.push_back(cs5.get_name_leafdata()); if (cs6.is_set || is_set(cs6.yfilter)) leaf_name_data.push_back(cs6.get_name_leafdata()); if (cs7.is_set || is_set(cs7.yfilter)) leaf_name_data.push_back(cs7.get_name_leafdata()); if (default_.is_set || is_set(default_.yfilter)) leaf_name_data.push_back(default_.get_name_leafdata()); if (ef.is_set || is_set(ef.yfilter)) leaf_name_data.push_back(ef.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::Dscp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::Dscp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::Dscp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "range") { range = value; range.value_namespace = name_space; range.value_namespace_prefix = name_space_prefix; } if(value_path == "af11") { af11 = value; af11.value_namespace = name_space; af11.value_namespace_prefix = name_space_prefix; } if(value_path == "af12") { af12 = value; af12.value_namespace = name_space; af12.value_namespace_prefix = name_space_prefix; } if(value_path == "af13") { af13 = value; af13.value_namespace = name_space; af13.value_namespace_prefix = name_space_prefix; } if(value_path == "af21") { af21 = value; af21.value_namespace = name_space; af21.value_namespace_prefix = name_space_prefix; } if(value_path == "af22") { af22 = value; af22.value_namespace = name_space; af22.value_namespace_prefix = name_space_prefix; } if(value_path == "af23") { af23 = value; af23.value_namespace = name_space; af23.value_namespace_prefix = name_space_prefix; } if(value_path == "af31") { af31 = value; af31.value_namespace = name_space; af31.value_namespace_prefix = name_space_prefix; } if(value_path == "af32") { af32 = value; af32.value_namespace = name_space; af32.value_namespace_prefix = name_space_prefix; } if(value_path == "af33") { af33 = value; af33.value_namespace = name_space; af33.value_namespace_prefix = name_space_prefix; } if(value_path == "af41") { af41 = value; af41.value_namespace = name_space; af41.value_namespace_prefix = name_space_prefix; } if(value_path == "af42") { af42 = value; af42.value_namespace = name_space; af42.value_namespace_prefix = name_space_prefix; } if(value_path == "af43") { af43 = value; af43.value_namespace = name_space; af43.value_namespace_prefix = name_space_prefix; } if(value_path == "cs1") { cs1 = value; cs1.value_namespace = name_space; cs1.value_namespace_prefix = name_space_prefix; } if(value_path == "cs2") { cs2 = value; cs2.value_namespace = name_space; cs2.value_namespace_prefix = name_space_prefix; } if(value_path == "cs3") { cs3 = value; cs3.value_namespace = name_space; cs3.value_namespace_prefix = name_space_prefix; } if(value_path == "cs4") { cs4 = value; cs4.value_namespace = name_space; cs4.value_namespace_prefix = name_space_prefix; } if(value_path == "cs5") { cs5 = value; cs5.value_namespace = name_space; cs5.value_namespace_prefix = name_space_prefix; } if(value_path == "cs6") { cs6 = value; cs6.value_namespace = name_space; cs6.value_namespace_prefix = name_space_prefix; } if(value_path == "cs7") { cs7 = value; cs7.value_namespace = name_space; cs7.value_namespace_prefix = name_space_prefix; } if(value_path == "default") { default_ = value; default_.value_namespace = name_space; default_.value_namespace_prefix = name_space_prefix; } if(value_path == "ef") { ef = value; ef.value_namespace = name_space; ef.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Udp::Dscp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "range") { range.yfilter = yfilter; } if(value_path == "af11") { af11.yfilter = yfilter; } if(value_path == "af12") { af12.yfilter = yfilter; } if(value_path == "af13") { af13.yfilter = yfilter; } if(value_path == "af21") { af21.yfilter = yfilter; } if(value_path == "af22") { af22.yfilter = yfilter; } if(value_path == "af23") { af23.yfilter = yfilter; } if(value_path == "af31") { af31.yfilter = yfilter; } if(value_path == "af32") { af32.yfilter = yfilter; } if(value_path == "af33") { af33.yfilter = yfilter; } if(value_path == "af41") { af41.yfilter = yfilter; } if(value_path == "af42") { af42.yfilter = yfilter; } if(value_path == "af43") { af43.yfilter = yfilter; } if(value_path == "cs1") { cs1.yfilter = yfilter; } if(value_path == "cs2") { cs2.yfilter = yfilter; } if(value_path == "cs3") { cs3.yfilter = yfilter; } if(value_path == "cs4") { cs4.yfilter = yfilter; } if(value_path == "cs5") { cs5.yfilter = yfilter; } if(value_path == "cs6") { cs6.yfilter = yfilter; } if(value_path == "cs7") { cs7.yfilter = yfilter; } if(value_path == "default") { default_.yfilter = yfilter; } if(value_path == "ef") { ef.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Udp::Dscp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "range" || name == "af11" || name == "af12" || name == "af13" || name == "af21" || name == "af22" || name == "af23" || name == "af31" || name == "af32" || name == "af33" || name == "af41" || name == "af42" || name == "af43" || name == "cs1" || name == "cs2" || name == "cs3" || name == "cs4" || name == "cs5" || name == "cs6" || name == "cs7" || name == "default" || name == "ef") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Ip_() : address(this, {"address0"}) , subnet(std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet>()) { subnet->parent = this; yang_name = "ip"; yang_parent_name = "udp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Udp::Ip_::~Ip_() { } bool Native::Ip::Nbar::Custom::Transport::Udp::Ip_::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_data()) return true; } return (subnet != nullptr && subnet->has_data()); } bool Native::Ip::Nbar::Custom::Transport::Udp::Ip_::has_operation() const { for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_operation()) return true; } return is_set(yfilter) || (subnet != nullptr && subnet->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::Udp::Ip_::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ip"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::Ip_::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::Ip_::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "address") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address>(); ent_->parent = this; address.append(ent_); return ent_; } if(child_yang_name == "subnet") { if(subnet == nullptr) { subnet = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet>(); } return subnet; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::Ip_::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(subnet != nullptr) { _children["subnet"] = subnet; } return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::Ip_::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Transport::Udp::Ip_::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Transport::Udp::Ip_::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address" || name == "subnet") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address::Address() : address0{YType::str, "address0"}, address1{YType::str, "address1"}, address2{YType::str, "address2"}, address3{YType::str, "address3"}, address4{YType::str, "address4"}, address5{YType::str, "address5"}, address6{YType::str, "address6"}, address7{YType::str, "address7"} { yang_name = "address"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address::~Address() { } bool Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address::has_data() const { if (is_presence_container) return true; return address0.is_set || address1.is_set || address2.is_set || address3.is_set || address4.is_set || address5.is_set || address6.is_set || address7.is_set; } bool Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address::has_operation() const { return is_set(yfilter) || ydk::is_set(address0.yfilter) || ydk::is_set(address1.yfilter) || ydk::is_set(address2.yfilter) || ydk::is_set(address3.yfilter) || ydk::is_set(address4.yfilter) || ydk::is_set(address5.yfilter) || ydk::is_set(address6.yfilter) || ydk::is_set(address7.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "address"; ADD_KEY_TOKEN(address0, "address0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (address0.is_set || is_set(address0.yfilter)) leaf_name_data.push_back(address0.get_name_leafdata()); if (address1.is_set || is_set(address1.yfilter)) leaf_name_data.push_back(address1.get_name_leafdata()); if (address2.is_set || is_set(address2.yfilter)) leaf_name_data.push_back(address2.get_name_leafdata()); if (address3.is_set || is_set(address3.yfilter)) leaf_name_data.push_back(address3.get_name_leafdata()); if (address4.is_set || is_set(address4.yfilter)) leaf_name_data.push_back(address4.get_name_leafdata()); if (address5.is_set || is_set(address5.yfilter)) leaf_name_data.push_back(address5.get_name_leafdata()); if (address6.is_set || is_set(address6.yfilter)) leaf_name_data.push_back(address6.get_name_leafdata()); if (address7.is_set || is_set(address7.yfilter)) leaf_name_data.push_back(address7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "address0") { address0 = value; address0.value_namespace = name_space; address0.value_namespace_prefix = name_space_prefix; } if(value_path == "address1") { address1 = value; address1.value_namespace = name_space; address1.value_namespace_prefix = name_space_prefix; } if(value_path == "address2") { address2 = value; address2.value_namespace = name_space; address2.value_namespace_prefix = name_space_prefix; } if(value_path == "address3") { address3 = value; address3.value_namespace = name_space; address3.value_namespace_prefix = name_space_prefix; } if(value_path == "address4") { address4 = value; address4.value_namespace = name_space; address4.value_namespace_prefix = name_space_prefix; } if(value_path == "address5") { address5 = value; address5.value_namespace = name_space; address5.value_namespace_prefix = name_space_prefix; } if(value_path == "address6") { address6 = value; address6.value_namespace = name_space; address6.value_namespace_prefix = name_space_prefix; } if(value_path == "address7") { address7 = value; address7.value_namespace = name_space; address7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "address0") { address0.yfilter = yfilter; } if(value_path == "address1") { address1.yfilter = yfilter; } if(value_path == "address2") { address2.yfilter = yfilter; } if(value_path == "address3") { address3.yfilter = yfilter; } if(value_path == "address4") { address4.yfilter = yfilter; } if(value_path == "address5") { address5.yfilter = yfilter; } if(value_path == "address6") { address6.yfilter = yfilter; } if(value_path == "address7") { address7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Address::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address0" || name == "address1" || name == "address2" || name == "address3" || name == "address4" || name == "address5" || name == "address6" || name == "address7") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet::Subnet() : subnet{YType::str, "subnet"}, mask{YType::uint8, "mask"} { yang_name = "subnet"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet::~Subnet() { } bool Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet::has_data() const { if (is_presence_container) return true; return subnet.is_set || mask.is_set; } bool Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet::has_operation() const { return is_set(yfilter) || ydk::is_set(subnet.yfilter) || ydk::is_set(mask.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "subnet"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (subnet.is_set || is_set(subnet.yfilter)) leaf_name_data.push_back(subnet.get_name_leafdata()); if (mask.is_set || is_set(mask.yfilter)) leaf_name_data.push_back(mask.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "subnet") { subnet = value; subnet.value_namespace = name_space; subnet.value_namespace_prefix = name_space_prefix; } if(value_path == "mask") { mask = value; mask.value_namespace = name_space; mask.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "subnet") { subnet.yfilter = yfilter; } if(value_path == "mask") { mask.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Udp::Ip_::Subnet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "subnet" || name == "mask") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Ipv6() : address(this, {"address0"}) , subnet(std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet>()) { subnet->parent = this; yang_name = "ipv6"; yang_parent_name = "udp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::~Ipv6() { } bool Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_data()) return true; } return (subnet != nullptr && subnet->has_data()); } bool Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::has_operation() const { for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_operation()) return true; } return is_set(yfilter) || (subnet != nullptr && subnet->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "address") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address>(); ent_->parent = this; address.append(ent_); return ent_; } if(child_yang_name == "subnet") { if(subnet == nullptr) { subnet = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet>(); } return subnet; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(subnet != nullptr) { _children["subnet"] = subnet; } return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address" || name == "subnet") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address::Address() : address0{YType::str, "address0"}, address1{YType::str, "address1"}, address2{YType::str, "address2"}, address3{YType::str, "address3"}, address4{YType::str, "address4"}, address5{YType::str, "address5"}, address6{YType::str, "address6"}, address7{YType::str, "address7"} { yang_name = "address"; yang_parent_name = "ipv6"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address::~Address() { } bool Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address::has_data() const { if (is_presence_container) return true; return address0.is_set || address1.is_set || address2.is_set || address3.is_set || address4.is_set || address5.is_set || address6.is_set || address7.is_set; } bool Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address::has_operation() const { return is_set(yfilter) || ydk::is_set(address0.yfilter) || ydk::is_set(address1.yfilter) || ydk::is_set(address2.yfilter) || ydk::is_set(address3.yfilter) || ydk::is_set(address4.yfilter) || ydk::is_set(address5.yfilter) || ydk::is_set(address6.yfilter) || ydk::is_set(address7.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "address"; ADD_KEY_TOKEN(address0, "address0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (address0.is_set || is_set(address0.yfilter)) leaf_name_data.push_back(address0.get_name_leafdata()); if (address1.is_set || is_set(address1.yfilter)) leaf_name_data.push_back(address1.get_name_leafdata()); if (address2.is_set || is_set(address2.yfilter)) leaf_name_data.push_back(address2.get_name_leafdata()); if (address3.is_set || is_set(address3.yfilter)) leaf_name_data.push_back(address3.get_name_leafdata()); if (address4.is_set || is_set(address4.yfilter)) leaf_name_data.push_back(address4.get_name_leafdata()); if (address5.is_set || is_set(address5.yfilter)) leaf_name_data.push_back(address5.get_name_leafdata()); if (address6.is_set || is_set(address6.yfilter)) leaf_name_data.push_back(address6.get_name_leafdata()); if (address7.is_set || is_set(address7.yfilter)) leaf_name_data.push_back(address7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "address0") { address0 = value; address0.value_namespace = name_space; address0.value_namespace_prefix = name_space_prefix; } if(value_path == "address1") { address1 = value; address1.value_namespace = name_space; address1.value_namespace_prefix = name_space_prefix; } if(value_path == "address2") { address2 = value; address2.value_namespace = name_space; address2.value_namespace_prefix = name_space_prefix; } if(value_path == "address3") { address3 = value; address3.value_namespace = name_space; address3.value_namespace_prefix = name_space_prefix; } if(value_path == "address4") { address4 = value; address4.value_namespace = name_space; address4.value_namespace_prefix = name_space_prefix; } if(value_path == "address5") { address5 = value; address5.value_namespace = name_space; address5.value_namespace_prefix = name_space_prefix; } if(value_path == "address6") { address6 = value; address6.value_namespace = name_space; address6.value_namespace_prefix = name_space_prefix; } if(value_path == "address7") { address7 = value; address7.value_namespace = name_space; address7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "address0") { address0.yfilter = yfilter; } if(value_path == "address1") { address1.yfilter = yfilter; } if(value_path == "address2") { address2.yfilter = yfilter; } if(value_path == "address3") { address3.yfilter = yfilter; } if(value_path == "address4") { address4.yfilter = yfilter; } if(value_path == "address5") { address5.yfilter = yfilter; } if(value_path == "address6") { address6.yfilter = yfilter; } if(value_path == "address7") { address7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Address::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address0" || name == "address1" || name == "address2" || name == "address3" || name == "address4" || name == "address5" || name == "address6" || name == "address7") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet::Subnet() : subnet{YType::str, "subnet"}, mask{YType::uint8, "mask"} { yang_name = "subnet"; yang_parent_name = "ipv6"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet::~Subnet() { } bool Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet::has_data() const { if (is_presence_container) return true; return subnet.is_set || mask.is_set; } bool Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet::has_operation() const { return is_set(yfilter) || ydk::is_set(subnet.yfilter) || ydk::is_set(mask.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "subnet"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (subnet.is_set || is_set(subnet.yfilter)) leaf_name_data.push_back(subnet.get_name_leafdata()); if (mask.is_set || is_set(mask.yfilter)) leaf_name_data.push_back(mask.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "subnet") { subnet = value; subnet.value_namespace = name_space; subnet.value_namespace_prefix = name_space_prefix; } if(value_path == "mask") { mask = value; mask.value_namespace = name_space; mask.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "subnet") { subnet.yfilter = yfilter; } if(value_path == "mask") { mask.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Udp::Ipv6::Subnet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "subnet" || name == "mask") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Direction::Direction() : any{YType::empty, "any"}, destination{YType::empty, "destination"}, source{YType::empty, "source"} { yang_name = "direction"; yang_parent_name = "udp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Udp::Direction::~Direction() { } bool Native::Ip::Nbar::Custom::Transport::Udp::Direction::has_data() const { if (is_presence_container) return true; return any.is_set || destination.is_set || source.is_set; } bool Native::Ip::Nbar::Custom::Transport::Udp::Direction::has_operation() const { return is_set(yfilter) || ydk::is_set(any.yfilter) || ydk::is_set(destination.yfilter) || ydk::is_set(source.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Udp::Direction::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "direction"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::Direction::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (any.is_set || is_set(any.yfilter)) leaf_name_data.push_back(any.get_name_leafdata()); if (destination.is_set || is_set(destination.yfilter)) leaf_name_data.push_back(destination.get_name_leafdata()); if (source.is_set || is_set(source.yfilter)) leaf_name_data.push_back(source.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::Direction::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::Direction::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::Direction::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "any") { any = value; any.value_namespace = name_space; any.value_namespace_prefix = name_space_prefix; } if(value_path == "destination") { destination = value; destination.value_namespace = name_space; destination.value_namespace_prefix = name_space_prefix; } if(value_path == "source") { source = value; source.value_namespace = name_space; source.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Udp::Direction::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "any") { any.yfilter = yfilter; } if(value_path == "destination") { destination.yfilter = yfilter; } if(value_path == "source") { source.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Udp::Direction::has_leaf_or_child_of_name(const std::string & name) const { if(name == "any" || name == "destination" || name == "source") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Port::Port() : port_numbers(this, {"port_number0"}) , range(std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Port::Range>()) { range->parent = this; yang_name = "port"; yang_parent_name = "udp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Udp::Port::~Port() { } bool Native::Ip::Nbar::Custom::Transport::Udp::Port::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<port_numbers.len(); index++) { if(port_numbers[index]->has_data()) return true; } return (range != nullptr && range->has_data()); } bool Native::Ip::Nbar::Custom::Transport::Udp::Port::has_operation() const { for (std::size_t index=0; index<port_numbers.len(); index++) { if(port_numbers[index]->has_operation()) return true; } return is_set(yfilter) || (range != nullptr && range->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::Udp::Port::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "port"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::Port::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::Port::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "port-numbers") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers>(); ent_->parent = this; port_numbers.append(ent_); return ent_; } if(child_yang_name == "range") { if(range == nullptr) { range = std::make_shared<Native::Ip::Nbar::Custom::Transport::Udp::Port::Range>(); } return range; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::Port::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : port_numbers.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(range != nullptr) { _children["range"] = range; } return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::Port::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Transport::Udp::Port::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Transport::Udp::Port::has_leaf_or_child_of_name(const std::string & name) const { if(name == "port-numbers" || name == "range") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers::PortNumbers() : port_number0{YType::uint16, "port-number0"}, port_number1{YType::uint16, "port-number1"}, port_number2{YType::uint16, "port-number2"}, port_number3{YType::uint16, "port-number3"}, port_number4{YType::uint16, "port-number4"}, port_number5{YType::uint16, "port-number5"}, port_number6{YType::uint16, "port-number6"}, port_number7{YType::uint16, "port-number7"} { yang_name = "port-numbers"; yang_parent_name = "port"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers::~PortNumbers() { } bool Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers::has_data() const { if (is_presence_container) return true; return port_number0.is_set || port_number1.is_set || port_number2.is_set || port_number3.is_set || port_number4.is_set || port_number5.is_set || port_number6.is_set || port_number7.is_set; } bool Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers::has_operation() const { return is_set(yfilter) || ydk::is_set(port_number0.yfilter) || ydk::is_set(port_number1.yfilter) || ydk::is_set(port_number2.yfilter) || ydk::is_set(port_number3.yfilter) || ydk::is_set(port_number4.yfilter) || ydk::is_set(port_number5.yfilter) || ydk::is_set(port_number6.yfilter) || ydk::is_set(port_number7.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "port-numbers"; ADD_KEY_TOKEN(port_number0, "port-number0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (port_number0.is_set || is_set(port_number0.yfilter)) leaf_name_data.push_back(port_number0.get_name_leafdata()); if (port_number1.is_set || is_set(port_number1.yfilter)) leaf_name_data.push_back(port_number1.get_name_leafdata()); if (port_number2.is_set || is_set(port_number2.yfilter)) leaf_name_data.push_back(port_number2.get_name_leafdata()); if (port_number3.is_set || is_set(port_number3.yfilter)) leaf_name_data.push_back(port_number3.get_name_leafdata()); if (port_number4.is_set || is_set(port_number4.yfilter)) leaf_name_data.push_back(port_number4.get_name_leafdata()); if (port_number5.is_set || is_set(port_number5.yfilter)) leaf_name_data.push_back(port_number5.get_name_leafdata()); if (port_number6.is_set || is_set(port_number6.yfilter)) leaf_name_data.push_back(port_number6.get_name_leafdata()); if (port_number7.is_set || is_set(port_number7.yfilter)) leaf_name_data.push_back(port_number7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "port-number0") { port_number0 = value; port_number0.value_namespace = name_space; port_number0.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number1") { port_number1 = value; port_number1.value_namespace = name_space; port_number1.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number2") { port_number2 = value; port_number2.value_namespace = name_space; port_number2.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number3") { port_number3 = value; port_number3.value_namespace = name_space; port_number3.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number4") { port_number4 = value; port_number4.value_namespace = name_space; port_number4.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number5") { port_number5 = value; port_number5.value_namespace = name_space; port_number5.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number6") { port_number6 = value; port_number6.value_namespace = name_space; port_number6.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number7") { port_number7 = value; port_number7.value_namespace = name_space; port_number7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "port-number0") { port_number0.yfilter = yfilter; } if(value_path == "port-number1") { port_number1.yfilter = yfilter; } if(value_path == "port-number2") { port_number2.yfilter = yfilter; } if(value_path == "port-number3") { port_number3.yfilter = yfilter; } if(value_path == "port-number4") { port_number4.yfilter = yfilter; } if(value_path == "port-number5") { port_number5.yfilter = yfilter; } if(value_path == "port-number6") { port_number6.yfilter = yfilter; } if(value_path == "port-number7") { port_number7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Udp::Port::PortNumbers::has_leaf_or_child_of_name(const std::string & name) const { if(name == "port-number0" || name == "port-number1" || name == "port-number2" || name == "port-number3" || name == "port-number4" || name == "port-number5" || name == "port-number6" || name == "port-number7") return true; return false; } Native::Ip::Nbar::Custom::Transport::Udp::Port::Range::Range() : start_range{YType::uint16, "start-range"}, end_range{YType::uint16, "end-range"} { yang_name = "range"; yang_parent_name = "port"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::Udp::Port::Range::~Range() { } bool Native::Ip::Nbar::Custom::Transport::Udp::Port::Range::has_data() const { if (is_presence_container) return true; return start_range.is_set || end_range.is_set; } bool Native::Ip::Nbar::Custom::Transport::Udp::Port::Range::has_operation() const { return is_set(yfilter) || ydk::is_set(start_range.yfilter) || ydk::is_set(end_range.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::Udp::Port::Range::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "range"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::Udp::Port::Range::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_range.is_set || is_set(start_range.yfilter)) leaf_name_data.push_back(start_range.get_name_leafdata()); if (end_range.is_set || is_set(end_range.yfilter)) leaf_name_data.push_back(end_range.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::Udp::Port::Range::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::Udp::Port::Range::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::Udp::Port::Range::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-range") { start_range = value; start_range.value_namespace = name_space; start_range.value_namespace_prefix = name_space_prefix; } if(value_path == "end-range") { end_range = value; end_range.value_namespace = name_space; end_range.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::Udp::Port::Range::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-range") { start_range.yfilter = yfilter; } if(value_path == "end-range") { end_range.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::Udp::Port::Range::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-range" || name == "end-range") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::UdpTcp() : id{YType::uint16, "id"} , dscp(std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp>()) , ip(std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_>()) , ipv6(std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6>()) , direction(std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction>()) , port(std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Port>()) { dscp->parent = this; ip->parent = this; ipv6->parent = this; direction->parent = this; port->parent = this; yang_name = "udp-tcp"; yang_parent_name = "transport"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::~UdpTcp() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::has_data() const { if (is_presence_container) return true; return id.is_set || (dscp != nullptr && dscp->has_data()) || (ip != nullptr && ip->has_data()) || (ipv6 != nullptr && ipv6->has_data()) || (direction != nullptr && direction->has_data()) || (port != nullptr && port->has_data()); } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::has_operation() const { return is_set(yfilter) || ydk::is_set(id.yfilter) || (dscp != nullptr && dscp->has_operation()) || (ip != nullptr && ip->has_operation()) || (ipv6 != nullptr && ipv6->has_operation()) || (direction != nullptr && direction->has_operation()) || (port != nullptr && port->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "udp-tcp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (id.is_set || is_set(id.yfilter)) leaf_name_data.push_back(id.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dscp") { if(dscp == nullptr) { dscp = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp>(); } return dscp; } if(child_yang_name == "ip") { if(ip == nullptr) { ip = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_>(); } return ip; } if(child_yang_name == "ipv6") { if(ipv6 == nullptr) { ipv6 = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6>(); } return ipv6; } if(child_yang_name == "direction") { if(direction == nullptr) { direction = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction>(); } return direction; } if(child_yang_name == "port") { if(port == nullptr) { port = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Port>(); } return port; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(dscp != nullptr) { _children["dscp"] = dscp; } if(ip != nullptr) { _children["ip"] = ip; } if(ipv6 != nullptr) { _children["ipv6"] = ipv6; } if(direction != nullptr) { _children["direction"] = direction; } if(port != nullptr) { _children["port"] = port; } return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "id") { id = value; id.value_namespace = name_space; id.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::UdpTcp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "id") { id.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dscp" || name == "ip" || name == "ipv6" || name == "direction" || name == "port" || name == "id") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp::Dscp() : range{YType::uint8, "range"}, af11{YType::empty, "af11"}, af12{YType::empty, "af12"}, af13{YType::empty, "af13"}, af21{YType::empty, "af21"}, af22{YType::empty, "af22"}, af23{YType::empty, "af23"}, af31{YType::empty, "af31"}, af32{YType::empty, "af32"}, af33{YType::empty, "af33"}, af41{YType::empty, "af41"}, af42{YType::empty, "af42"}, af43{YType::empty, "af43"}, cs1{YType::empty, "cs1"}, cs2{YType::empty, "cs2"}, cs3{YType::empty, "cs3"}, cs4{YType::empty, "cs4"}, cs5{YType::empty, "cs5"}, cs6{YType::empty, "cs6"}, cs7{YType::empty, "cs7"}, default_{YType::empty, "default"}, ef{YType::empty, "ef"} { yang_name = "dscp"; yang_parent_name = "udp-tcp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp::~Dscp() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp::has_data() const { if (is_presence_container) return true; return range.is_set || af11.is_set || af12.is_set || af13.is_set || af21.is_set || af22.is_set || af23.is_set || af31.is_set || af32.is_set || af33.is_set || af41.is_set || af42.is_set || af43.is_set || cs1.is_set || cs2.is_set || cs3.is_set || cs4.is_set || cs5.is_set || cs6.is_set || cs7.is_set || default_.is_set || ef.is_set; } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp::has_operation() const { return is_set(yfilter) || ydk::is_set(range.yfilter) || ydk::is_set(af11.yfilter) || ydk::is_set(af12.yfilter) || ydk::is_set(af13.yfilter) || ydk::is_set(af21.yfilter) || ydk::is_set(af22.yfilter) || ydk::is_set(af23.yfilter) || ydk::is_set(af31.yfilter) || ydk::is_set(af32.yfilter) || ydk::is_set(af33.yfilter) || ydk::is_set(af41.yfilter) || ydk::is_set(af42.yfilter) || ydk::is_set(af43.yfilter) || ydk::is_set(cs1.yfilter) || ydk::is_set(cs2.yfilter) || ydk::is_set(cs3.yfilter) || ydk::is_set(cs4.yfilter) || ydk::is_set(cs5.yfilter) || ydk::is_set(cs6.yfilter) || ydk::is_set(cs7.yfilter) || ydk::is_set(default_.yfilter) || ydk::is_set(ef.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dscp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (range.is_set || is_set(range.yfilter)) leaf_name_data.push_back(range.get_name_leafdata()); if (af11.is_set || is_set(af11.yfilter)) leaf_name_data.push_back(af11.get_name_leafdata()); if (af12.is_set || is_set(af12.yfilter)) leaf_name_data.push_back(af12.get_name_leafdata()); if (af13.is_set || is_set(af13.yfilter)) leaf_name_data.push_back(af13.get_name_leafdata()); if (af21.is_set || is_set(af21.yfilter)) leaf_name_data.push_back(af21.get_name_leafdata()); if (af22.is_set || is_set(af22.yfilter)) leaf_name_data.push_back(af22.get_name_leafdata()); if (af23.is_set || is_set(af23.yfilter)) leaf_name_data.push_back(af23.get_name_leafdata()); if (af31.is_set || is_set(af31.yfilter)) leaf_name_data.push_back(af31.get_name_leafdata()); if (af32.is_set || is_set(af32.yfilter)) leaf_name_data.push_back(af32.get_name_leafdata()); if (af33.is_set || is_set(af33.yfilter)) leaf_name_data.push_back(af33.get_name_leafdata()); if (af41.is_set || is_set(af41.yfilter)) leaf_name_data.push_back(af41.get_name_leafdata()); if (af42.is_set || is_set(af42.yfilter)) leaf_name_data.push_back(af42.get_name_leafdata()); if (af43.is_set || is_set(af43.yfilter)) leaf_name_data.push_back(af43.get_name_leafdata()); if (cs1.is_set || is_set(cs1.yfilter)) leaf_name_data.push_back(cs1.get_name_leafdata()); if (cs2.is_set || is_set(cs2.yfilter)) leaf_name_data.push_back(cs2.get_name_leafdata()); if (cs3.is_set || is_set(cs3.yfilter)) leaf_name_data.push_back(cs3.get_name_leafdata()); if (cs4.is_set || is_set(cs4.yfilter)) leaf_name_data.push_back(cs4.get_name_leafdata()); if (cs5.is_set || is_set(cs5.yfilter)) leaf_name_data.push_back(cs5.get_name_leafdata()); if (cs6.is_set || is_set(cs6.yfilter)) leaf_name_data.push_back(cs6.get_name_leafdata()); if (cs7.is_set || is_set(cs7.yfilter)) leaf_name_data.push_back(cs7.get_name_leafdata()); if (default_.is_set || is_set(default_.yfilter)) leaf_name_data.push_back(default_.get_name_leafdata()); if (ef.is_set || is_set(ef.yfilter)) leaf_name_data.push_back(ef.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "range") { range = value; range.value_namespace = name_space; range.value_namespace_prefix = name_space_prefix; } if(value_path == "af11") { af11 = value; af11.value_namespace = name_space; af11.value_namespace_prefix = name_space_prefix; } if(value_path == "af12") { af12 = value; af12.value_namespace = name_space; af12.value_namespace_prefix = name_space_prefix; } if(value_path == "af13") { af13 = value; af13.value_namespace = name_space; af13.value_namespace_prefix = name_space_prefix; } if(value_path == "af21") { af21 = value; af21.value_namespace = name_space; af21.value_namespace_prefix = name_space_prefix; } if(value_path == "af22") { af22 = value; af22.value_namespace = name_space; af22.value_namespace_prefix = name_space_prefix; } if(value_path == "af23") { af23 = value; af23.value_namespace = name_space; af23.value_namespace_prefix = name_space_prefix; } if(value_path == "af31") { af31 = value; af31.value_namespace = name_space; af31.value_namespace_prefix = name_space_prefix; } if(value_path == "af32") { af32 = value; af32.value_namespace = name_space; af32.value_namespace_prefix = name_space_prefix; } if(value_path == "af33") { af33 = value; af33.value_namespace = name_space; af33.value_namespace_prefix = name_space_prefix; } if(value_path == "af41") { af41 = value; af41.value_namespace = name_space; af41.value_namespace_prefix = name_space_prefix; } if(value_path == "af42") { af42 = value; af42.value_namespace = name_space; af42.value_namespace_prefix = name_space_prefix; } if(value_path == "af43") { af43 = value; af43.value_namespace = name_space; af43.value_namespace_prefix = name_space_prefix; } if(value_path == "cs1") { cs1 = value; cs1.value_namespace = name_space; cs1.value_namespace_prefix = name_space_prefix; } if(value_path == "cs2") { cs2 = value; cs2.value_namespace = name_space; cs2.value_namespace_prefix = name_space_prefix; } if(value_path == "cs3") { cs3 = value; cs3.value_namespace = name_space; cs3.value_namespace_prefix = name_space_prefix; } if(value_path == "cs4") { cs4 = value; cs4.value_namespace = name_space; cs4.value_namespace_prefix = name_space_prefix; } if(value_path == "cs5") { cs5 = value; cs5.value_namespace = name_space; cs5.value_namespace_prefix = name_space_prefix; } if(value_path == "cs6") { cs6 = value; cs6.value_namespace = name_space; cs6.value_namespace_prefix = name_space_prefix; } if(value_path == "cs7") { cs7 = value; cs7.value_namespace = name_space; cs7.value_namespace_prefix = name_space_prefix; } if(value_path == "default") { default_ = value; default_.value_namespace = name_space; default_.value_namespace_prefix = name_space_prefix; } if(value_path == "ef") { ef = value; ef.value_namespace = name_space; ef.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "range") { range.yfilter = yfilter; } if(value_path == "af11") { af11.yfilter = yfilter; } if(value_path == "af12") { af12.yfilter = yfilter; } if(value_path == "af13") { af13.yfilter = yfilter; } if(value_path == "af21") { af21.yfilter = yfilter; } if(value_path == "af22") { af22.yfilter = yfilter; } if(value_path == "af23") { af23.yfilter = yfilter; } if(value_path == "af31") { af31.yfilter = yfilter; } if(value_path == "af32") { af32.yfilter = yfilter; } if(value_path == "af33") { af33.yfilter = yfilter; } if(value_path == "af41") { af41.yfilter = yfilter; } if(value_path == "af42") { af42.yfilter = yfilter; } if(value_path == "af43") { af43.yfilter = yfilter; } if(value_path == "cs1") { cs1.yfilter = yfilter; } if(value_path == "cs2") { cs2.yfilter = yfilter; } if(value_path == "cs3") { cs3.yfilter = yfilter; } if(value_path == "cs4") { cs4.yfilter = yfilter; } if(value_path == "cs5") { cs5.yfilter = yfilter; } if(value_path == "cs6") { cs6.yfilter = yfilter; } if(value_path == "cs7") { cs7.yfilter = yfilter; } if(value_path == "default") { default_.yfilter = yfilter; } if(value_path == "ef") { ef.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Dscp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "range" || name == "af11" || name == "af12" || name == "af13" || name == "af21" || name == "af22" || name == "af23" || name == "af31" || name == "af32" || name == "af33" || name == "af41" || name == "af42" || name == "af43" || name == "cs1" || name == "cs2" || name == "cs3" || name == "cs4" || name == "cs5" || name == "cs6" || name == "cs7" || name == "default" || name == "ef") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Ip_() : address(this, {"address0"}) , subnet(std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet>()) { subnet->parent = this; yang_name = "ip"; yang_parent_name = "udp-tcp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::~Ip_() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_data()) return true; } return (subnet != nullptr && subnet->has_data()); } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::has_operation() const { for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_operation()) return true; } return is_set(yfilter) || (subnet != nullptr && subnet->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ip"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "address") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address>(); ent_->parent = this; address.append(ent_); return ent_; } if(child_yang_name == "subnet") { if(subnet == nullptr) { subnet = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet>(); } return subnet; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(subnet != nullptr) { _children["subnet"] = subnet; } return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address" || name == "subnet") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address::Address() : address0{YType::str, "address0"}, address1{YType::str, "address1"}, address2{YType::str, "address2"}, address3{YType::str, "address3"}, address4{YType::str, "address4"}, address5{YType::str, "address5"}, address6{YType::str, "address6"}, address7{YType::str, "address7"} { yang_name = "address"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address::~Address() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address::has_data() const { if (is_presence_container) return true; return address0.is_set || address1.is_set || address2.is_set || address3.is_set || address4.is_set || address5.is_set || address6.is_set || address7.is_set; } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address::has_operation() const { return is_set(yfilter) || ydk::is_set(address0.yfilter) || ydk::is_set(address1.yfilter) || ydk::is_set(address2.yfilter) || ydk::is_set(address3.yfilter) || ydk::is_set(address4.yfilter) || ydk::is_set(address5.yfilter) || ydk::is_set(address6.yfilter) || ydk::is_set(address7.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "address"; ADD_KEY_TOKEN(address0, "address0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (address0.is_set || is_set(address0.yfilter)) leaf_name_data.push_back(address0.get_name_leafdata()); if (address1.is_set || is_set(address1.yfilter)) leaf_name_data.push_back(address1.get_name_leafdata()); if (address2.is_set || is_set(address2.yfilter)) leaf_name_data.push_back(address2.get_name_leafdata()); if (address3.is_set || is_set(address3.yfilter)) leaf_name_data.push_back(address3.get_name_leafdata()); if (address4.is_set || is_set(address4.yfilter)) leaf_name_data.push_back(address4.get_name_leafdata()); if (address5.is_set || is_set(address5.yfilter)) leaf_name_data.push_back(address5.get_name_leafdata()); if (address6.is_set || is_set(address6.yfilter)) leaf_name_data.push_back(address6.get_name_leafdata()); if (address7.is_set || is_set(address7.yfilter)) leaf_name_data.push_back(address7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "address0") { address0 = value; address0.value_namespace = name_space; address0.value_namespace_prefix = name_space_prefix; } if(value_path == "address1") { address1 = value; address1.value_namespace = name_space; address1.value_namespace_prefix = name_space_prefix; } if(value_path == "address2") { address2 = value; address2.value_namespace = name_space; address2.value_namespace_prefix = name_space_prefix; } if(value_path == "address3") { address3 = value; address3.value_namespace = name_space; address3.value_namespace_prefix = name_space_prefix; } if(value_path == "address4") { address4 = value; address4.value_namespace = name_space; address4.value_namespace_prefix = name_space_prefix; } if(value_path == "address5") { address5 = value; address5.value_namespace = name_space; address5.value_namespace_prefix = name_space_prefix; } if(value_path == "address6") { address6 = value; address6.value_namespace = name_space; address6.value_namespace_prefix = name_space_prefix; } if(value_path == "address7") { address7 = value; address7.value_namespace = name_space; address7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "address0") { address0.yfilter = yfilter; } if(value_path == "address1") { address1.yfilter = yfilter; } if(value_path == "address2") { address2.yfilter = yfilter; } if(value_path == "address3") { address3.yfilter = yfilter; } if(value_path == "address4") { address4.yfilter = yfilter; } if(value_path == "address5") { address5.yfilter = yfilter; } if(value_path == "address6") { address6.yfilter = yfilter; } if(value_path == "address7") { address7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Address::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address0" || name == "address1" || name == "address2" || name == "address3" || name == "address4" || name == "address5" || name == "address6" || name == "address7") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet::Subnet() : subnet{YType::str, "subnet"}, mask{YType::uint8, "mask"} { yang_name = "subnet"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet::~Subnet() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet::has_data() const { if (is_presence_container) return true; return subnet.is_set || mask.is_set; } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet::has_operation() const { return is_set(yfilter) || ydk::is_set(subnet.yfilter) || ydk::is_set(mask.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "subnet"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (subnet.is_set || is_set(subnet.yfilter)) leaf_name_data.push_back(subnet.get_name_leafdata()); if (mask.is_set || is_set(mask.yfilter)) leaf_name_data.push_back(mask.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "subnet") { subnet = value; subnet.value_namespace = name_space; subnet.value_namespace_prefix = name_space_prefix; } if(value_path == "mask") { mask = value; mask.value_namespace = name_space; mask.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "subnet") { subnet.yfilter = yfilter; } if(value_path == "mask") { mask.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ip_::Subnet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "subnet" || name == "mask") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Ipv6() : address(this, {"address0"}) , subnet(std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet>()) { subnet->parent = this; yang_name = "ipv6"; yang_parent_name = "udp-tcp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::~Ipv6() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_data()) return true; } return (subnet != nullptr && subnet->has_data()); } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::has_operation() const { for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_operation()) return true; } return is_set(yfilter) || (subnet != nullptr && subnet->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "address") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address>(); ent_->parent = this; address.append(ent_); return ent_; } if(child_yang_name == "subnet") { if(subnet == nullptr) { subnet = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet>(); } return subnet; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(subnet != nullptr) { _children["subnet"] = subnet; } return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address" || name == "subnet") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address::Address() : address0{YType::str, "address0"}, address1{YType::str, "address1"}, address2{YType::str, "address2"}, address3{YType::str, "address3"}, address4{YType::str, "address4"}, address5{YType::str, "address5"}, address6{YType::str, "address6"}, address7{YType::str, "address7"} { yang_name = "address"; yang_parent_name = "ipv6"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address::~Address() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address::has_data() const { if (is_presence_container) return true; return address0.is_set || address1.is_set || address2.is_set || address3.is_set || address4.is_set || address5.is_set || address6.is_set || address7.is_set; } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address::has_operation() const { return is_set(yfilter) || ydk::is_set(address0.yfilter) || ydk::is_set(address1.yfilter) || ydk::is_set(address2.yfilter) || ydk::is_set(address3.yfilter) || ydk::is_set(address4.yfilter) || ydk::is_set(address5.yfilter) || ydk::is_set(address6.yfilter) || ydk::is_set(address7.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "address"; ADD_KEY_TOKEN(address0, "address0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (address0.is_set || is_set(address0.yfilter)) leaf_name_data.push_back(address0.get_name_leafdata()); if (address1.is_set || is_set(address1.yfilter)) leaf_name_data.push_back(address1.get_name_leafdata()); if (address2.is_set || is_set(address2.yfilter)) leaf_name_data.push_back(address2.get_name_leafdata()); if (address3.is_set || is_set(address3.yfilter)) leaf_name_data.push_back(address3.get_name_leafdata()); if (address4.is_set || is_set(address4.yfilter)) leaf_name_data.push_back(address4.get_name_leafdata()); if (address5.is_set || is_set(address5.yfilter)) leaf_name_data.push_back(address5.get_name_leafdata()); if (address6.is_set || is_set(address6.yfilter)) leaf_name_data.push_back(address6.get_name_leafdata()); if (address7.is_set || is_set(address7.yfilter)) leaf_name_data.push_back(address7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "address0") { address0 = value; address0.value_namespace = name_space; address0.value_namespace_prefix = name_space_prefix; } if(value_path == "address1") { address1 = value; address1.value_namespace = name_space; address1.value_namespace_prefix = name_space_prefix; } if(value_path == "address2") { address2 = value; address2.value_namespace = name_space; address2.value_namespace_prefix = name_space_prefix; } if(value_path == "address3") { address3 = value; address3.value_namespace = name_space; address3.value_namespace_prefix = name_space_prefix; } if(value_path == "address4") { address4 = value; address4.value_namespace = name_space; address4.value_namespace_prefix = name_space_prefix; } if(value_path == "address5") { address5 = value; address5.value_namespace = name_space; address5.value_namespace_prefix = name_space_prefix; } if(value_path == "address6") { address6 = value; address6.value_namespace = name_space; address6.value_namespace_prefix = name_space_prefix; } if(value_path == "address7") { address7 = value; address7.value_namespace = name_space; address7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "address0") { address0.yfilter = yfilter; } if(value_path == "address1") { address1.yfilter = yfilter; } if(value_path == "address2") { address2.yfilter = yfilter; } if(value_path == "address3") { address3.yfilter = yfilter; } if(value_path == "address4") { address4.yfilter = yfilter; } if(value_path == "address5") { address5.yfilter = yfilter; } if(value_path == "address6") { address6.yfilter = yfilter; } if(value_path == "address7") { address7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Address::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address0" || name == "address1" || name == "address2" || name == "address3" || name == "address4" || name == "address5" || name == "address6" || name == "address7") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet::Subnet() : subnet{YType::str, "subnet"}, mask{YType::uint8, "mask"} { yang_name = "subnet"; yang_parent_name = "ipv6"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet::~Subnet() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet::has_data() const { if (is_presence_container) return true; return subnet.is_set || mask.is_set; } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet::has_operation() const { return is_set(yfilter) || ydk::is_set(subnet.yfilter) || ydk::is_set(mask.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "subnet"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (subnet.is_set || is_set(subnet.yfilter)) leaf_name_data.push_back(subnet.get_name_leafdata()); if (mask.is_set || is_set(mask.yfilter)) leaf_name_data.push_back(mask.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "subnet") { subnet = value; subnet.value_namespace = name_space; subnet.value_namespace_prefix = name_space_prefix; } if(value_path == "mask") { mask = value; mask.value_namespace = name_space; mask.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "subnet") { subnet.yfilter = yfilter; } if(value_path == "mask") { mask.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Ipv6::Subnet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "subnet" || name == "mask") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction::Direction() : any{YType::empty, "any"}, destination{YType::empty, "destination"}, source{YType::empty, "source"} { yang_name = "direction"; yang_parent_name = "udp-tcp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction::~Direction() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction::has_data() const { if (is_presence_container) return true; return any.is_set || destination.is_set || source.is_set; } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction::has_operation() const { return is_set(yfilter) || ydk::is_set(any.yfilter) || ydk::is_set(destination.yfilter) || ydk::is_set(source.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "direction"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (any.is_set || is_set(any.yfilter)) leaf_name_data.push_back(any.get_name_leafdata()); if (destination.is_set || is_set(destination.yfilter)) leaf_name_data.push_back(destination.get_name_leafdata()); if (source.is_set || is_set(source.yfilter)) leaf_name_data.push_back(source.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "any") { any = value; any.value_namespace = name_space; any.value_namespace_prefix = name_space_prefix; } if(value_path == "destination") { destination = value; destination.value_namespace = name_space; destination.value_namespace_prefix = name_space_prefix; } if(value_path == "source") { source = value; source.value_namespace = name_space; source.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "any") { any.yfilter = yfilter; } if(value_path == "destination") { destination.yfilter = yfilter; } if(value_path == "source") { source.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Direction::has_leaf_or_child_of_name(const std::string & name) const { if(name == "any" || name == "destination" || name == "source") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Port() : port_numbers(this, {"port_number0"}) , range(std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range>()) { range->parent = this; yang_name = "port"; yang_parent_name = "udp-tcp"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::~Port() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<port_numbers.len(); index++) { if(port_numbers[index]->has_data()) return true; } return (range != nullptr && range->has_data()); } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::has_operation() const { for (std::size_t index=0; index<port_numbers.len(); index++) { if(port_numbers[index]->has_operation()) return true; } return is_set(yfilter) || (range != nullptr && range->has_operation()); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "port"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "port-numbers") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers>(); ent_->parent = this; port_numbers.append(ent_); return ent_; } if(child_yang_name == "range") { if(range == nullptr) { range = std::make_shared<Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range>(); } return range; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : port_numbers.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(range != nullptr) { _children["range"] = range; } return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::has_leaf_or_child_of_name(const std::string & name) const { if(name == "port-numbers" || name == "range") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers::PortNumbers() : port_number0{YType::uint16, "port-number0"}, port_number1{YType::uint16, "port-number1"}, port_number2{YType::uint16, "port-number2"}, port_number3{YType::uint16, "port-number3"}, port_number4{YType::uint16, "port-number4"}, port_number5{YType::uint16, "port-number5"}, port_number6{YType::uint16, "port-number6"}, port_number7{YType::uint16, "port-number7"} { yang_name = "port-numbers"; yang_parent_name = "port"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers::~PortNumbers() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers::has_data() const { if (is_presence_container) return true; return port_number0.is_set || port_number1.is_set || port_number2.is_set || port_number3.is_set || port_number4.is_set || port_number5.is_set || port_number6.is_set || port_number7.is_set; } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers::has_operation() const { return is_set(yfilter) || ydk::is_set(port_number0.yfilter) || ydk::is_set(port_number1.yfilter) || ydk::is_set(port_number2.yfilter) || ydk::is_set(port_number3.yfilter) || ydk::is_set(port_number4.yfilter) || ydk::is_set(port_number5.yfilter) || ydk::is_set(port_number6.yfilter) || ydk::is_set(port_number7.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "port-numbers"; ADD_KEY_TOKEN(port_number0, "port-number0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (port_number0.is_set || is_set(port_number0.yfilter)) leaf_name_data.push_back(port_number0.get_name_leafdata()); if (port_number1.is_set || is_set(port_number1.yfilter)) leaf_name_data.push_back(port_number1.get_name_leafdata()); if (port_number2.is_set || is_set(port_number2.yfilter)) leaf_name_data.push_back(port_number2.get_name_leafdata()); if (port_number3.is_set || is_set(port_number3.yfilter)) leaf_name_data.push_back(port_number3.get_name_leafdata()); if (port_number4.is_set || is_set(port_number4.yfilter)) leaf_name_data.push_back(port_number4.get_name_leafdata()); if (port_number5.is_set || is_set(port_number5.yfilter)) leaf_name_data.push_back(port_number5.get_name_leafdata()); if (port_number6.is_set || is_set(port_number6.yfilter)) leaf_name_data.push_back(port_number6.get_name_leafdata()); if (port_number7.is_set || is_set(port_number7.yfilter)) leaf_name_data.push_back(port_number7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "port-number0") { port_number0 = value; port_number0.value_namespace = name_space; port_number0.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number1") { port_number1 = value; port_number1.value_namespace = name_space; port_number1.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number2") { port_number2 = value; port_number2.value_namespace = name_space; port_number2.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number3") { port_number3 = value; port_number3.value_namespace = name_space; port_number3.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number4") { port_number4 = value; port_number4.value_namespace = name_space; port_number4.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number5") { port_number5 = value; port_number5.value_namespace = name_space; port_number5.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number6") { port_number6 = value; port_number6.value_namespace = name_space; port_number6.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number7") { port_number7 = value; port_number7.value_namespace = name_space; port_number7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "port-number0") { port_number0.yfilter = yfilter; } if(value_path == "port-number1") { port_number1.yfilter = yfilter; } if(value_path == "port-number2") { port_number2.yfilter = yfilter; } if(value_path == "port-number3") { port_number3.yfilter = yfilter; } if(value_path == "port-number4") { port_number4.yfilter = yfilter; } if(value_path == "port-number5") { port_number5.yfilter = yfilter; } if(value_path == "port-number6") { port_number6.yfilter = yfilter; } if(value_path == "port-number7") { port_number7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::PortNumbers::has_leaf_or_child_of_name(const std::string & name) const { if(name == "port-number0" || name == "port-number1" || name == "port-number2" || name == "port-number3" || name == "port-number4" || name == "port-number5" || name == "port-number6" || name == "port-number7") return true; return false; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range::Range() : start_range{YType::uint16, "start-range"}, end_range{YType::uint16, "end-range"} { yang_name = "range"; yang_parent_name = "port"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range::~Range() { } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range::has_data() const { if (is_presence_container) return true; return start_range.is_set || end_range.is_set; } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range::has_operation() const { return is_set(yfilter) || ydk::is_set(start_range.yfilter) || ydk::is_set(end_range.yfilter); } std::string Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "range"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_range.is_set || is_set(start_range.yfilter)) leaf_name_data.push_back(start_range.get_name_leafdata()); if (end_range.is_set || is_set(end_range.yfilter)) leaf_name_data.push_back(end_range.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-range") { start_range = value; start_range.value_namespace = name_space; start_range.value_namespace_prefix = name_space_prefix; } if(value_path == "end-range") { end_range = value; end_range.value_namespace = name_space; end_range.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-range") { start_range.yfilter = yfilter; } if(value_path == "end-range") { end_range.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Transport::UdpTcp::Port::Range::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-range" || name == "end-range") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Ip_() : any(nullptr) // presence node { yang_name = "ip"; yang_parent_name = "custom"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::~Ip_() { } bool Native::Ip::Nbar::Custom::Ip_::has_data() const { if (is_presence_container) return true; return (any != nullptr && any->has_data()); } bool Native::Ip::Nbar::Custom::Ip_::has_operation() const { return is_set(yfilter) || (any != nullptr && any->has_operation()); } std::string Native::Ip::Nbar::Custom::Ip_::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ip"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "any") { if(any == nullptr) { any = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any>(); } return any; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(any != nullptr) { _children["any"] = any; } return _children; } void Native::Ip::Nbar::Custom::Ip_::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Ip_::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Ip_::has_leaf_or_child_of_name(const std::string & name) const { if(name == "any") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Any() : id{YType::uint16, "id"} , dscp(std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Dscp>()) , ip(std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Ip_>()) , ipv6(std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Ipv6>()) , direction(std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Direction>()) , port(std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Port>()) { dscp->parent = this; ip->parent = this; ipv6->parent = this; direction->parent = this; port->parent = this; yang_name = "any"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Native::Ip::Nbar::Custom::Ip_::Any::~Any() { } bool Native::Ip::Nbar::Custom::Ip_::Any::has_data() const { if (is_presence_container) return true; return id.is_set || (dscp != nullptr && dscp->has_data()) || (ip != nullptr && ip->has_data()) || (ipv6 != nullptr && ipv6->has_data()) || (direction != nullptr && direction->has_data()) || (port != nullptr && port->has_data()); } bool Native::Ip::Nbar::Custom::Ip_::Any::has_operation() const { return is_set(yfilter) || ydk::is_set(id.yfilter) || (dscp != nullptr && dscp->has_operation()) || (ip != nullptr && ip->has_operation()) || (ipv6 != nullptr && ipv6->has_operation()) || (direction != nullptr && direction->has_operation()) || (port != nullptr && port->has_operation()); } std::string Native::Ip::Nbar::Custom::Ip_::Any::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "any"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (id.is_set || is_set(id.yfilter)) leaf_name_data.push_back(id.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dscp") { if(dscp == nullptr) { dscp = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Dscp>(); } return dscp; } if(child_yang_name == "ip") { if(ip == nullptr) { ip = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Ip_>(); } return ip; } if(child_yang_name == "ipv6") { if(ipv6 == nullptr) { ipv6 = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Ipv6>(); } return ipv6; } if(child_yang_name == "direction") { if(direction == nullptr) { direction = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Direction>(); } return direction; } if(child_yang_name == "port") { if(port == nullptr) { port = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Port>(); } return port; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(dscp != nullptr) { _children["dscp"] = dscp; } if(ip != nullptr) { _children["ip"] = ip; } if(ipv6 != nullptr) { _children["ipv6"] = ipv6; } if(direction != nullptr) { _children["direction"] = direction; } if(port != nullptr) { _children["port"] = port; } return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "id") { id = value; id.value_namespace = name_space; id.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Ip_::Any::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "id") { id.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Ip_::Any::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dscp" || name == "ip" || name == "ipv6" || name == "direction" || name == "port" || name == "id") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Dscp::Dscp() : range{YType::uint8, "range"}, af11{YType::empty, "af11"}, af12{YType::empty, "af12"}, af13{YType::empty, "af13"}, af21{YType::empty, "af21"}, af22{YType::empty, "af22"}, af23{YType::empty, "af23"}, af31{YType::empty, "af31"}, af32{YType::empty, "af32"}, af33{YType::empty, "af33"}, af41{YType::empty, "af41"}, af42{YType::empty, "af42"}, af43{YType::empty, "af43"}, cs1{YType::empty, "cs1"}, cs2{YType::empty, "cs2"}, cs3{YType::empty, "cs3"}, cs4{YType::empty, "cs4"}, cs5{YType::empty, "cs5"}, cs6{YType::empty, "cs6"}, cs7{YType::empty, "cs7"}, default_{YType::empty, "default"}, ef{YType::empty, "ef"} { yang_name = "dscp"; yang_parent_name = "any"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::Any::Dscp::~Dscp() { } bool Native::Ip::Nbar::Custom::Ip_::Any::Dscp::has_data() const { if (is_presence_container) return true; return range.is_set || af11.is_set || af12.is_set || af13.is_set || af21.is_set || af22.is_set || af23.is_set || af31.is_set || af32.is_set || af33.is_set || af41.is_set || af42.is_set || af43.is_set || cs1.is_set || cs2.is_set || cs3.is_set || cs4.is_set || cs5.is_set || cs6.is_set || cs7.is_set || default_.is_set || ef.is_set; } bool Native::Ip::Nbar::Custom::Ip_::Any::Dscp::has_operation() const { return is_set(yfilter) || ydk::is_set(range.yfilter) || ydk::is_set(af11.yfilter) || ydk::is_set(af12.yfilter) || ydk::is_set(af13.yfilter) || ydk::is_set(af21.yfilter) || ydk::is_set(af22.yfilter) || ydk::is_set(af23.yfilter) || ydk::is_set(af31.yfilter) || ydk::is_set(af32.yfilter) || ydk::is_set(af33.yfilter) || ydk::is_set(af41.yfilter) || ydk::is_set(af42.yfilter) || ydk::is_set(af43.yfilter) || ydk::is_set(cs1.yfilter) || ydk::is_set(cs2.yfilter) || ydk::is_set(cs3.yfilter) || ydk::is_set(cs4.yfilter) || ydk::is_set(cs5.yfilter) || ydk::is_set(cs6.yfilter) || ydk::is_set(cs7.yfilter) || ydk::is_set(default_.yfilter) || ydk::is_set(ef.yfilter); } std::string Native::Ip::Nbar::Custom::Ip_::Any::Dscp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dscp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::Dscp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (range.is_set || is_set(range.yfilter)) leaf_name_data.push_back(range.get_name_leafdata()); if (af11.is_set || is_set(af11.yfilter)) leaf_name_data.push_back(af11.get_name_leafdata()); if (af12.is_set || is_set(af12.yfilter)) leaf_name_data.push_back(af12.get_name_leafdata()); if (af13.is_set || is_set(af13.yfilter)) leaf_name_data.push_back(af13.get_name_leafdata()); if (af21.is_set || is_set(af21.yfilter)) leaf_name_data.push_back(af21.get_name_leafdata()); if (af22.is_set || is_set(af22.yfilter)) leaf_name_data.push_back(af22.get_name_leafdata()); if (af23.is_set || is_set(af23.yfilter)) leaf_name_data.push_back(af23.get_name_leafdata()); if (af31.is_set || is_set(af31.yfilter)) leaf_name_data.push_back(af31.get_name_leafdata()); if (af32.is_set || is_set(af32.yfilter)) leaf_name_data.push_back(af32.get_name_leafdata()); if (af33.is_set || is_set(af33.yfilter)) leaf_name_data.push_back(af33.get_name_leafdata()); if (af41.is_set || is_set(af41.yfilter)) leaf_name_data.push_back(af41.get_name_leafdata()); if (af42.is_set || is_set(af42.yfilter)) leaf_name_data.push_back(af42.get_name_leafdata()); if (af43.is_set || is_set(af43.yfilter)) leaf_name_data.push_back(af43.get_name_leafdata()); if (cs1.is_set || is_set(cs1.yfilter)) leaf_name_data.push_back(cs1.get_name_leafdata()); if (cs2.is_set || is_set(cs2.yfilter)) leaf_name_data.push_back(cs2.get_name_leafdata()); if (cs3.is_set || is_set(cs3.yfilter)) leaf_name_data.push_back(cs3.get_name_leafdata()); if (cs4.is_set || is_set(cs4.yfilter)) leaf_name_data.push_back(cs4.get_name_leafdata()); if (cs5.is_set || is_set(cs5.yfilter)) leaf_name_data.push_back(cs5.get_name_leafdata()); if (cs6.is_set || is_set(cs6.yfilter)) leaf_name_data.push_back(cs6.get_name_leafdata()); if (cs7.is_set || is_set(cs7.yfilter)) leaf_name_data.push_back(cs7.get_name_leafdata()); if (default_.is_set || is_set(default_.yfilter)) leaf_name_data.push_back(default_.get_name_leafdata()); if (ef.is_set || is_set(ef.yfilter)) leaf_name_data.push_back(ef.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::Dscp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::Dscp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::Dscp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "range") { range = value; range.value_namespace = name_space; range.value_namespace_prefix = name_space_prefix; } if(value_path == "af11") { af11 = value; af11.value_namespace = name_space; af11.value_namespace_prefix = name_space_prefix; } if(value_path == "af12") { af12 = value; af12.value_namespace = name_space; af12.value_namespace_prefix = name_space_prefix; } if(value_path == "af13") { af13 = value; af13.value_namespace = name_space; af13.value_namespace_prefix = name_space_prefix; } if(value_path == "af21") { af21 = value; af21.value_namespace = name_space; af21.value_namespace_prefix = name_space_prefix; } if(value_path == "af22") { af22 = value; af22.value_namespace = name_space; af22.value_namespace_prefix = name_space_prefix; } if(value_path == "af23") { af23 = value; af23.value_namespace = name_space; af23.value_namespace_prefix = name_space_prefix; } if(value_path == "af31") { af31 = value; af31.value_namespace = name_space; af31.value_namespace_prefix = name_space_prefix; } if(value_path == "af32") { af32 = value; af32.value_namespace = name_space; af32.value_namespace_prefix = name_space_prefix; } if(value_path == "af33") { af33 = value; af33.value_namespace = name_space; af33.value_namespace_prefix = name_space_prefix; } if(value_path == "af41") { af41 = value; af41.value_namespace = name_space; af41.value_namespace_prefix = name_space_prefix; } if(value_path == "af42") { af42 = value; af42.value_namespace = name_space; af42.value_namespace_prefix = name_space_prefix; } if(value_path == "af43") { af43 = value; af43.value_namespace = name_space; af43.value_namespace_prefix = name_space_prefix; } if(value_path == "cs1") { cs1 = value; cs1.value_namespace = name_space; cs1.value_namespace_prefix = name_space_prefix; } if(value_path == "cs2") { cs2 = value; cs2.value_namespace = name_space; cs2.value_namespace_prefix = name_space_prefix; } if(value_path == "cs3") { cs3 = value; cs3.value_namespace = name_space; cs3.value_namespace_prefix = name_space_prefix; } if(value_path == "cs4") { cs4 = value; cs4.value_namespace = name_space; cs4.value_namespace_prefix = name_space_prefix; } if(value_path == "cs5") { cs5 = value; cs5.value_namespace = name_space; cs5.value_namespace_prefix = name_space_prefix; } if(value_path == "cs6") { cs6 = value; cs6.value_namespace = name_space; cs6.value_namespace_prefix = name_space_prefix; } if(value_path == "cs7") { cs7 = value; cs7.value_namespace = name_space; cs7.value_namespace_prefix = name_space_prefix; } if(value_path == "default") { default_ = value; default_.value_namespace = name_space; default_.value_namespace_prefix = name_space_prefix; } if(value_path == "ef") { ef = value; ef.value_namespace = name_space; ef.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Ip_::Any::Dscp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "range") { range.yfilter = yfilter; } if(value_path == "af11") { af11.yfilter = yfilter; } if(value_path == "af12") { af12.yfilter = yfilter; } if(value_path == "af13") { af13.yfilter = yfilter; } if(value_path == "af21") { af21.yfilter = yfilter; } if(value_path == "af22") { af22.yfilter = yfilter; } if(value_path == "af23") { af23.yfilter = yfilter; } if(value_path == "af31") { af31.yfilter = yfilter; } if(value_path == "af32") { af32.yfilter = yfilter; } if(value_path == "af33") { af33.yfilter = yfilter; } if(value_path == "af41") { af41.yfilter = yfilter; } if(value_path == "af42") { af42.yfilter = yfilter; } if(value_path == "af43") { af43.yfilter = yfilter; } if(value_path == "cs1") { cs1.yfilter = yfilter; } if(value_path == "cs2") { cs2.yfilter = yfilter; } if(value_path == "cs3") { cs3.yfilter = yfilter; } if(value_path == "cs4") { cs4.yfilter = yfilter; } if(value_path == "cs5") { cs5.yfilter = yfilter; } if(value_path == "cs6") { cs6.yfilter = yfilter; } if(value_path == "cs7") { cs7.yfilter = yfilter; } if(value_path == "default") { default_.yfilter = yfilter; } if(value_path == "ef") { ef.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Ip_::Any::Dscp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "range" || name == "af11" || name == "af12" || name == "af13" || name == "af21" || name == "af22" || name == "af23" || name == "af31" || name == "af32" || name == "af33" || name == "af41" || name == "af42" || name == "af43" || name == "cs1" || name == "cs2" || name == "cs3" || name == "cs4" || name == "cs5" || name == "cs6" || name == "cs7" || name == "default" || name == "ef") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Ip_() : address(this, {"address0"}) , subnet(std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet>()) { subnet->parent = this; yang_name = "ip"; yang_parent_name = "any"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::Any::Ip_::~Ip_() { } bool Native::Ip::Nbar::Custom::Ip_::Any::Ip_::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_data()) return true; } return (subnet != nullptr && subnet->has_data()); } bool Native::Ip::Nbar::Custom::Ip_::Any::Ip_::has_operation() const { for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_operation()) return true; } return is_set(yfilter) || (subnet != nullptr && subnet->has_operation()); } std::string Native::Ip::Nbar::Custom::Ip_::Any::Ip_::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ip"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::Ip_::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::Ip_::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "address") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address>(); ent_->parent = this; address.append(ent_); return ent_; } if(child_yang_name == "subnet") { if(subnet == nullptr) { subnet = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet>(); } return subnet; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::Ip_::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(subnet != nullptr) { _children["subnet"] = subnet; } return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::Ip_::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Ip_::Any::Ip_::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Ip_::Any::Ip_::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address" || name == "subnet") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address::Address() : address0{YType::str, "address0"}, address1{YType::str, "address1"}, address2{YType::str, "address2"}, address3{YType::str, "address3"}, address4{YType::str, "address4"}, address5{YType::str, "address5"}, address6{YType::str, "address6"}, address7{YType::str, "address7"} { yang_name = "address"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address::~Address() { } bool Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address::has_data() const { if (is_presence_container) return true; return address0.is_set || address1.is_set || address2.is_set || address3.is_set || address4.is_set || address5.is_set || address6.is_set || address7.is_set; } bool Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address::has_operation() const { return is_set(yfilter) || ydk::is_set(address0.yfilter) || ydk::is_set(address1.yfilter) || ydk::is_set(address2.yfilter) || ydk::is_set(address3.yfilter) || ydk::is_set(address4.yfilter) || ydk::is_set(address5.yfilter) || ydk::is_set(address6.yfilter) || ydk::is_set(address7.yfilter); } std::string Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "address"; ADD_KEY_TOKEN(address0, "address0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (address0.is_set || is_set(address0.yfilter)) leaf_name_data.push_back(address0.get_name_leafdata()); if (address1.is_set || is_set(address1.yfilter)) leaf_name_data.push_back(address1.get_name_leafdata()); if (address2.is_set || is_set(address2.yfilter)) leaf_name_data.push_back(address2.get_name_leafdata()); if (address3.is_set || is_set(address3.yfilter)) leaf_name_data.push_back(address3.get_name_leafdata()); if (address4.is_set || is_set(address4.yfilter)) leaf_name_data.push_back(address4.get_name_leafdata()); if (address5.is_set || is_set(address5.yfilter)) leaf_name_data.push_back(address5.get_name_leafdata()); if (address6.is_set || is_set(address6.yfilter)) leaf_name_data.push_back(address6.get_name_leafdata()); if (address7.is_set || is_set(address7.yfilter)) leaf_name_data.push_back(address7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "address0") { address0 = value; address0.value_namespace = name_space; address0.value_namespace_prefix = name_space_prefix; } if(value_path == "address1") { address1 = value; address1.value_namespace = name_space; address1.value_namespace_prefix = name_space_prefix; } if(value_path == "address2") { address2 = value; address2.value_namespace = name_space; address2.value_namespace_prefix = name_space_prefix; } if(value_path == "address3") { address3 = value; address3.value_namespace = name_space; address3.value_namespace_prefix = name_space_prefix; } if(value_path == "address4") { address4 = value; address4.value_namespace = name_space; address4.value_namespace_prefix = name_space_prefix; } if(value_path == "address5") { address5 = value; address5.value_namespace = name_space; address5.value_namespace_prefix = name_space_prefix; } if(value_path == "address6") { address6 = value; address6.value_namespace = name_space; address6.value_namespace_prefix = name_space_prefix; } if(value_path == "address7") { address7 = value; address7.value_namespace = name_space; address7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "address0") { address0.yfilter = yfilter; } if(value_path == "address1") { address1.yfilter = yfilter; } if(value_path == "address2") { address2.yfilter = yfilter; } if(value_path == "address3") { address3.yfilter = yfilter; } if(value_path == "address4") { address4.yfilter = yfilter; } if(value_path == "address5") { address5.yfilter = yfilter; } if(value_path == "address6") { address6.yfilter = yfilter; } if(value_path == "address7") { address7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Address::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address0" || name == "address1" || name == "address2" || name == "address3" || name == "address4" || name == "address5" || name == "address6" || name == "address7") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet::Subnet() : subnet{YType::str, "subnet"}, mask{YType::uint8, "mask"} { yang_name = "subnet"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet::~Subnet() { } bool Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet::has_data() const { if (is_presence_container) return true; return subnet.is_set || mask.is_set; } bool Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet::has_operation() const { return is_set(yfilter) || ydk::is_set(subnet.yfilter) || ydk::is_set(mask.yfilter); } std::string Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "subnet"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (subnet.is_set || is_set(subnet.yfilter)) leaf_name_data.push_back(subnet.get_name_leafdata()); if (mask.is_set || is_set(mask.yfilter)) leaf_name_data.push_back(mask.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "subnet") { subnet = value; subnet.value_namespace = name_space; subnet.value_namespace_prefix = name_space_prefix; } if(value_path == "mask") { mask = value; mask.value_namespace = name_space; mask.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "subnet") { subnet.yfilter = yfilter; } if(value_path == "mask") { mask.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Ip_::Any::Ip_::Subnet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "subnet" || name == "mask") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Ipv6() : address(this, {"address0"}) , subnet(std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet>()) { subnet->parent = this; yang_name = "ipv6"; yang_parent_name = "any"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::~Ipv6() { } bool Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_data()) return true; } return (subnet != nullptr && subnet->has_data()); } bool Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::has_operation() const { for (std::size_t index=0; index<address.len(); index++) { if(address[index]->has_operation()) return true; } return is_set(yfilter) || (subnet != nullptr && subnet->has_operation()); } std::string Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "address") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address>(); ent_->parent = this; address.append(ent_); return ent_; } if(child_yang_name == "subnet") { if(subnet == nullptr) { subnet = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet>(); } return subnet; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(subnet != nullptr) { _children["subnet"] = subnet; } return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address" || name == "subnet") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address::Address() : address0{YType::str, "address0"}, address1{YType::str, "address1"}, address2{YType::str, "address2"}, address3{YType::str, "address3"}, address4{YType::str, "address4"}, address5{YType::str, "address5"}, address6{YType::str, "address6"}, address7{YType::str, "address7"} { yang_name = "address"; yang_parent_name = "ipv6"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address::~Address() { } bool Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address::has_data() const { if (is_presence_container) return true; return address0.is_set || address1.is_set || address2.is_set || address3.is_set || address4.is_set || address5.is_set || address6.is_set || address7.is_set; } bool Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address::has_operation() const { return is_set(yfilter) || ydk::is_set(address0.yfilter) || ydk::is_set(address1.yfilter) || ydk::is_set(address2.yfilter) || ydk::is_set(address3.yfilter) || ydk::is_set(address4.yfilter) || ydk::is_set(address5.yfilter) || ydk::is_set(address6.yfilter) || ydk::is_set(address7.yfilter); } std::string Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "address"; ADD_KEY_TOKEN(address0, "address0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (address0.is_set || is_set(address0.yfilter)) leaf_name_data.push_back(address0.get_name_leafdata()); if (address1.is_set || is_set(address1.yfilter)) leaf_name_data.push_back(address1.get_name_leafdata()); if (address2.is_set || is_set(address2.yfilter)) leaf_name_data.push_back(address2.get_name_leafdata()); if (address3.is_set || is_set(address3.yfilter)) leaf_name_data.push_back(address3.get_name_leafdata()); if (address4.is_set || is_set(address4.yfilter)) leaf_name_data.push_back(address4.get_name_leafdata()); if (address5.is_set || is_set(address5.yfilter)) leaf_name_data.push_back(address5.get_name_leafdata()); if (address6.is_set || is_set(address6.yfilter)) leaf_name_data.push_back(address6.get_name_leafdata()); if (address7.is_set || is_set(address7.yfilter)) leaf_name_data.push_back(address7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "address0") { address0 = value; address0.value_namespace = name_space; address0.value_namespace_prefix = name_space_prefix; } if(value_path == "address1") { address1 = value; address1.value_namespace = name_space; address1.value_namespace_prefix = name_space_prefix; } if(value_path == "address2") { address2 = value; address2.value_namespace = name_space; address2.value_namespace_prefix = name_space_prefix; } if(value_path == "address3") { address3 = value; address3.value_namespace = name_space; address3.value_namespace_prefix = name_space_prefix; } if(value_path == "address4") { address4 = value; address4.value_namespace = name_space; address4.value_namespace_prefix = name_space_prefix; } if(value_path == "address5") { address5 = value; address5.value_namespace = name_space; address5.value_namespace_prefix = name_space_prefix; } if(value_path == "address6") { address6 = value; address6.value_namespace = name_space; address6.value_namespace_prefix = name_space_prefix; } if(value_path == "address7") { address7 = value; address7.value_namespace = name_space; address7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "address0") { address0.yfilter = yfilter; } if(value_path == "address1") { address1.yfilter = yfilter; } if(value_path == "address2") { address2.yfilter = yfilter; } if(value_path == "address3") { address3.yfilter = yfilter; } if(value_path == "address4") { address4.yfilter = yfilter; } if(value_path == "address5") { address5.yfilter = yfilter; } if(value_path == "address6") { address6.yfilter = yfilter; } if(value_path == "address7") { address7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Address::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address0" || name == "address1" || name == "address2" || name == "address3" || name == "address4" || name == "address5" || name == "address6" || name == "address7") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet::Subnet() : subnet{YType::str, "subnet"}, mask{YType::uint8, "mask"} { yang_name = "subnet"; yang_parent_name = "ipv6"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet::~Subnet() { } bool Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet::has_data() const { if (is_presence_container) return true; return subnet.is_set || mask.is_set; } bool Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet::has_operation() const { return is_set(yfilter) || ydk::is_set(subnet.yfilter) || ydk::is_set(mask.yfilter); } std::string Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "subnet"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (subnet.is_set || is_set(subnet.yfilter)) leaf_name_data.push_back(subnet.get_name_leafdata()); if (mask.is_set || is_set(mask.yfilter)) leaf_name_data.push_back(mask.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "subnet") { subnet = value; subnet.value_namespace = name_space; subnet.value_namespace_prefix = name_space_prefix; } if(value_path == "mask") { mask = value; mask.value_namespace = name_space; mask.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "subnet") { subnet.yfilter = yfilter; } if(value_path == "mask") { mask.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Ip_::Any::Ipv6::Subnet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "subnet" || name == "mask") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Direction::Direction() : any{YType::empty, "any"}, destination{YType::empty, "destination"}, source{YType::empty, "source"} { yang_name = "direction"; yang_parent_name = "any"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::Any::Direction::~Direction() { } bool Native::Ip::Nbar::Custom::Ip_::Any::Direction::has_data() const { if (is_presence_container) return true; return any.is_set || destination.is_set || source.is_set; } bool Native::Ip::Nbar::Custom::Ip_::Any::Direction::has_operation() const { return is_set(yfilter) || ydk::is_set(any.yfilter) || ydk::is_set(destination.yfilter) || ydk::is_set(source.yfilter); } std::string Native::Ip::Nbar::Custom::Ip_::Any::Direction::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "direction"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::Direction::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (any.is_set || is_set(any.yfilter)) leaf_name_data.push_back(any.get_name_leafdata()); if (destination.is_set || is_set(destination.yfilter)) leaf_name_data.push_back(destination.get_name_leafdata()); if (source.is_set || is_set(source.yfilter)) leaf_name_data.push_back(source.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::Direction::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::Direction::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::Direction::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "any") { any = value; any.value_namespace = name_space; any.value_namespace_prefix = name_space_prefix; } if(value_path == "destination") { destination = value; destination.value_namespace = name_space; destination.value_namespace_prefix = name_space_prefix; } if(value_path == "source") { source = value; source.value_namespace = name_space; source.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Ip_::Any::Direction::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "any") { any.yfilter = yfilter; } if(value_path == "destination") { destination.yfilter = yfilter; } if(value_path == "source") { source.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Ip_::Any::Direction::has_leaf_or_child_of_name(const std::string & name) const { if(name == "any" || name == "destination" || name == "source") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Port::Port() : port_numbers(this, {"port_number0"}) , range(std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Port::Range>()) { range->parent = this; yang_name = "port"; yang_parent_name = "any"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::Any::Port::~Port() { } bool Native::Ip::Nbar::Custom::Ip_::Any::Port::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<port_numbers.len(); index++) { if(port_numbers[index]->has_data()) return true; } return (range != nullptr && range->has_data()); } bool Native::Ip::Nbar::Custom::Ip_::Any::Port::has_operation() const { for (std::size_t index=0; index<port_numbers.len(); index++) { if(port_numbers[index]->has_operation()) return true; } return is_set(yfilter) || (range != nullptr && range->has_operation()); } std::string Native::Ip::Nbar::Custom::Ip_::Any::Port::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "port"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::Port::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::Port::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "port-numbers") { auto ent_ = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers>(); ent_->parent = this; port_numbers.append(ent_); return ent_; } if(child_yang_name == "range") { if(range == nullptr) { range = std::make_shared<Native::Ip::Nbar::Custom::Ip_::Any::Port::Range>(); } return range; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::Port::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : port_numbers.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(range != nullptr) { _children["range"] = range; } return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::Port::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::Custom::Ip_::Any::Port::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::Custom::Ip_::Any::Port::has_leaf_or_child_of_name(const std::string & name) const { if(name == "port-numbers" || name == "range") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers::PortNumbers() : port_number0{YType::uint16, "port-number0"}, port_number1{YType::uint16, "port-number1"}, port_number2{YType::uint16, "port-number2"}, port_number3{YType::uint16, "port-number3"}, port_number4{YType::uint16, "port-number4"}, port_number5{YType::uint16, "port-number5"}, port_number6{YType::uint16, "port-number6"}, port_number7{YType::uint16, "port-number7"} { yang_name = "port-numbers"; yang_parent_name = "port"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers::~PortNumbers() { } bool Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers::has_data() const { if (is_presence_container) return true; return port_number0.is_set || port_number1.is_set || port_number2.is_set || port_number3.is_set || port_number4.is_set || port_number5.is_set || port_number6.is_set || port_number7.is_set; } bool Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers::has_operation() const { return is_set(yfilter) || ydk::is_set(port_number0.yfilter) || ydk::is_set(port_number1.yfilter) || ydk::is_set(port_number2.yfilter) || ydk::is_set(port_number3.yfilter) || ydk::is_set(port_number4.yfilter) || ydk::is_set(port_number5.yfilter) || ydk::is_set(port_number6.yfilter) || ydk::is_set(port_number7.yfilter); } std::string Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "port-numbers"; ADD_KEY_TOKEN(port_number0, "port-number0"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (port_number0.is_set || is_set(port_number0.yfilter)) leaf_name_data.push_back(port_number0.get_name_leafdata()); if (port_number1.is_set || is_set(port_number1.yfilter)) leaf_name_data.push_back(port_number1.get_name_leafdata()); if (port_number2.is_set || is_set(port_number2.yfilter)) leaf_name_data.push_back(port_number2.get_name_leafdata()); if (port_number3.is_set || is_set(port_number3.yfilter)) leaf_name_data.push_back(port_number3.get_name_leafdata()); if (port_number4.is_set || is_set(port_number4.yfilter)) leaf_name_data.push_back(port_number4.get_name_leafdata()); if (port_number5.is_set || is_set(port_number5.yfilter)) leaf_name_data.push_back(port_number5.get_name_leafdata()); if (port_number6.is_set || is_set(port_number6.yfilter)) leaf_name_data.push_back(port_number6.get_name_leafdata()); if (port_number7.is_set || is_set(port_number7.yfilter)) leaf_name_data.push_back(port_number7.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "port-number0") { port_number0 = value; port_number0.value_namespace = name_space; port_number0.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number1") { port_number1 = value; port_number1.value_namespace = name_space; port_number1.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number2") { port_number2 = value; port_number2.value_namespace = name_space; port_number2.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number3") { port_number3 = value; port_number3.value_namespace = name_space; port_number3.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number4") { port_number4 = value; port_number4.value_namespace = name_space; port_number4.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number5") { port_number5 = value; port_number5.value_namespace = name_space; port_number5.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number6") { port_number6 = value; port_number6.value_namespace = name_space; port_number6.value_namespace_prefix = name_space_prefix; } if(value_path == "port-number7") { port_number7 = value; port_number7.value_namespace = name_space; port_number7.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "port-number0") { port_number0.yfilter = yfilter; } if(value_path == "port-number1") { port_number1.yfilter = yfilter; } if(value_path == "port-number2") { port_number2.yfilter = yfilter; } if(value_path == "port-number3") { port_number3.yfilter = yfilter; } if(value_path == "port-number4") { port_number4.yfilter = yfilter; } if(value_path == "port-number5") { port_number5.yfilter = yfilter; } if(value_path == "port-number6") { port_number6.yfilter = yfilter; } if(value_path == "port-number7") { port_number7.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Ip_::Any::Port::PortNumbers::has_leaf_or_child_of_name(const std::string & name) const { if(name == "port-number0" || name == "port-number1" || name == "port-number2" || name == "port-number3" || name == "port-number4" || name == "port-number5" || name == "port-number6" || name == "port-number7") return true; return false; } Native::Ip::Nbar::Custom::Ip_::Any::Port::Range::Range() : start_range{YType::uint16, "start-range"}, end_range{YType::uint16, "end-range"} { yang_name = "range"; yang_parent_name = "port"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Nbar::Custom::Ip_::Any::Port::Range::~Range() { } bool Native::Ip::Nbar::Custom::Ip_::Any::Port::Range::has_data() const { if (is_presence_container) return true; return start_range.is_set || end_range.is_set; } bool Native::Ip::Nbar::Custom::Ip_::Any::Port::Range::has_operation() const { return is_set(yfilter) || ydk::is_set(start_range.yfilter) || ydk::is_set(end_range.yfilter); } std::string Native::Ip::Nbar::Custom::Ip_::Any::Port::Range::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "range"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::Custom::Ip_::Any::Port::Range::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_range.is_set || is_set(start_range.yfilter)) leaf_name_data.push_back(start_range.get_name_leafdata()); if (end_range.is_set || is_set(end_range.yfilter)) leaf_name_data.push_back(end_range.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::Custom::Ip_::Any::Port::Range::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::Custom::Ip_::Any::Port::Range::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::Custom::Ip_::Any::Port::Range::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-range") { start_range = value; start_range.value_namespace = name_space; start_range.value_namespace_prefix = name_space_prefix; } if(value_path == "end-range") { end_range = value; end_range.value_namespace = name_space; end_range.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::Custom::Ip_::Any::Port::Range::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-range") { start_range.yfilter = yfilter; } if(value_path == "end-range") { end_range.yfilter = yfilter; } } bool Native::Ip::Nbar::Custom::Ip_::Any::Port::Range::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-range" || name == "end-range") return true; return false; } Native::Ip::Nbar::ProtocolPack::ProtocolPack() : filepath(this, {"filepath"}) { yang_name = "protocol-pack"; yang_parent_name = "nbar"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::ProtocolPack::~ProtocolPack() { } bool Native::Ip::Nbar::ProtocolPack::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<filepath.len(); index++) { if(filepath[index]->has_data()) return true; } return false; } bool Native::Ip::Nbar::ProtocolPack::has_operation() const { for (std::size_t index=0; index<filepath.len(); index++) { if(filepath[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Nbar::ProtocolPack::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::ProtocolPack::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "protocol-pack"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::ProtocolPack::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::ProtocolPack::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "filepath") { auto ent_ = std::make_shared<Native::Ip::Nbar::ProtocolPack::Filepath>(); ent_->parent = this; filepath.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::ProtocolPack::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : filepath.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Nbar::ProtocolPack::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Nbar::ProtocolPack::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Nbar::ProtocolPack::has_leaf_or_child_of_name(const std::string & name) const { if(name == "filepath") return true; return false; } Native::Ip::Nbar::ProtocolPack::Filepath::Filepath() : filepath{YType::str, "filepath"}, force{YType::empty, "force"} { yang_name = "filepath"; yang_parent_name = "protocol-pack"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Nbar::ProtocolPack::Filepath::~Filepath() { } bool Native::Ip::Nbar::ProtocolPack::Filepath::has_data() const { if (is_presence_container) return true; return filepath.is_set || force.is_set; } bool Native::Ip::Nbar::ProtocolPack::Filepath::has_operation() const { return is_set(yfilter) || ydk::is_set(filepath.yfilter) || ydk::is_set(force.yfilter); } std::string Native::Ip::Nbar::ProtocolPack::Filepath::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-nbar:nbar/protocol-pack/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Nbar::ProtocolPack::Filepath::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "filepath"; ADD_KEY_TOKEN(filepath, "filepath"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Nbar::ProtocolPack::Filepath::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (filepath.is_set || is_set(filepath.yfilter)) leaf_name_data.push_back(filepath.get_name_leafdata()); if (force.is_set || is_set(force.yfilter)) leaf_name_data.push_back(force.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Nbar::ProtocolPack::Filepath::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Nbar::ProtocolPack::Filepath::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Nbar::ProtocolPack::Filepath::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "filepath") { filepath = value; filepath.value_namespace = name_space; filepath.value_namespace_prefix = name_space_prefix; } if(value_path == "force") { force = value; force.value_namespace = name_space; force.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Nbar::ProtocolPack::Filepath::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "filepath") { filepath.yfilter = yfilter; } if(value_path == "force") { force.yfilter = yfilter; } } bool Native::Ip::Nbar::ProtocolPack::Filepath::has_leaf_or_child_of_name(const std::string & name) const { if(name == "filepath" || name == "force") return true; return false; } Native::Ip::Sla::Sla() : entry(this, {"number"}) , enable(std::make_shared<Native::Ip::Sla::Enable>()) , responder(nullptr) // presence node , logging(std::make_shared<Native::Ip::Sla::Logging>()) , group(std::make_shared<Native::Ip::Sla::Group>()) , schedule(this, {"entry_number"}) , reaction_configuration(this, {"entry_number"}) , server(std::make_shared<Native::Ip::Sla::Server>()) { enable->parent = this; logging->parent = this; group->parent = this; server->parent = this; yang_name = "sla"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::~Sla() { } bool Native::Ip::Sla::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<entry.len(); index++) { if(entry[index]->has_data()) return true; } for (std::size_t index=0; index<schedule.len(); index++) { if(schedule[index]->has_data()) return true; } for (std::size_t index=0; index<reaction_configuration.len(); index++) { if(reaction_configuration[index]->has_data()) return true; } return (enable != nullptr && enable->has_data()) || (responder != nullptr && responder->has_data()) || (logging != nullptr && logging->has_data()) || (group != nullptr && group->has_data()) || (server != nullptr && server->has_data()); } bool Native::Ip::Sla::has_operation() const { for (std::size_t index=0; index<entry.len(); index++) { if(entry[index]->has_operation()) return true; } for (std::size_t index=0; index<schedule.len(); index++) { if(schedule[index]->has_operation()) return true; } for (std::size_t index=0; index<reaction_configuration.len(); index++) { if(reaction_configuration[index]->has_operation()) return true; } return is_set(yfilter) || (enable != nullptr && enable->has_operation()) || (responder != nullptr && responder->has_operation()) || (logging != nullptr && logging->has_operation()) || (group != nullptr && group->has_operation()) || (server != nullptr && server->has_operation()); } std::string Native::Ip::Sla::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-sla:sla"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "entry") { auto ent_ = std::make_shared<Native::Ip::Sla::Entry>(); ent_->parent = this; entry.append(ent_); return ent_; } if(child_yang_name == "enable") { if(enable == nullptr) { enable = std::make_shared<Native::Ip::Sla::Enable>(); } return enable; } if(child_yang_name == "responder") { if(responder == nullptr) { responder = std::make_shared<Native::Ip::Sla::Responder>(); } return responder; } if(child_yang_name == "logging") { if(logging == nullptr) { logging = std::make_shared<Native::Ip::Sla::Logging>(); } return logging; } if(child_yang_name == "group") { if(group == nullptr) { group = std::make_shared<Native::Ip::Sla::Group>(); } return group; } if(child_yang_name == "schedule") { auto ent_ = std::make_shared<Native::Ip::Sla::Schedule>(); ent_->parent = this; schedule.append(ent_); return ent_; } if(child_yang_name == "reaction-configuration") { auto ent_ = std::make_shared<Native::Ip::Sla::ReactionConfiguration>(); ent_->parent = this; reaction_configuration.append(ent_); return ent_; } if(child_yang_name == "server") { if(server == nullptr) { server = std::make_shared<Native::Ip::Sla::Server>(); } return server; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : entry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(enable != nullptr) { _children["enable"] = enable; } if(responder != nullptr) { _children["responder"] = responder; } if(logging != nullptr) { _children["logging"] = logging; } if(group != nullptr) { _children["group"] = group; } count_ = 0; for (auto ent_ : schedule.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } count_ = 0; for (auto ent_ : reaction_configuration.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(server != nullptr) { _children["server"] = server; } return _children; } void Native::Ip::Sla::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Sla::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Sla::has_leaf_or_child_of_name(const std::string & name) const { if(name == "entry" || name == "enable" || name == "responder" || name == "logging" || name == "group" || name == "schedule" || name == "reaction-configuration" || name == "server") return true; return false; } Native::Ip::Sla::Entry::Entry() : number{YType::uint32, "number"} , icmp_echo(std::make_shared<Native::Ip::Sla::Entry::IcmpEcho>()) , path_echo(std::make_shared<Native::Ip::Sla::Entry::PathEcho>()) , path_jitter(std::make_shared<Native::Ip::Sla::Entry::PathJitter>()) , udp_echo(std::make_shared<Native::Ip::Sla::Entry::UdpEcho>()) , udp_jitter(std::make_shared<Native::Ip::Sla::Entry::UdpJitter>()) , http(std::make_shared<Native::Ip::Sla::Entry::Http>()) , dhcp(std::make_shared<Native::Ip::Sla::Entry::Dhcp>()) , ethernet(std::make_shared<Native::Ip::Sla::Entry::Ethernet>()) { icmp_echo->parent = this; path_echo->parent = this; path_jitter->parent = this; udp_echo->parent = this; udp_jitter->parent = this; http->parent = this; dhcp->parent = this; ethernet->parent = this; yang_name = "entry"; yang_parent_name = "sla"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::Entry::~Entry() { } bool Native::Ip::Sla::Entry::has_data() const { if (is_presence_container) return true; return number.is_set || (icmp_echo != nullptr && icmp_echo->has_data()) || (path_echo != nullptr && path_echo->has_data()) || (path_jitter != nullptr && path_jitter->has_data()) || (udp_echo != nullptr && udp_echo->has_data()) || (udp_jitter != nullptr && udp_jitter->has_data()) || (http != nullptr && http->has_data()) || (dhcp != nullptr && dhcp->has_data()) || (ethernet != nullptr && ethernet->has_data()); } bool Native::Ip::Sla::Entry::has_operation() const { return is_set(yfilter) || ydk::is_set(number.yfilter) || (icmp_echo != nullptr && icmp_echo->has_operation()) || (path_echo != nullptr && path_echo->has_operation()) || (path_jitter != nullptr && path_jitter->has_operation()) || (udp_echo != nullptr && udp_echo->has_operation()) || (udp_jitter != nullptr && udp_jitter->has_operation()) || (http != nullptr && http->has_operation()) || (dhcp != nullptr && dhcp->has_operation()) || (ethernet != nullptr && ethernet->has_operation()); } std::string Native::Ip::Sla::Entry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Entry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "entry"; ADD_KEY_TOKEN(number, "number"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (number.is_set || is_set(number.yfilter)) leaf_name_data.push_back(number.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "icmp-echo") { if(icmp_echo == nullptr) { icmp_echo = std::make_shared<Native::Ip::Sla::Entry::IcmpEcho>(); } return icmp_echo; } if(child_yang_name == "path-echo") { if(path_echo == nullptr) { path_echo = std::make_shared<Native::Ip::Sla::Entry::PathEcho>(); } return path_echo; } if(child_yang_name == "path-jitter") { if(path_jitter == nullptr) { path_jitter = std::make_shared<Native::Ip::Sla::Entry::PathJitter>(); } return path_jitter; } if(child_yang_name == "udp-echo") { if(udp_echo == nullptr) { udp_echo = std::make_shared<Native::Ip::Sla::Entry::UdpEcho>(); } return udp_echo; } if(child_yang_name == "udp-jitter") { if(udp_jitter == nullptr) { udp_jitter = std::make_shared<Native::Ip::Sla::Entry::UdpJitter>(); } return udp_jitter; } if(child_yang_name == "http") { if(http == nullptr) { http = std::make_shared<Native::Ip::Sla::Entry::Http>(); } return http; } if(child_yang_name == "dhcp") { if(dhcp == nullptr) { dhcp = std::make_shared<Native::Ip::Sla::Entry::Dhcp>(); } return dhcp; } if(child_yang_name == "ethernet") { if(ethernet == nullptr) { ethernet = std::make_shared<Native::Ip::Sla::Entry::Ethernet>(); } return ethernet; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(icmp_echo != nullptr) { _children["icmp-echo"] = icmp_echo; } if(path_echo != nullptr) { _children["path-echo"] = path_echo; } if(path_jitter != nullptr) { _children["path-jitter"] = path_jitter; } if(udp_echo != nullptr) { _children["udp-echo"] = udp_echo; } if(udp_jitter != nullptr) { _children["udp-jitter"] = udp_jitter; } if(http != nullptr) { _children["http"] = http; } if(dhcp != nullptr) { _children["dhcp"] = dhcp; } if(ethernet != nullptr) { _children["ethernet"] = ethernet; } return _children; } void Native::Ip::Sla::Entry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "number") { number = value; number.value_namespace = name_space; number.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "number") { number.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "icmp-echo" || name == "path-echo" || name == "path-jitter" || name == "udp-echo" || name == "udp-jitter" || name == "http" || name == "dhcp" || name == "ethernet" || name == "number") return true; return false; } Native::Ip::Sla::Entry::IcmpEcho::IcmpEcho() : destination{YType::str, "destination"}, source_interface{YType::str, "source-interface"}, source_ip{YType::str, "source-ip"}, data_pattern{YType::str, "data-pattern"}, frequency{YType::uint32, "frequency"}, owner{YType::str, "owner"}, request_data_size{YType::uint32, "request-data-size"}, tag{YType::str, "tag"}, threshold{YType::uint32, "threshold"}, timeout{YType::uint64, "timeout"}, tos{YType::uint8, "tos"}, verify_data{YType::empty, "verify-data"}, vrf{YType::str, "vrf"} , history(std::make_shared<Native::Ip::Sla::Entry::IcmpEcho::History>()) { history->parent = this; yang_name = "icmp-echo"; yang_parent_name = "entry"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::IcmpEcho::~IcmpEcho() { } bool Native::Ip::Sla::Entry::IcmpEcho::has_data() const { if (is_presence_container) return true; return destination.is_set || source_interface.is_set || source_ip.is_set || data_pattern.is_set || frequency.is_set || owner.is_set || request_data_size.is_set || tag.is_set || threshold.is_set || timeout.is_set || tos.is_set || verify_data.is_set || vrf.is_set || (history != nullptr && history->has_data()); } bool Native::Ip::Sla::Entry::IcmpEcho::has_operation() const { return is_set(yfilter) || ydk::is_set(destination.yfilter) || ydk::is_set(source_interface.yfilter) || ydk::is_set(source_ip.yfilter) || ydk::is_set(data_pattern.yfilter) || ydk::is_set(frequency.yfilter) || ydk::is_set(owner.yfilter) || ydk::is_set(request_data_size.yfilter) || ydk::is_set(tag.yfilter) || ydk::is_set(threshold.yfilter) || ydk::is_set(timeout.yfilter) || ydk::is_set(tos.yfilter) || ydk::is_set(verify_data.yfilter) || ydk::is_set(vrf.yfilter) || (history != nullptr && history->has_operation()); } std::string Native::Ip::Sla::Entry::IcmpEcho::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "icmp-echo"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::IcmpEcho::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (destination.is_set || is_set(destination.yfilter)) leaf_name_data.push_back(destination.get_name_leafdata()); if (source_interface.is_set || is_set(source_interface.yfilter)) leaf_name_data.push_back(source_interface.get_name_leafdata()); if (source_ip.is_set || is_set(source_ip.yfilter)) leaf_name_data.push_back(source_ip.get_name_leafdata()); if (data_pattern.is_set || is_set(data_pattern.yfilter)) leaf_name_data.push_back(data_pattern.get_name_leafdata()); if (frequency.is_set || is_set(frequency.yfilter)) leaf_name_data.push_back(frequency.get_name_leafdata()); if (owner.is_set || is_set(owner.yfilter)) leaf_name_data.push_back(owner.get_name_leafdata()); if (request_data_size.is_set || is_set(request_data_size.yfilter)) leaf_name_data.push_back(request_data_size.get_name_leafdata()); if (tag.is_set || is_set(tag.yfilter)) leaf_name_data.push_back(tag.get_name_leafdata()); if (threshold.is_set || is_set(threshold.yfilter)) leaf_name_data.push_back(threshold.get_name_leafdata()); if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata()); if (tos.is_set || is_set(tos.yfilter)) leaf_name_data.push_back(tos.get_name_leafdata()); if (verify_data.is_set || is_set(verify_data.yfilter)) leaf_name_data.push_back(verify_data.get_name_leafdata()); if (vrf.is_set || is_set(vrf.yfilter)) leaf_name_data.push_back(vrf.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::IcmpEcho::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "history") { if(history == nullptr) { history = std::make_shared<Native::Ip::Sla::Entry::IcmpEcho::History>(); } return history; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::IcmpEcho::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(history != nullptr) { _children["history"] = history; } return _children; } void Native::Ip::Sla::Entry::IcmpEcho::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "destination") { destination = value; destination.value_namespace = name_space; destination.value_namespace_prefix = name_space_prefix; } if(value_path == "source-interface") { source_interface = value; source_interface.value_namespace = name_space; source_interface.value_namespace_prefix = name_space_prefix; } if(value_path == "source-ip") { source_ip = value; source_ip.value_namespace = name_space; source_ip.value_namespace_prefix = name_space_prefix; } if(value_path == "data-pattern") { data_pattern = value; data_pattern.value_namespace = name_space; data_pattern.value_namespace_prefix = name_space_prefix; } if(value_path == "frequency") { frequency = value; frequency.value_namespace = name_space; frequency.value_namespace_prefix = name_space_prefix; } if(value_path == "owner") { owner = value; owner.value_namespace = name_space; owner.value_namespace_prefix = name_space_prefix; } if(value_path == "request-data-size") { request_data_size = value; request_data_size.value_namespace = name_space; request_data_size.value_namespace_prefix = name_space_prefix; } if(value_path == "tag") { tag = value; tag.value_namespace = name_space; tag.value_namespace_prefix = name_space_prefix; } if(value_path == "threshold") { threshold = value; threshold.value_namespace = name_space; threshold.value_namespace_prefix = name_space_prefix; } if(value_path == "timeout") { timeout = value; timeout.value_namespace = name_space; timeout.value_namespace_prefix = name_space_prefix; } if(value_path == "tos") { tos = value; tos.value_namespace = name_space; tos.value_namespace_prefix = name_space_prefix; } if(value_path == "verify-data") { verify_data = value; verify_data.value_namespace = name_space; verify_data.value_namespace_prefix = name_space_prefix; } if(value_path == "vrf") { vrf = value; vrf.value_namespace = name_space; vrf.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::IcmpEcho::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "destination") { destination.yfilter = yfilter; } if(value_path == "source-interface") { source_interface.yfilter = yfilter; } if(value_path == "source-ip") { source_ip.yfilter = yfilter; } if(value_path == "data-pattern") { data_pattern.yfilter = yfilter; } if(value_path == "frequency") { frequency.yfilter = yfilter; } if(value_path == "owner") { owner.yfilter = yfilter; } if(value_path == "request-data-size") { request_data_size.yfilter = yfilter; } if(value_path == "tag") { tag.yfilter = yfilter; } if(value_path == "threshold") { threshold.yfilter = yfilter; } if(value_path == "timeout") { timeout.yfilter = yfilter; } if(value_path == "tos") { tos.yfilter = yfilter; } if(value_path == "verify-data") { verify_data.yfilter = yfilter; } if(value_path == "vrf") { vrf.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::IcmpEcho::has_leaf_or_child_of_name(const std::string & name) const { if(name == "history" || name == "destination" || name == "source-interface" || name == "source-ip" || name == "data-pattern" || name == "frequency" || name == "owner" || name == "request-data-size" || name == "tag" || name == "threshold" || name == "timeout" || name == "tos" || name == "verify-data" || name == "vrf") return true; return false; } Native::Ip::Sla::Entry::IcmpEcho::History::History() : buckets_kept{YType::uint8, "buckets-kept"}, distributions_of_statistics_kept{YType::uint8, "distributions-of-statistics-kept"}, filter{YType::enumeration, "filter"}, hours_of_statistics_kept{YType::uint8, "hours-of-statistics-kept"}, lives_kept{YType::uint8, "lives-kept"}, statistics_distribution_interval{YType::uint8, "statistics-distribution-interval"} , enhanced(std::make_shared<Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced>()) { enhanced->parent = this; yang_name = "history"; yang_parent_name = "icmp-echo"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::IcmpEcho::History::~History() { } bool Native::Ip::Sla::Entry::IcmpEcho::History::has_data() const { if (is_presence_container) return true; return buckets_kept.is_set || distributions_of_statistics_kept.is_set || filter.is_set || hours_of_statistics_kept.is_set || lives_kept.is_set || statistics_distribution_interval.is_set || (enhanced != nullptr && enhanced->has_data()); } bool Native::Ip::Sla::Entry::IcmpEcho::History::has_operation() const { return is_set(yfilter) || ydk::is_set(buckets_kept.yfilter) || ydk::is_set(distributions_of_statistics_kept.yfilter) || ydk::is_set(filter.yfilter) || ydk::is_set(hours_of_statistics_kept.yfilter) || ydk::is_set(lives_kept.yfilter) || ydk::is_set(statistics_distribution_interval.yfilter) || (enhanced != nullptr && enhanced->has_operation()); } std::string Native::Ip::Sla::Entry::IcmpEcho::History::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "history"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::IcmpEcho::History::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (buckets_kept.is_set || is_set(buckets_kept.yfilter)) leaf_name_data.push_back(buckets_kept.get_name_leafdata()); if (distributions_of_statistics_kept.is_set || is_set(distributions_of_statistics_kept.yfilter)) leaf_name_data.push_back(distributions_of_statistics_kept.get_name_leafdata()); if (filter.is_set || is_set(filter.yfilter)) leaf_name_data.push_back(filter.get_name_leafdata()); if (hours_of_statistics_kept.is_set || is_set(hours_of_statistics_kept.yfilter)) leaf_name_data.push_back(hours_of_statistics_kept.get_name_leafdata()); if (lives_kept.is_set || is_set(lives_kept.yfilter)) leaf_name_data.push_back(lives_kept.get_name_leafdata()); if (statistics_distribution_interval.is_set || is_set(statistics_distribution_interval.yfilter)) leaf_name_data.push_back(statistics_distribution_interval.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::IcmpEcho::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "enhanced") { if(enhanced == nullptr) { enhanced = std::make_shared<Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced>(); } return enhanced; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::IcmpEcho::History::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(enhanced != nullptr) { _children["enhanced"] = enhanced; } return _children; } void Native::Ip::Sla::Entry::IcmpEcho::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "buckets-kept") { buckets_kept = value; buckets_kept.value_namespace = name_space; buckets_kept.value_namespace_prefix = name_space_prefix; } if(value_path == "distributions-of-statistics-kept") { distributions_of_statistics_kept = value; distributions_of_statistics_kept.value_namespace = name_space; distributions_of_statistics_kept.value_namespace_prefix = name_space_prefix; } if(value_path == "filter") { filter = value; filter.value_namespace = name_space; filter.value_namespace_prefix = name_space_prefix; } if(value_path == "hours-of-statistics-kept") { hours_of_statistics_kept = value; hours_of_statistics_kept.value_namespace = name_space; hours_of_statistics_kept.value_namespace_prefix = name_space_prefix; } if(value_path == "lives-kept") { lives_kept = value; lives_kept.value_namespace = name_space; lives_kept.value_namespace_prefix = name_space_prefix; } if(value_path == "statistics-distribution-interval") { statistics_distribution_interval = value; statistics_distribution_interval.value_namespace = name_space; statistics_distribution_interval.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::IcmpEcho::History::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "buckets-kept") { buckets_kept.yfilter = yfilter; } if(value_path == "distributions-of-statistics-kept") { distributions_of_statistics_kept.yfilter = yfilter; } if(value_path == "filter") { filter.yfilter = yfilter; } if(value_path == "hours-of-statistics-kept") { hours_of_statistics_kept.yfilter = yfilter; } if(value_path == "lives-kept") { lives_kept.yfilter = yfilter; } if(value_path == "statistics-distribution-interval") { statistics_distribution_interval.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::IcmpEcho::History::has_leaf_or_child_of_name(const std::string & name) const { if(name == "enhanced" || name == "buckets-kept" || name == "distributions-of-statistics-kept" || name == "filter" || name == "hours-of-statistics-kept" || name == "lives-kept" || name == "statistics-distribution-interval") return true; return false; } Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced::Enhanced() : interval{YType::uint32, "interval"}, buckets{YType::uint8, "buckets"} { yang_name = "enhanced"; yang_parent_name = "history"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced::~Enhanced() { } bool Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced::has_data() const { if (is_presence_container) return true; return interval.is_set || buckets.is_set; } bool Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced::has_operation() const { return is_set(yfilter) || ydk::is_set(interval.yfilter) || ydk::is_set(buckets.yfilter); } std::string Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "enhanced"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata()); if (buckets.is_set || is_set(buckets.yfilter)) leaf_name_data.push_back(buckets.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "interval") { interval = value; interval.value_namespace = name_space; interval.value_namespace_prefix = name_space_prefix; } if(value_path == "buckets") { buckets = value; buckets.value_namespace = name_space; buckets.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "interval") { interval.yfilter = yfilter; } if(value_path == "buckets") { buckets.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::IcmpEcho::History::Enhanced::has_leaf_or_child_of_name(const std::string & name) const { if(name == "interval" || name == "buckets") return true; return false; } Native::Ip::Sla::Entry::PathEcho::PathEcho() : dst_ip{YType::str, "dst-ip"}, source_ip{YType::str, "source-ip"}, paths_of_statistics_kept{YType::uint8, "paths-of-statistics-kept"}, samples_of_history_kept{YType::uint8, "samples-of-history-kept"}, hops_of_statistics_kept{YType::uint8, "hops-of-statistics-kept"} { yang_name = "path-echo"; yang_parent_name = "entry"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::PathEcho::~PathEcho() { } bool Native::Ip::Sla::Entry::PathEcho::has_data() const { if (is_presence_container) return true; return dst_ip.is_set || source_ip.is_set || paths_of_statistics_kept.is_set || samples_of_history_kept.is_set || hops_of_statistics_kept.is_set; } bool Native::Ip::Sla::Entry::PathEcho::has_operation() const { return is_set(yfilter) || ydk::is_set(dst_ip.yfilter) || ydk::is_set(source_ip.yfilter) || ydk::is_set(paths_of_statistics_kept.yfilter) || ydk::is_set(samples_of_history_kept.yfilter) || ydk::is_set(hops_of_statistics_kept.yfilter); } std::string Native::Ip::Sla::Entry::PathEcho::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "path-echo"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::PathEcho::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dst_ip.is_set || is_set(dst_ip.yfilter)) leaf_name_data.push_back(dst_ip.get_name_leafdata()); if (source_ip.is_set || is_set(source_ip.yfilter)) leaf_name_data.push_back(source_ip.get_name_leafdata()); if (paths_of_statistics_kept.is_set || is_set(paths_of_statistics_kept.yfilter)) leaf_name_data.push_back(paths_of_statistics_kept.get_name_leafdata()); if (samples_of_history_kept.is_set || is_set(samples_of_history_kept.yfilter)) leaf_name_data.push_back(samples_of_history_kept.get_name_leafdata()); if (hops_of_statistics_kept.is_set || is_set(hops_of_statistics_kept.yfilter)) leaf_name_data.push_back(hops_of_statistics_kept.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::PathEcho::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::PathEcho::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Entry::PathEcho::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dst-ip") { dst_ip = value; dst_ip.value_namespace = name_space; dst_ip.value_namespace_prefix = name_space_prefix; } if(value_path == "source-ip") { source_ip = value; source_ip.value_namespace = name_space; source_ip.value_namespace_prefix = name_space_prefix; } if(value_path == "paths-of-statistics-kept") { paths_of_statistics_kept = value; paths_of_statistics_kept.value_namespace = name_space; paths_of_statistics_kept.value_namespace_prefix = name_space_prefix; } if(value_path == "samples-of-history-kept") { samples_of_history_kept = value; samples_of_history_kept.value_namespace = name_space; samples_of_history_kept.value_namespace_prefix = name_space_prefix; } if(value_path == "hops-of-statistics-kept") { hops_of_statistics_kept = value; hops_of_statistics_kept.value_namespace = name_space; hops_of_statistics_kept.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::PathEcho::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dst-ip") { dst_ip.yfilter = yfilter; } if(value_path == "source-ip") { source_ip.yfilter = yfilter; } if(value_path == "paths-of-statistics-kept") { paths_of_statistics_kept.yfilter = yfilter; } if(value_path == "samples-of-history-kept") { samples_of_history_kept.yfilter = yfilter; } if(value_path == "hops-of-statistics-kept") { hops_of_statistics_kept.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::PathEcho::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dst-ip" || name == "source-ip" || name == "paths-of-statistics-kept" || name == "samples-of-history-kept" || name == "hops-of-statistics-kept") return true; return false; } Native::Ip::Sla::Entry::PathJitter::PathJitter() : dst_ip{YType::str, "dst-ip"}, source_ip{YType::str, "source-ip"}, frequency{YType::uint32, "frequency"}, lsr_path{YType::str, "lsr-path"}, owner{YType::str, "owner"}, request_data_size{YType::uint32, "request-data-size"}, tag{YType::str, "tag"}, threshold{YType::uint32, "threshold"}, timeout{YType::uint32, "timeout"}, tos{YType::uint8, "tos"}, verify_data{YType::empty, "verify-data"}, vrf{YType::str, "vrf"} , default_(std::make_shared<Native::Ip::Sla::Entry::PathJitter::Default>()) { default_->parent = this; yang_name = "path-jitter"; yang_parent_name = "entry"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::PathJitter::~PathJitter() { } bool Native::Ip::Sla::Entry::PathJitter::has_data() const { if (is_presence_container) return true; for (auto const & leaf : lsr_path.getYLeafs()) { if(leaf.is_set) return true; } return dst_ip.is_set || source_ip.is_set || frequency.is_set || owner.is_set || request_data_size.is_set || tag.is_set || threshold.is_set || timeout.is_set || tos.is_set || verify_data.is_set || vrf.is_set || (default_ != nullptr && default_->has_data()); } bool Native::Ip::Sla::Entry::PathJitter::has_operation() const { for (auto const & leaf : lsr_path.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(dst_ip.yfilter) || ydk::is_set(source_ip.yfilter) || ydk::is_set(frequency.yfilter) || ydk::is_set(lsr_path.yfilter) || ydk::is_set(owner.yfilter) || ydk::is_set(request_data_size.yfilter) || ydk::is_set(tag.yfilter) || ydk::is_set(threshold.yfilter) || ydk::is_set(timeout.yfilter) || ydk::is_set(tos.yfilter) || ydk::is_set(verify_data.yfilter) || ydk::is_set(vrf.yfilter) || (default_ != nullptr && default_->has_operation()); } std::string Native::Ip::Sla::Entry::PathJitter::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "path-jitter"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::PathJitter::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dst_ip.is_set || is_set(dst_ip.yfilter)) leaf_name_data.push_back(dst_ip.get_name_leafdata()); if (source_ip.is_set || is_set(source_ip.yfilter)) leaf_name_data.push_back(source_ip.get_name_leafdata()); if (frequency.is_set || is_set(frequency.yfilter)) leaf_name_data.push_back(frequency.get_name_leafdata()); if (owner.is_set || is_set(owner.yfilter)) leaf_name_data.push_back(owner.get_name_leafdata()); if (request_data_size.is_set || is_set(request_data_size.yfilter)) leaf_name_data.push_back(request_data_size.get_name_leafdata()); if (tag.is_set || is_set(tag.yfilter)) leaf_name_data.push_back(tag.get_name_leafdata()); if (threshold.is_set || is_set(threshold.yfilter)) leaf_name_data.push_back(threshold.get_name_leafdata()); if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata()); if (tos.is_set || is_set(tos.yfilter)) leaf_name_data.push_back(tos.get_name_leafdata()); if (verify_data.is_set || is_set(verify_data.yfilter)) leaf_name_data.push_back(verify_data.get_name_leafdata()); if (vrf.is_set || is_set(vrf.yfilter)) leaf_name_data.push_back(vrf.get_name_leafdata()); auto lsr_path_name_datas = lsr_path.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), lsr_path_name_datas.begin(), lsr_path_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::PathJitter::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "default") { if(default_ == nullptr) { default_ = std::make_shared<Native::Ip::Sla::Entry::PathJitter::Default>(); } return default_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::PathJitter::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(default_ != nullptr) { _children["default"] = default_; } return _children; } void Native::Ip::Sla::Entry::PathJitter::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dst-ip") { dst_ip = value; dst_ip.value_namespace = name_space; dst_ip.value_namespace_prefix = name_space_prefix; } if(value_path == "source-ip") { source_ip = value; source_ip.value_namespace = name_space; source_ip.value_namespace_prefix = name_space_prefix; } if(value_path == "frequency") { frequency = value; frequency.value_namespace = name_space; frequency.value_namespace_prefix = name_space_prefix; } if(value_path == "lsr-path") { lsr_path.append(value); } if(value_path == "owner") { owner = value; owner.value_namespace = name_space; owner.value_namespace_prefix = name_space_prefix; } if(value_path == "request-data-size") { request_data_size = value; request_data_size.value_namespace = name_space; request_data_size.value_namespace_prefix = name_space_prefix; } if(value_path == "tag") { tag = value; tag.value_namespace = name_space; tag.value_namespace_prefix = name_space_prefix; } if(value_path == "threshold") { threshold = value; threshold.value_namespace = name_space; threshold.value_namespace_prefix = name_space_prefix; } if(value_path == "timeout") { timeout = value; timeout.value_namespace = name_space; timeout.value_namespace_prefix = name_space_prefix; } if(value_path == "tos") { tos = value; tos.value_namespace = name_space; tos.value_namespace_prefix = name_space_prefix; } if(value_path == "verify-data") { verify_data = value; verify_data.value_namespace = name_space; verify_data.value_namespace_prefix = name_space_prefix; } if(value_path == "vrf") { vrf = value; vrf.value_namespace = name_space; vrf.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::PathJitter::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dst-ip") { dst_ip.yfilter = yfilter; } if(value_path == "source-ip") { source_ip.yfilter = yfilter; } if(value_path == "frequency") { frequency.yfilter = yfilter; } if(value_path == "lsr-path") { lsr_path.yfilter = yfilter; } if(value_path == "owner") { owner.yfilter = yfilter; } if(value_path == "request-data-size") { request_data_size.yfilter = yfilter; } if(value_path == "tag") { tag.yfilter = yfilter; } if(value_path == "threshold") { threshold.yfilter = yfilter; } if(value_path == "timeout") { timeout.yfilter = yfilter; } if(value_path == "tos") { tos.yfilter = yfilter; } if(value_path == "verify-data") { verify_data.yfilter = yfilter; } if(value_path == "vrf") { vrf.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::PathJitter::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default" || name == "dst-ip" || name == "source-ip" || name == "frequency" || name == "lsr-path" || name == "owner" || name == "request-data-size" || name == "tag" || name == "threshold" || name == "timeout" || name == "tos" || name == "verify-data" || name == "vrf") return true; return false; } Native::Ip::Sla::Entry::PathJitter::Default::Default() : frequency{YType::empty, "frequency"}, lsr_path{YType::empty, "lsr-path"}, owner{YType::empty, "owner"}, request_data_size{YType::empty, "request-data-size"}, tag{YType::empty, "tag"}, threshold{YType::empty, "threshold"}, timeout{YType::empty, "timeout"}, tos{YType::empty, "tos"}, verify_data{YType::empty, "verify-data"}, vrf{YType::empty, "vrf"} { yang_name = "default"; yang_parent_name = "path-jitter"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::PathJitter::Default::~Default() { } bool Native::Ip::Sla::Entry::PathJitter::Default::has_data() const { if (is_presence_container) return true; return frequency.is_set || lsr_path.is_set || owner.is_set || request_data_size.is_set || tag.is_set || threshold.is_set || timeout.is_set || tos.is_set || verify_data.is_set || vrf.is_set; } bool Native::Ip::Sla::Entry::PathJitter::Default::has_operation() const { return is_set(yfilter) || ydk::is_set(frequency.yfilter) || ydk::is_set(lsr_path.yfilter) || ydk::is_set(owner.yfilter) || ydk::is_set(request_data_size.yfilter) || ydk::is_set(tag.yfilter) || ydk::is_set(threshold.yfilter) || ydk::is_set(timeout.yfilter) || ydk::is_set(tos.yfilter) || ydk::is_set(verify_data.yfilter) || ydk::is_set(vrf.yfilter); } std::string Native::Ip::Sla::Entry::PathJitter::Default::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "default"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::PathJitter::Default::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (frequency.is_set || is_set(frequency.yfilter)) leaf_name_data.push_back(frequency.get_name_leafdata()); if (lsr_path.is_set || is_set(lsr_path.yfilter)) leaf_name_data.push_back(lsr_path.get_name_leafdata()); if (owner.is_set || is_set(owner.yfilter)) leaf_name_data.push_back(owner.get_name_leafdata()); if (request_data_size.is_set || is_set(request_data_size.yfilter)) leaf_name_data.push_back(request_data_size.get_name_leafdata()); if (tag.is_set || is_set(tag.yfilter)) leaf_name_data.push_back(tag.get_name_leafdata()); if (threshold.is_set || is_set(threshold.yfilter)) leaf_name_data.push_back(threshold.get_name_leafdata()); if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata()); if (tos.is_set || is_set(tos.yfilter)) leaf_name_data.push_back(tos.get_name_leafdata()); if (verify_data.is_set || is_set(verify_data.yfilter)) leaf_name_data.push_back(verify_data.get_name_leafdata()); if (vrf.is_set || is_set(vrf.yfilter)) leaf_name_data.push_back(vrf.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::PathJitter::Default::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::PathJitter::Default::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Entry::PathJitter::Default::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "frequency") { frequency = value; frequency.value_namespace = name_space; frequency.value_namespace_prefix = name_space_prefix; } if(value_path == "lsr-path") { lsr_path = value; lsr_path.value_namespace = name_space; lsr_path.value_namespace_prefix = name_space_prefix; } if(value_path == "owner") { owner = value; owner.value_namespace = name_space; owner.value_namespace_prefix = name_space_prefix; } if(value_path == "request-data-size") { request_data_size = value; request_data_size.value_namespace = name_space; request_data_size.value_namespace_prefix = name_space_prefix; } if(value_path == "tag") { tag = value; tag.value_namespace = name_space; tag.value_namespace_prefix = name_space_prefix; } if(value_path == "threshold") { threshold = value; threshold.value_namespace = name_space; threshold.value_namespace_prefix = name_space_prefix; } if(value_path == "timeout") { timeout = value; timeout.value_namespace = name_space; timeout.value_namespace_prefix = name_space_prefix; } if(value_path == "tos") { tos = value; tos.value_namespace = name_space; tos.value_namespace_prefix = name_space_prefix; } if(value_path == "verify-data") { verify_data = value; verify_data.value_namespace = name_space; verify_data.value_namespace_prefix = name_space_prefix; } if(value_path == "vrf") { vrf = value; vrf.value_namespace = name_space; vrf.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::PathJitter::Default::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "frequency") { frequency.yfilter = yfilter; } if(value_path == "lsr-path") { lsr_path.yfilter = yfilter; } if(value_path == "owner") { owner.yfilter = yfilter; } if(value_path == "request-data-size") { request_data_size.yfilter = yfilter; } if(value_path == "tag") { tag.yfilter = yfilter; } if(value_path == "threshold") { threshold.yfilter = yfilter; } if(value_path == "timeout") { timeout.yfilter = yfilter; } if(value_path == "tos") { tos.yfilter = yfilter; } if(value_path == "verify-data") { verify_data.yfilter = yfilter; } if(value_path == "vrf") { vrf.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::PathJitter::Default::has_leaf_or_child_of_name(const std::string & name) const { if(name == "frequency" || name == "lsr-path" || name == "owner" || name == "request-data-size" || name == "tag" || name == "threshold" || name == "timeout" || name == "tos" || name == "verify-data" || name == "vrf") return true; return false; } Native::Ip::Sla::Entry::UdpEcho::UdpEcho() : dest_addr{YType::str, "dest-addr"}, dest_port{YType::uint16, "dest-port"}, source_ip{YType::str, "source-ip"}, source_port{YType::uint16, "source-port"} { yang_name = "udp-echo"; yang_parent_name = "entry"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::UdpEcho::~UdpEcho() { } bool Native::Ip::Sla::Entry::UdpEcho::has_data() const { if (is_presence_container) return true; return dest_addr.is_set || dest_port.is_set || source_ip.is_set || source_port.is_set; } bool Native::Ip::Sla::Entry::UdpEcho::has_operation() const { return is_set(yfilter) || ydk::is_set(dest_addr.yfilter) || ydk::is_set(dest_port.yfilter) || ydk::is_set(source_ip.yfilter) || ydk::is_set(source_port.yfilter); } std::string Native::Ip::Sla::Entry::UdpEcho::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "udp-echo"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::UdpEcho::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dest_addr.is_set || is_set(dest_addr.yfilter)) leaf_name_data.push_back(dest_addr.get_name_leafdata()); if (dest_port.is_set || is_set(dest_port.yfilter)) leaf_name_data.push_back(dest_port.get_name_leafdata()); if (source_ip.is_set || is_set(source_ip.yfilter)) leaf_name_data.push_back(source_ip.get_name_leafdata()); if (source_port.is_set || is_set(source_port.yfilter)) leaf_name_data.push_back(source_port.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::UdpEcho::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::UdpEcho::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Entry::UdpEcho::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dest-addr") { dest_addr = value; dest_addr.value_namespace = name_space; dest_addr.value_namespace_prefix = name_space_prefix; } if(value_path == "dest-port") { dest_port = value; dest_port.value_namespace = name_space; dest_port.value_namespace_prefix = name_space_prefix; } if(value_path == "source-ip") { source_ip = value; source_ip.value_namespace = name_space; source_ip.value_namespace_prefix = name_space_prefix; } if(value_path == "source-port") { source_port = value; source_port.value_namespace = name_space; source_port.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::UdpEcho::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dest-addr") { dest_addr.yfilter = yfilter; } if(value_path == "dest-port") { dest_port.yfilter = yfilter; } if(value_path == "source-ip") { source_ip.yfilter = yfilter; } if(value_path == "source-port") { source_port.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::UdpEcho::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dest-addr" || name == "dest-port" || name == "source-ip" || name == "source-port") return true; return false; } Native::Ip::Sla::Entry::UdpJitter::UdpJitter() : dest_addr{YType::str, "dest-addr"}, portno{YType::uint16, "portno"}, codec{YType::enumeration, "codec"}, advantage_factor{YType::uint16, "advantage-factor"}, codec_interval{YType::uint32, "codec-interval"}, codec_numpackets{YType::uint32, "codec-numpackets"}, codec_size{YType::uint16, "codec-size"}, num_packets{YType::uint16, "num-packets"}, interval{YType::uint16, "interval"}, source_ip{YType::str, "source-ip"}, source_port{YType::uint16, "source-port"}, control{YType::enumeration, "control"}, owner{YType::str, "owner"}, request_data_size{YType::uint16, "request-data-size"}, tag{YType::str, "tag"}, threshold{YType::uint16, "threshold"}, timeout{YType::uint32, "timeout"}, tos{YType::uint8, "tos"}, traffic_class{YType::uint8, "traffic-class"}, vrf{YType::str, "vrf"} , history(std::make_shared<Native::Ip::Sla::Entry::UdpJitter::History>()) { history->parent = this; yang_name = "udp-jitter"; yang_parent_name = "entry"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::UdpJitter::~UdpJitter() { } bool Native::Ip::Sla::Entry::UdpJitter::has_data() const { if (is_presence_container) return true; return dest_addr.is_set || portno.is_set || codec.is_set || advantage_factor.is_set || codec_interval.is_set || codec_numpackets.is_set || codec_size.is_set || num_packets.is_set || interval.is_set || source_ip.is_set || source_port.is_set || control.is_set || owner.is_set || request_data_size.is_set || tag.is_set || threshold.is_set || timeout.is_set || tos.is_set || traffic_class.is_set || vrf.is_set || (history != nullptr && history->has_data()); } bool Native::Ip::Sla::Entry::UdpJitter::has_operation() const { return is_set(yfilter) || ydk::is_set(dest_addr.yfilter) || ydk::is_set(portno.yfilter) || ydk::is_set(codec.yfilter) || ydk::is_set(advantage_factor.yfilter) || ydk::is_set(codec_interval.yfilter) || ydk::is_set(codec_numpackets.yfilter) || ydk::is_set(codec_size.yfilter) || ydk::is_set(num_packets.yfilter) || ydk::is_set(interval.yfilter) || ydk::is_set(source_ip.yfilter) || ydk::is_set(source_port.yfilter) || ydk::is_set(control.yfilter) || ydk::is_set(owner.yfilter) || ydk::is_set(request_data_size.yfilter) || ydk::is_set(tag.yfilter) || ydk::is_set(threshold.yfilter) || ydk::is_set(timeout.yfilter) || ydk::is_set(tos.yfilter) || ydk::is_set(traffic_class.yfilter) || ydk::is_set(vrf.yfilter) || (history != nullptr && history->has_operation()); } std::string Native::Ip::Sla::Entry::UdpJitter::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "udp-jitter"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::UdpJitter::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dest_addr.is_set || is_set(dest_addr.yfilter)) leaf_name_data.push_back(dest_addr.get_name_leafdata()); if (portno.is_set || is_set(portno.yfilter)) leaf_name_data.push_back(portno.get_name_leafdata()); if (codec.is_set || is_set(codec.yfilter)) leaf_name_data.push_back(codec.get_name_leafdata()); if (advantage_factor.is_set || is_set(advantage_factor.yfilter)) leaf_name_data.push_back(advantage_factor.get_name_leafdata()); if (codec_interval.is_set || is_set(codec_interval.yfilter)) leaf_name_data.push_back(codec_interval.get_name_leafdata()); if (codec_numpackets.is_set || is_set(codec_numpackets.yfilter)) leaf_name_data.push_back(codec_numpackets.get_name_leafdata()); if (codec_size.is_set || is_set(codec_size.yfilter)) leaf_name_data.push_back(codec_size.get_name_leafdata()); if (num_packets.is_set || is_set(num_packets.yfilter)) leaf_name_data.push_back(num_packets.get_name_leafdata()); if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata()); if (source_ip.is_set || is_set(source_ip.yfilter)) leaf_name_data.push_back(source_ip.get_name_leafdata()); if (source_port.is_set || is_set(source_port.yfilter)) leaf_name_data.push_back(source_port.get_name_leafdata()); if (control.is_set || is_set(control.yfilter)) leaf_name_data.push_back(control.get_name_leafdata()); if (owner.is_set || is_set(owner.yfilter)) leaf_name_data.push_back(owner.get_name_leafdata()); if (request_data_size.is_set || is_set(request_data_size.yfilter)) leaf_name_data.push_back(request_data_size.get_name_leafdata()); if (tag.is_set || is_set(tag.yfilter)) leaf_name_data.push_back(tag.get_name_leafdata()); if (threshold.is_set || is_set(threshold.yfilter)) leaf_name_data.push_back(threshold.get_name_leafdata()); if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata()); if (tos.is_set || is_set(tos.yfilter)) leaf_name_data.push_back(tos.get_name_leafdata()); if (traffic_class.is_set || is_set(traffic_class.yfilter)) leaf_name_data.push_back(traffic_class.get_name_leafdata()); if (vrf.is_set || is_set(vrf.yfilter)) leaf_name_data.push_back(vrf.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::UdpJitter::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "history") { if(history == nullptr) { history = std::make_shared<Native::Ip::Sla::Entry::UdpJitter::History>(); } return history; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::UdpJitter::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(history != nullptr) { _children["history"] = history; } return _children; } void Native::Ip::Sla::Entry::UdpJitter::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dest-addr") { dest_addr = value; dest_addr.value_namespace = name_space; dest_addr.value_namespace_prefix = name_space_prefix; } if(value_path == "portno") { portno = value; portno.value_namespace = name_space; portno.value_namespace_prefix = name_space_prefix; } if(value_path == "codec") { codec = value; codec.value_namespace = name_space; codec.value_namespace_prefix = name_space_prefix; } if(value_path == "advantage-factor") { advantage_factor = value; advantage_factor.value_namespace = name_space; advantage_factor.value_namespace_prefix = name_space_prefix; } if(value_path == "codec-interval") { codec_interval = value; codec_interval.value_namespace = name_space; codec_interval.value_namespace_prefix = name_space_prefix; } if(value_path == "codec-numpackets") { codec_numpackets = value; codec_numpackets.value_namespace = name_space; codec_numpackets.value_namespace_prefix = name_space_prefix; } if(value_path == "codec-size") { codec_size = value; codec_size.value_namespace = name_space; codec_size.value_namespace_prefix = name_space_prefix; } if(value_path == "num-packets") { num_packets = value; num_packets.value_namespace = name_space; num_packets.value_namespace_prefix = name_space_prefix; } if(value_path == "interval") { interval = value; interval.value_namespace = name_space; interval.value_namespace_prefix = name_space_prefix; } if(value_path == "source-ip") { source_ip = value; source_ip.value_namespace = name_space; source_ip.value_namespace_prefix = name_space_prefix; } if(value_path == "source-port") { source_port = value; source_port.value_namespace = name_space; source_port.value_namespace_prefix = name_space_prefix; } if(value_path == "control") { control = value; control.value_namespace = name_space; control.value_namespace_prefix = name_space_prefix; } if(value_path == "owner") { owner = value; owner.value_namespace = name_space; owner.value_namespace_prefix = name_space_prefix; } if(value_path == "request-data-size") { request_data_size = value; request_data_size.value_namespace = name_space; request_data_size.value_namespace_prefix = name_space_prefix; } if(value_path == "tag") { tag = value; tag.value_namespace = name_space; tag.value_namespace_prefix = name_space_prefix; } if(value_path == "threshold") { threshold = value; threshold.value_namespace = name_space; threshold.value_namespace_prefix = name_space_prefix; } if(value_path == "timeout") { timeout = value; timeout.value_namespace = name_space; timeout.value_namespace_prefix = name_space_prefix; } if(value_path == "tos") { tos = value; tos.value_namespace = name_space; tos.value_namespace_prefix = name_space_prefix; } if(value_path == "traffic-class") { traffic_class = value; traffic_class.value_namespace = name_space; traffic_class.value_namespace_prefix = name_space_prefix; } if(value_path == "vrf") { vrf = value; vrf.value_namespace = name_space; vrf.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::UdpJitter::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dest-addr") { dest_addr.yfilter = yfilter; } if(value_path == "portno") { portno.yfilter = yfilter; } if(value_path == "codec") { codec.yfilter = yfilter; } if(value_path == "advantage-factor") { advantage_factor.yfilter = yfilter; } if(value_path == "codec-interval") { codec_interval.yfilter = yfilter; } if(value_path == "codec-numpackets") { codec_numpackets.yfilter = yfilter; } if(value_path == "codec-size") { codec_size.yfilter = yfilter; } if(value_path == "num-packets") { num_packets.yfilter = yfilter; } if(value_path == "interval") { interval.yfilter = yfilter; } if(value_path == "source-ip") { source_ip.yfilter = yfilter; } if(value_path == "source-port") { source_port.yfilter = yfilter; } if(value_path == "control") { control.yfilter = yfilter; } if(value_path == "owner") { owner.yfilter = yfilter; } if(value_path == "request-data-size") { request_data_size.yfilter = yfilter; } if(value_path == "tag") { tag.yfilter = yfilter; } if(value_path == "threshold") { threshold.yfilter = yfilter; } if(value_path == "timeout") { timeout.yfilter = yfilter; } if(value_path == "tos") { tos.yfilter = yfilter; } if(value_path == "traffic-class") { traffic_class.yfilter = yfilter; } if(value_path == "vrf") { vrf.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::UdpJitter::has_leaf_or_child_of_name(const std::string & name) const { if(name == "history" || name == "dest-addr" || name == "portno" || name == "codec" || name == "advantage-factor" || name == "codec-interval" || name == "codec-numpackets" || name == "codec-size" || name == "num-packets" || name == "interval" || name == "source-ip" || name == "source-port" || name == "control" || name == "owner" || name == "request-data-size" || name == "tag" || name == "threshold" || name == "timeout" || name == "tos" || name == "traffic-class" || name == "vrf") return true; return false; } Native::Ip::Sla::Entry::UdpJitter::History::History() : distributions_of_statistics_kept{YType::uint8, "distributions-of-statistics-kept"}, hours_of_statistics_kept{YType::uint8, "hours-of-statistics-kept"}, statistics_distribution_interval{YType::uint8, "statistics-distribution-interval"} , enhanced(std::make_shared<Native::Ip::Sla::Entry::UdpJitter::History::Enhanced>()) { enhanced->parent = this; yang_name = "history"; yang_parent_name = "udp-jitter"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::UdpJitter::History::~History() { } bool Native::Ip::Sla::Entry::UdpJitter::History::has_data() const { if (is_presence_container) return true; return distributions_of_statistics_kept.is_set || hours_of_statistics_kept.is_set || statistics_distribution_interval.is_set || (enhanced != nullptr && enhanced->has_data()); } bool Native::Ip::Sla::Entry::UdpJitter::History::has_operation() const { return is_set(yfilter) || ydk::is_set(distributions_of_statistics_kept.yfilter) || ydk::is_set(hours_of_statistics_kept.yfilter) || ydk::is_set(statistics_distribution_interval.yfilter) || (enhanced != nullptr && enhanced->has_operation()); } std::string Native::Ip::Sla::Entry::UdpJitter::History::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "history"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::UdpJitter::History::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (distributions_of_statistics_kept.is_set || is_set(distributions_of_statistics_kept.yfilter)) leaf_name_data.push_back(distributions_of_statistics_kept.get_name_leafdata()); if (hours_of_statistics_kept.is_set || is_set(hours_of_statistics_kept.yfilter)) leaf_name_data.push_back(hours_of_statistics_kept.get_name_leafdata()); if (statistics_distribution_interval.is_set || is_set(statistics_distribution_interval.yfilter)) leaf_name_data.push_back(statistics_distribution_interval.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::UdpJitter::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "enhanced") { if(enhanced == nullptr) { enhanced = std::make_shared<Native::Ip::Sla::Entry::UdpJitter::History::Enhanced>(); } return enhanced; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::UdpJitter::History::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(enhanced != nullptr) { _children["enhanced"] = enhanced; } return _children; } void Native::Ip::Sla::Entry::UdpJitter::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "distributions-of-statistics-kept") { distributions_of_statistics_kept = value; distributions_of_statistics_kept.value_namespace = name_space; distributions_of_statistics_kept.value_namespace_prefix = name_space_prefix; } if(value_path == "hours-of-statistics-kept") { hours_of_statistics_kept = value; hours_of_statistics_kept.value_namespace = name_space; hours_of_statistics_kept.value_namespace_prefix = name_space_prefix; } if(value_path == "statistics-distribution-interval") { statistics_distribution_interval = value; statistics_distribution_interval.value_namespace = name_space; statistics_distribution_interval.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::UdpJitter::History::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "distributions-of-statistics-kept") { distributions_of_statistics_kept.yfilter = yfilter; } if(value_path == "hours-of-statistics-kept") { hours_of_statistics_kept.yfilter = yfilter; } if(value_path == "statistics-distribution-interval") { statistics_distribution_interval.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::UdpJitter::History::has_leaf_or_child_of_name(const std::string & name) const { if(name == "enhanced" || name == "distributions-of-statistics-kept" || name == "hours-of-statistics-kept" || name == "statistics-distribution-interval") return true; return false; } Native::Ip::Sla::Entry::UdpJitter::History::Enhanced::Enhanced() : interval{YType::uint16, "interval"}, buckets{YType::uint8, "buckets"} { yang_name = "enhanced"; yang_parent_name = "history"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::UdpJitter::History::Enhanced::~Enhanced() { } bool Native::Ip::Sla::Entry::UdpJitter::History::Enhanced::has_data() const { if (is_presence_container) return true; return interval.is_set || buckets.is_set; } bool Native::Ip::Sla::Entry::UdpJitter::History::Enhanced::has_operation() const { return is_set(yfilter) || ydk::is_set(interval.yfilter) || ydk::is_set(buckets.yfilter); } std::string Native::Ip::Sla::Entry::UdpJitter::History::Enhanced::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "enhanced"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::UdpJitter::History::Enhanced::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata()); if (buckets.is_set || is_set(buckets.yfilter)) leaf_name_data.push_back(buckets.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::UdpJitter::History::Enhanced::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::UdpJitter::History::Enhanced::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Entry::UdpJitter::History::Enhanced::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "interval") { interval = value; interval.value_namespace = name_space; interval.value_namespace_prefix = name_space_prefix; } if(value_path == "buckets") { buckets = value; buckets.value_namespace = name_space; buckets.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::UdpJitter::History::Enhanced::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "interval") { interval.yfilter = yfilter; } if(value_path == "buckets") { buckets.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::UdpJitter::History::Enhanced::has_leaf_or_child_of_name(const std::string & name) const { if(name == "interval" || name == "buckets") return true; return false; } Native::Ip::Sla::Entry::Http::Http() : owner{YType::str, "owner"}, tag{YType::str, "tag"}, vrf{YType::str, "vrf"} , get(std::make_shared<Native::Ip::Sla::Entry::Http::Get>()) , raw(std::make_shared<Native::Ip::Sla::Entry::Http::Raw>()) { get->parent = this; raw->parent = this; yang_name = "http"; yang_parent_name = "entry"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::Http::~Http() { } bool Native::Ip::Sla::Entry::Http::has_data() const { if (is_presence_container) return true; return owner.is_set || tag.is_set || vrf.is_set || (get != nullptr && get->has_data()) || (raw != nullptr && raw->has_data()); } bool Native::Ip::Sla::Entry::Http::has_operation() const { return is_set(yfilter) || ydk::is_set(owner.yfilter) || ydk::is_set(tag.yfilter) || ydk::is_set(vrf.yfilter) || (get != nullptr && get->has_operation()) || (raw != nullptr && raw->has_operation()); } std::string Native::Ip::Sla::Entry::Http::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "http"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::Http::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (owner.is_set || is_set(owner.yfilter)) leaf_name_data.push_back(owner.get_name_leafdata()); if (tag.is_set || is_set(tag.yfilter)) leaf_name_data.push_back(tag.get_name_leafdata()); if (vrf.is_set || is_set(vrf.yfilter)) leaf_name_data.push_back(vrf.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::Http::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "get") { if(get == nullptr) { get = std::make_shared<Native::Ip::Sla::Entry::Http::Get>(); } return get; } if(child_yang_name == "raw") { if(raw == nullptr) { raw = std::make_shared<Native::Ip::Sla::Entry::Http::Raw>(); } return raw; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::Http::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(get != nullptr) { _children["get"] = get; } if(raw != nullptr) { _children["raw"] = raw; } return _children; } void Native::Ip::Sla::Entry::Http::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "owner") { owner = value; owner.value_namespace = name_space; owner.value_namespace_prefix = name_space_prefix; } if(value_path == "tag") { tag = value; tag.value_namespace = name_space; tag.value_namespace_prefix = name_space_prefix; } if(value_path == "vrf") { vrf = value; vrf.value_namespace = name_space; vrf.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::Http::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "owner") { owner.yfilter = yfilter; } if(value_path == "tag") { tag.yfilter = yfilter; } if(value_path == "vrf") { vrf.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::Http::has_leaf_or_child_of_name(const std::string & name) const { if(name == "get" || name == "raw" || name == "owner" || name == "tag" || name == "vrf") return true; return false; } Native::Ip::Sla::Entry::Http::Get::Get() : url{YType::str, "url"}, source_ip{YType::str, "source-ip"}, source_port{YType::uint16, "source-port"}, name_server{YType::str, "name-server"} { yang_name = "get"; yang_parent_name = "http"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::Http::Get::~Get() { } bool Native::Ip::Sla::Entry::Http::Get::has_data() const { if (is_presence_container) return true; return url.is_set || source_ip.is_set || source_port.is_set || name_server.is_set; } bool Native::Ip::Sla::Entry::Http::Get::has_operation() const { return is_set(yfilter) || ydk::is_set(url.yfilter) || ydk::is_set(source_ip.yfilter) || ydk::is_set(source_port.yfilter) || ydk::is_set(name_server.yfilter); } std::string Native::Ip::Sla::Entry::Http::Get::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "get"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::Http::Get::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (url.is_set || is_set(url.yfilter)) leaf_name_data.push_back(url.get_name_leafdata()); if (source_ip.is_set || is_set(source_ip.yfilter)) leaf_name_data.push_back(source_ip.get_name_leafdata()); if (source_port.is_set || is_set(source_port.yfilter)) leaf_name_data.push_back(source_port.get_name_leafdata()); if (name_server.is_set || is_set(name_server.yfilter)) leaf_name_data.push_back(name_server.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::Http::Get::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::Http::Get::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Entry::Http::Get::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "url") { url = value; url.value_namespace = name_space; url.value_namespace_prefix = name_space_prefix; } if(value_path == "source-ip") { source_ip = value; source_ip.value_namespace = name_space; source_ip.value_namespace_prefix = name_space_prefix; } if(value_path == "source-port") { source_port = value; source_port.value_namespace = name_space; source_port.value_namespace_prefix = name_space_prefix; } if(value_path == "name-server") { name_server = value; name_server.value_namespace = name_space; name_server.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::Http::Get::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "url") { url.yfilter = yfilter; } if(value_path == "source-ip") { source_ip.yfilter = yfilter; } if(value_path == "source-port") { source_port.yfilter = yfilter; } if(value_path == "name-server") { name_server.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::Http::Get::has_leaf_or_child_of_name(const std::string & name) const { if(name == "url" || name == "source-ip" || name == "source-port" || name == "name-server") return true; return false; } Native::Ip::Sla::Entry::Http::Raw::Raw() : url{YType::str, "url"}, source_ip{YType::str, "source-ip"}, source_port{YType::uint16, "source-port"}, name_server{YType::str, "name-server"} { yang_name = "raw"; yang_parent_name = "http"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::Http::Raw::~Raw() { } bool Native::Ip::Sla::Entry::Http::Raw::has_data() const { if (is_presence_container) return true; return url.is_set || source_ip.is_set || source_port.is_set || name_server.is_set; } bool Native::Ip::Sla::Entry::Http::Raw::has_operation() const { return is_set(yfilter) || ydk::is_set(url.yfilter) || ydk::is_set(source_ip.yfilter) || ydk::is_set(source_port.yfilter) || ydk::is_set(name_server.yfilter); } std::string Native::Ip::Sla::Entry::Http::Raw::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "raw"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::Http::Raw::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (url.is_set || is_set(url.yfilter)) leaf_name_data.push_back(url.get_name_leafdata()); if (source_ip.is_set || is_set(source_ip.yfilter)) leaf_name_data.push_back(source_ip.get_name_leafdata()); if (source_port.is_set || is_set(source_port.yfilter)) leaf_name_data.push_back(source_port.get_name_leafdata()); if (name_server.is_set || is_set(name_server.yfilter)) leaf_name_data.push_back(name_server.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::Http::Raw::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::Http::Raw::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Entry::Http::Raw::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "url") { url = value; url.value_namespace = name_space; url.value_namespace_prefix = name_space_prefix; } if(value_path == "source-ip") { source_ip = value; source_ip.value_namespace = name_space; source_ip.value_namespace_prefix = name_space_prefix; } if(value_path == "source-port") { source_port = value; source_port.value_namespace = name_space; source_port.value_namespace_prefix = name_space_prefix; } if(value_path == "name-server") { name_server = value; name_server.value_namespace = name_space; name_server.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::Http::Raw::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "url") { url.yfilter = yfilter; } if(value_path == "source-ip") { source_ip.yfilter = yfilter; } if(value_path == "source-port") { source_port.yfilter = yfilter; } if(value_path == "name-server") { name_server.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::Http::Raw::has_leaf_or_child_of_name(const std::string & name) const { if(name == "url" || name == "source-ip" || name == "source-port" || name == "name-server") return true; return false; } Native::Ip::Sla::Entry::Dhcp::Dhcp() : dst_ip{YType::str, "dst-ip"}, source_ip{YType::str, "source-ip"} { yang_name = "dhcp"; yang_parent_name = "entry"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::Dhcp::~Dhcp() { } bool Native::Ip::Sla::Entry::Dhcp::has_data() const { if (is_presence_container) return true; return dst_ip.is_set || source_ip.is_set; } bool Native::Ip::Sla::Entry::Dhcp::has_operation() const { return is_set(yfilter) || ydk::is_set(dst_ip.yfilter) || ydk::is_set(source_ip.yfilter); } std::string Native::Ip::Sla::Entry::Dhcp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dhcp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::Dhcp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dst_ip.is_set || is_set(dst_ip.yfilter)) leaf_name_data.push_back(dst_ip.get_name_leafdata()); if (source_ip.is_set || is_set(source_ip.yfilter)) leaf_name_data.push_back(source_ip.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::Dhcp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::Dhcp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Entry::Dhcp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dst-ip") { dst_ip = value; dst_ip.value_namespace = name_space; dst_ip.value_namespace_prefix = name_space_prefix; } if(value_path == "source-ip") { source_ip = value; source_ip.value_namespace = name_space; source_ip.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::Dhcp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dst-ip") { dst_ip.yfilter = yfilter; } if(value_path == "source-ip") { source_ip.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::Dhcp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dst-ip" || name == "source-ip") return true; return false; } Native::Ip::Sla::Entry::Ethernet::Ethernet() : y1731(std::make_shared<Native::Ip::Sla::Entry::Ethernet::Y1731>()) , aggregate(std::make_shared<Native::Ip::Sla::Entry::Ethernet::Aggregate>()) , history(std::make_shared<Native::Ip::Sla::Entry::Ethernet::History>()) { y1731->parent = this; aggregate->parent = this; history->parent = this; yang_name = "ethernet"; yang_parent_name = "entry"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::Ethernet::~Ethernet() { } bool Native::Ip::Sla::Entry::Ethernet::has_data() const { if (is_presence_container) return true; return (y1731 != nullptr && y1731->has_data()) || (aggregate != nullptr && aggregate->has_data()) || (history != nullptr && history->has_data()); } bool Native::Ip::Sla::Entry::Ethernet::has_operation() const { return is_set(yfilter) || (y1731 != nullptr && y1731->has_operation()) || (aggregate != nullptr && aggregate->has_operation()) || (history != nullptr && history->has_operation()); } std::string Native::Ip::Sla::Entry::Ethernet::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ethernet"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::Ethernet::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::Ethernet::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "y1731") { if(y1731 == nullptr) { y1731 = std::make_shared<Native::Ip::Sla::Entry::Ethernet::Y1731>(); } return y1731; } if(child_yang_name == "aggregate") { if(aggregate == nullptr) { aggregate = std::make_shared<Native::Ip::Sla::Entry::Ethernet::Aggregate>(); } return aggregate; } if(child_yang_name == "history") { if(history == nullptr) { history = std::make_shared<Native::Ip::Sla::Entry::Ethernet::History>(); } return history; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::Ethernet::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(y1731 != nullptr) { _children["y1731"] = y1731; } if(aggregate != nullptr) { _children["aggregate"] = aggregate; } if(history != nullptr) { _children["history"] = history; } return _children; } void Native::Ip::Sla::Entry::Ethernet::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Sla::Entry::Ethernet::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Sla::Entry::Ethernet::has_leaf_or_child_of_name(const std::string & name) const { if(name == "y1731" || name == "aggregate" || name == "history") return true; return false; } Native::Ip::Sla::Entry::Ethernet::Y1731::Y1731() : delay(std::make_shared<Native::Ip::Sla::Entry::Ethernet::Y1731::Delay>()) { delay->parent = this; yang_name = "y1731"; yang_parent_name = "ethernet"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::Ethernet::Y1731::~Y1731() { } bool Native::Ip::Sla::Entry::Ethernet::Y1731::has_data() const { if (is_presence_container) return true; return (delay != nullptr && delay->has_data()); } bool Native::Ip::Sla::Entry::Ethernet::Y1731::has_operation() const { return is_set(yfilter) || (delay != nullptr && delay->has_operation()); } std::string Native::Ip::Sla::Entry::Ethernet::Y1731::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "y1731"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::Ethernet::Y1731::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::Ethernet::Y1731::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "delay") { if(delay == nullptr) { delay = std::make_shared<Native::Ip::Sla::Entry::Ethernet::Y1731::Delay>(); } return delay; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::Ethernet::Y1731::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(delay != nullptr) { _children["delay"] = delay; } return _children; } void Native::Ip::Sla::Entry::Ethernet::Y1731::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Sla::Entry::Ethernet::Y1731::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Sla::Entry::Ethernet::Y1731::has_leaf_or_child_of_name(const std::string & name) const { if(name == "delay") return true; return false; } Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Delay() : name{YType::enumeration, "name"}, burst{YType::empty, "burst"}, domain{YType::str, "domain"}, evc{YType::str, "evc"}, vlan{YType::uint16, "vlan"}, mac_address{YType::str, "mac-address"}, mpid{YType::uint16, "mpid"}, cos{YType::uint8, "cos"} , source(std::make_shared<Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source>()) { source->parent = this; yang_name = "delay"; yang_parent_name = "y1731"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::~Delay() { } bool Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::has_data() const { if (is_presence_container) return true; return name.is_set || burst.is_set || domain.is_set || evc.is_set || vlan.is_set || mac_address.is_set || mpid.is_set || cos.is_set || (source != nullptr && source->has_data()); } bool Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || ydk::is_set(burst.yfilter) || ydk::is_set(domain.yfilter) || ydk::is_set(evc.yfilter) || ydk::is_set(vlan.yfilter) || ydk::is_set(mac_address.yfilter) || ydk::is_set(mpid.yfilter) || ydk::is_set(cos.yfilter) || (source != nullptr && source->has_operation()); } std::string Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "delay"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); if (burst.is_set || is_set(burst.yfilter)) leaf_name_data.push_back(burst.get_name_leafdata()); if (domain.is_set || is_set(domain.yfilter)) leaf_name_data.push_back(domain.get_name_leafdata()); if (evc.is_set || is_set(evc.yfilter)) leaf_name_data.push_back(evc.get_name_leafdata()); if (vlan.is_set || is_set(vlan.yfilter)) leaf_name_data.push_back(vlan.get_name_leafdata()); if (mac_address.is_set || is_set(mac_address.yfilter)) leaf_name_data.push_back(mac_address.get_name_leafdata()); if (mpid.is_set || is_set(mpid.yfilter)) leaf_name_data.push_back(mpid.get_name_leafdata()); if (cos.is_set || is_set(cos.yfilter)) leaf_name_data.push_back(cos.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "source") { if(source == nullptr) { source = std::make_shared<Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source>(); } return source; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(source != nullptr) { _children["source"] = source; } return _children; } void Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } if(value_path == "burst") { burst = value; burst.value_namespace = name_space; burst.value_namespace_prefix = name_space_prefix; } if(value_path == "domain") { domain = value; domain.value_namespace = name_space; domain.value_namespace_prefix = name_space_prefix; } if(value_path == "evc") { evc = value; evc.value_namespace = name_space; evc.value_namespace_prefix = name_space_prefix; } if(value_path == "vlan") { vlan = value; vlan.value_namespace = name_space; vlan.value_namespace_prefix = name_space_prefix; } if(value_path == "mac-address") { mac_address = value; mac_address.value_namespace = name_space; mac_address.value_namespace_prefix = name_space_prefix; } if(value_path == "mpid") { mpid = value; mpid.value_namespace = name_space; mpid.value_namespace_prefix = name_space_prefix; } if(value_path == "cos") { cos = value; cos.value_namespace = name_space; cos.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } if(value_path == "burst") { burst.yfilter = yfilter; } if(value_path == "domain") { domain.yfilter = yfilter; } if(value_path == "evc") { evc.yfilter = yfilter; } if(value_path == "vlan") { vlan.yfilter = yfilter; } if(value_path == "mac-address") { mac_address.yfilter = yfilter; } if(value_path == "mpid") { mpid.yfilter = yfilter; } if(value_path == "cos") { cos.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::has_leaf_or_child_of_name(const std::string & name) const { if(name == "source" || name == "name" || name == "burst" || name == "domain" || name == "evc" || name == "vlan" || name == "mac-address" || name == "mpid" || name == "cos") return true; return false; } Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source::Source() : mac_address{YType::str, "mac-address"}, mpid{YType::uint16, "mpid"} { yang_name = "source"; yang_parent_name = "delay"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source::~Source() { } bool Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source::has_data() const { if (is_presence_container) return true; return mac_address.is_set || mpid.is_set; } bool Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source::has_operation() const { return is_set(yfilter) || ydk::is_set(mac_address.yfilter) || ydk::is_set(mpid.yfilter); } std::string Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "source"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (mac_address.is_set || is_set(mac_address.yfilter)) leaf_name_data.push_back(mac_address.get_name_leafdata()); if (mpid.is_set || is_set(mpid.yfilter)) leaf_name_data.push_back(mpid.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "mac-address") { mac_address = value; mac_address.value_namespace = name_space; mac_address.value_namespace_prefix = name_space_prefix; } if(value_path == "mpid") { mpid = value; mpid.value_namespace = name_space; mpid.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "mac-address") { mac_address.yfilter = yfilter; } if(value_path == "mpid") { mpid.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Source::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mac-address" || name == "mpid") return true; return false; } Native::Ip::Sla::Entry::Ethernet::Aggregate::Aggregate() : interval{YType::uint32, "interval"} { yang_name = "aggregate"; yang_parent_name = "ethernet"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::Ethernet::Aggregate::~Aggregate() { } bool Native::Ip::Sla::Entry::Ethernet::Aggregate::has_data() const { if (is_presence_container) return true; return interval.is_set; } bool Native::Ip::Sla::Entry::Ethernet::Aggregate::has_operation() const { return is_set(yfilter) || ydk::is_set(interval.yfilter); } std::string Native::Ip::Sla::Entry::Ethernet::Aggregate::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "aggregate"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::Ethernet::Aggregate::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::Ethernet::Aggregate::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::Ethernet::Aggregate::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Entry::Ethernet::Aggregate::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "interval") { interval = value; interval.value_namespace = name_space; interval.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::Ethernet::Aggregate::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "interval") { interval.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::Ethernet::Aggregate::has_leaf_or_child_of_name(const std::string & name) const { if(name == "interval") return true; return false; } Native::Ip::Sla::Entry::Ethernet::History::History() : interval{YType::uint8, "interval"} { yang_name = "history"; yang_parent_name = "ethernet"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Entry::Ethernet::History::~History() { } bool Native::Ip::Sla::Entry::Ethernet::History::has_data() const { if (is_presence_container) return true; return interval.is_set; } bool Native::Ip::Sla::Entry::Ethernet::History::has_operation() const { return is_set(yfilter) || ydk::is_set(interval.yfilter); } std::string Native::Ip::Sla::Entry::Ethernet::History::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "history"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Entry::Ethernet::History::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Entry::Ethernet::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Entry::Ethernet::History::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Entry::Ethernet::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "interval") { interval = value; interval.value_namespace = name_space; interval.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Entry::Ethernet::History::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "interval") { interval.yfilter = yfilter; } } bool Native::Ip::Sla::Entry::Ethernet::History::has_leaf_or_child_of_name(const std::string & name) const { if(name == "interval") return true; return false; } Native::Ip::Sla::Enable::Enable() : reaction_alerts{YType::empty, "reaction-alerts"} { yang_name = "enable"; yang_parent_name = "sla"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::Enable::~Enable() { } bool Native::Ip::Sla::Enable::has_data() const { if (is_presence_container) return true; return reaction_alerts.is_set; } bool Native::Ip::Sla::Enable::has_operation() const { return is_set(yfilter) || ydk::is_set(reaction_alerts.yfilter); } std::string Native::Ip::Sla::Enable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Enable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "enable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Enable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (reaction_alerts.is_set || is_set(reaction_alerts.yfilter)) leaf_name_data.push_back(reaction_alerts.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Enable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Enable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Enable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "reaction-alerts") { reaction_alerts = value; reaction_alerts.value_namespace = name_space; reaction_alerts.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Enable::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "reaction-alerts") { reaction_alerts.yfilter = yfilter; } } bool Native::Ip::Sla::Enable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "reaction-alerts") return true; return false; } Native::Ip::Sla::Responder::Responder() : udp_echo(std::make_shared<Native::Ip::Sla::Responder::UdpEcho>()) , tcp_connect(std::make_shared<Native::Ip::Sla::Responder::TcpConnect>()) { udp_echo->parent = this; tcp_connect->parent = this; yang_name = "responder"; yang_parent_name = "sla"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } Native::Ip::Sla::Responder::~Responder() { } bool Native::Ip::Sla::Responder::has_data() const { if (is_presence_container) return true; return (udp_echo != nullptr && udp_echo->has_data()) || (tcp_connect != nullptr && tcp_connect->has_data()); } bool Native::Ip::Sla::Responder::has_operation() const { return is_set(yfilter) || (udp_echo != nullptr && udp_echo->has_operation()) || (tcp_connect != nullptr && tcp_connect->has_operation()); } std::string Native::Ip::Sla::Responder::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Responder::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "responder"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Responder::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Responder::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "udp-echo") { if(udp_echo == nullptr) { udp_echo = std::make_shared<Native::Ip::Sla::Responder::UdpEcho>(); } return udp_echo; } if(child_yang_name == "tcp-connect") { if(tcp_connect == nullptr) { tcp_connect = std::make_shared<Native::Ip::Sla::Responder::TcpConnect>(); } return tcp_connect; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Responder::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(udp_echo != nullptr) { _children["udp-echo"] = udp_echo; } if(tcp_connect != nullptr) { _children["tcp-connect"] = tcp_connect; } return _children; } void Native::Ip::Sla::Responder::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Sla::Responder::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Sla::Responder::has_leaf_or_child_of_name(const std::string & name) const { if(name == "udp-echo" || name == "tcp-connect") return true; return false; } Native::Ip::Sla::Responder::UdpEcho::UdpEcho() : port{YType::uint16, "port"} , ipaddress(this, {"host"}) { yang_name = "udp-echo"; yang_parent_name = "responder"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::Responder::UdpEcho::~UdpEcho() { } bool Native::Ip::Sla::Responder::UdpEcho::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipaddress.len(); index++) { if(ipaddress[index]->has_data()) return true; } return port.is_set; } bool Native::Ip::Sla::Responder::UdpEcho::has_operation() const { for (std::size_t index=0; index<ipaddress.len(); index++) { if(ipaddress[index]->has_operation()) return true; } return is_set(yfilter) || ydk::is_set(port.yfilter); } std::string Native::Ip::Sla::Responder::UdpEcho::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/responder/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Responder::UdpEcho::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "udp-echo"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Responder::UdpEcho::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (port.is_set || is_set(port.yfilter)) leaf_name_data.push_back(port.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Responder::UdpEcho::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipaddress") { auto ent_ = std::make_shared<Native::Ip::Sla::Responder::UdpEcho::Ipaddress>(); ent_->parent = this; ipaddress.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Responder::UdpEcho::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipaddress.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Sla::Responder::UdpEcho::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "port") { port = value; port.value_namespace = name_space; port.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Responder::UdpEcho::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "port") { port.yfilter = yfilter; } } bool Native::Ip::Sla::Responder::UdpEcho::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipaddress" || name == "port") return true; return false; } Native::Ip::Sla::Responder::UdpEcho::Ipaddress::Ipaddress() : host{YType::str, "host"}, port{YType::uint16, "port"} { yang_name = "ipaddress"; yang_parent_name = "udp-echo"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::Responder::UdpEcho::Ipaddress::~Ipaddress() { } bool Native::Ip::Sla::Responder::UdpEcho::Ipaddress::has_data() const { if (is_presence_container) return true; return host.is_set || port.is_set; } bool Native::Ip::Sla::Responder::UdpEcho::Ipaddress::has_operation() const { return is_set(yfilter) || ydk::is_set(host.yfilter) || ydk::is_set(port.yfilter); } std::string Native::Ip::Sla::Responder::UdpEcho::Ipaddress::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/responder/udp-echo/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Responder::UdpEcho::Ipaddress::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipaddress"; ADD_KEY_TOKEN(host, "host"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Responder::UdpEcho::Ipaddress::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (host.is_set || is_set(host.yfilter)) leaf_name_data.push_back(host.get_name_leafdata()); if (port.is_set || is_set(port.yfilter)) leaf_name_data.push_back(port.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Responder::UdpEcho::Ipaddress::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Responder::UdpEcho::Ipaddress::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Responder::UdpEcho::Ipaddress::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "host") { host = value; host.value_namespace = name_space; host.value_namespace_prefix = name_space_prefix; } if(value_path == "port") { port = value; port.value_namespace = name_space; port.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Responder::UdpEcho::Ipaddress::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "host") { host.yfilter = yfilter; } if(value_path == "port") { port.yfilter = yfilter; } } bool Native::Ip::Sla::Responder::UdpEcho::Ipaddress::has_leaf_or_child_of_name(const std::string & name) const { if(name == "host" || name == "port") return true; return false; } Native::Ip::Sla::Responder::TcpConnect::TcpConnect() : port{YType::uint16, "port"} , ipaddress(this, {"host"}) { yang_name = "tcp-connect"; yang_parent_name = "responder"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::Responder::TcpConnect::~TcpConnect() { } bool Native::Ip::Sla::Responder::TcpConnect::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipaddress.len(); index++) { if(ipaddress[index]->has_data()) return true; } return port.is_set; } bool Native::Ip::Sla::Responder::TcpConnect::has_operation() const { for (std::size_t index=0; index<ipaddress.len(); index++) { if(ipaddress[index]->has_operation()) return true; } return is_set(yfilter) || ydk::is_set(port.yfilter); } std::string Native::Ip::Sla::Responder::TcpConnect::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/responder/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Responder::TcpConnect::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "tcp-connect"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Responder::TcpConnect::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (port.is_set || is_set(port.yfilter)) leaf_name_data.push_back(port.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Responder::TcpConnect::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipaddress") { auto ent_ = std::make_shared<Native::Ip::Sla::Responder::TcpConnect::Ipaddress>(); ent_->parent = this; ipaddress.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Responder::TcpConnect::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipaddress.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Sla::Responder::TcpConnect::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "port") { port = value; port.value_namespace = name_space; port.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Responder::TcpConnect::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "port") { port.yfilter = yfilter; } } bool Native::Ip::Sla::Responder::TcpConnect::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipaddress" || name == "port") return true; return false; } Native::Ip::Sla::Responder::TcpConnect::Ipaddress::Ipaddress() : host{YType::str, "host"}, port{YType::uint16, "port"} { yang_name = "ipaddress"; yang_parent_name = "tcp-connect"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::Responder::TcpConnect::Ipaddress::~Ipaddress() { } bool Native::Ip::Sla::Responder::TcpConnect::Ipaddress::has_data() const { if (is_presence_container) return true; return host.is_set || port.is_set; } bool Native::Ip::Sla::Responder::TcpConnect::Ipaddress::has_operation() const { return is_set(yfilter) || ydk::is_set(host.yfilter) || ydk::is_set(port.yfilter); } std::string Native::Ip::Sla::Responder::TcpConnect::Ipaddress::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/responder/tcp-connect/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Responder::TcpConnect::Ipaddress::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipaddress"; ADD_KEY_TOKEN(host, "host"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Responder::TcpConnect::Ipaddress::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (host.is_set || is_set(host.yfilter)) leaf_name_data.push_back(host.get_name_leafdata()); if (port.is_set || is_set(port.yfilter)) leaf_name_data.push_back(port.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Responder::TcpConnect::Ipaddress::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Responder::TcpConnect::Ipaddress::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Responder::TcpConnect::Ipaddress::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "host") { host = value; host.value_namespace = name_space; host.value_namespace_prefix = name_space_prefix; } if(value_path == "port") { port = value; port.value_namespace = name_space; port.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Responder::TcpConnect::Ipaddress::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "host") { host.yfilter = yfilter; } if(value_path == "port") { port.yfilter = yfilter; } } bool Native::Ip::Sla::Responder::TcpConnect::Ipaddress::has_leaf_or_child_of_name(const std::string & name) const { if(name == "host" || name == "port") return true; return false; } Native::Ip::Sla::Logging::Logging() : traps{YType::empty, "traps"} { yang_name = "logging"; yang_parent_name = "sla"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::Logging::~Logging() { } bool Native::Ip::Sla::Logging::has_data() const { if (is_presence_container) return true; return traps.is_set; } bool Native::Ip::Sla::Logging::has_operation() const { return is_set(yfilter) || ydk::is_set(traps.yfilter); } std::string Native::Ip::Sla::Logging::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Logging::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "logging"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Logging::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (traps.is_set || is_set(traps.yfilter)) leaf_name_data.push_back(traps.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Logging::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Logging::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Logging::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "traps") { traps = value; traps.value_namespace = name_space; traps.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Logging::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "traps") { traps.yfilter = yfilter; } } bool Native::Ip::Sla::Logging::has_leaf_or_child_of_name(const std::string & name) const { if(name == "traps") return true; return false; } Native::Ip::Sla::Group::Group() : schedule(this, {"entry_number"}) { yang_name = "group"; yang_parent_name = "sla"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::Group::~Group() { } bool Native::Ip::Sla::Group::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<schedule.len(); index++) { if(schedule[index]->has_data()) return true; } return false; } bool Native::Ip::Sla::Group::has_operation() const { for (std::size_t index=0; index<schedule.len(); index++) { if(schedule[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Sla::Group::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Group::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "group"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Group::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Group::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "schedule") { auto ent_ = std::make_shared<Native::Ip::Sla::Group::Schedule>(); ent_->parent = this; schedule.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Group::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : schedule.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Sla::Group::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Sla::Group::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Sla::Group::has_leaf_or_child_of_name(const std::string & name) const { if(name == "schedule") return true; return false; } Native::Ip::Sla::Group::Schedule::Schedule() : entry_number{YType::uint32, "entry-number"} , probe_ids(this, {"word"}) { yang_name = "schedule"; yang_parent_name = "group"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::Group::Schedule::~Schedule() { } bool Native::Ip::Sla::Group::Schedule::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<probe_ids.len(); index++) { if(probe_ids[index]->has_data()) return true; } return entry_number.is_set; } bool Native::Ip::Sla::Group::Schedule::has_operation() const { for (std::size_t index=0; index<probe_ids.len(); index++) { if(probe_ids[index]->has_operation()) return true; } return is_set(yfilter) || ydk::is_set(entry_number.yfilter); } std::string Native::Ip::Sla::Group::Schedule::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/group/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Group::Schedule::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "schedule"; ADD_KEY_TOKEN(entry_number, "entry-number"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Group::Schedule::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (entry_number.is_set || is_set(entry_number.yfilter)) leaf_name_data.push_back(entry_number.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Group::Schedule::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "probe-ids") { auto ent_ = std::make_shared<Native::Ip::Sla::Group::Schedule::ProbeIds>(); ent_->parent = this; probe_ids.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Group::Schedule::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : probe_ids.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Sla::Group::Schedule::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "entry-number") { entry_number = value; entry_number.value_namespace = name_space; entry_number.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Group::Schedule::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "entry-number") { entry_number.yfilter = yfilter; } } bool Native::Ip::Sla::Group::Schedule::has_leaf_or_child_of_name(const std::string & name) const { if(name == "probe-ids" || name == "entry-number") return true; return false; } Native::Ip::Sla::Group::Schedule::ProbeIds::ProbeIds() : word{YType::str, "word"} , schedule_period(std::make_shared<Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod>()) { schedule_period->parent = this; yang_name = "probe-ids"; yang_parent_name = "schedule"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Group::Schedule::ProbeIds::~ProbeIds() { } bool Native::Ip::Sla::Group::Schedule::ProbeIds::has_data() const { if (is_presence_container) return true; return word.is_set || (schedule_period != nullptr && schedule_period->has_data()); } bool Native::Ip::Sla::Group::Schedule::ProbeIds::has_operation() const { return is_set(yfilter) || ydk::is_set(word.yfilter) || (schedule_period != nullptr && schedule_period->has_operation()); } std::string Native::Ip::Sla::Group::Schedule::ProbeIds::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "probe-ids"; ADD_KEY_TOKEN(word, "word"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Group::Schedule::ProbeIds::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (word.is_set || is_set(word.yfilter)) leaf_name_data.push_back(word.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Group::Schedule::ProbeIds::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "schedule-period") { if(schedule_period == nullptr) { schedule_period = std::make_shared<Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod>(); } return schedule_period; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Group::Schedule::ProbeIds::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(schedule_period != nullptr) { _children["schedule-period"] = schedule_period; } return _children; } void Native::Ip::Sla::Group::Schedule::ProbeIds::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "word") { word = value; word.value_namespace = name_space; word.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Group::Schedule::ProbeIds::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "word") { word.yfilter = yfilter; } } bool Native::Ip::Sla::Group::Schedule::ProbeIds::has_leaf_or_child_of_name(const std::string & name) const { if(name == "schedule-period" || name == "word") return true; return false; } Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::SchedulePeriod() : seconds{YType::uint32, "seconds"}, life{YType::str, "life"} , frequency(std::make_shared<Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency>()) , start_time(std::make_shared<Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime>()) { frequency->parent = this; start_time->parent = this; yang_name = "schedule-period"; yang_parent_name = "probe-ids"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::~SchedulePeriod() { } bool Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::has_data() const { if (is_presence_container) return true; return seconds.is_set || life.is_set || (frequency != nullptr && frequency->has_data()) || (start_time != nullptr && start_time->has_data()); } bool Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::has_operation() const { return is_set(yfilter) || ydk::is_set(seconds.yfilter) || ydk::is_set(life.yfilter) || (frequency != nullptr && frequency->has_operation()) || (start_time != nullptr && start_time->has_operation()); } std::string Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "schedule-period"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (seconds.is_set || is_set(seconds.yfilter)) leaf_name_data.push_back(seconds.get_name_leafdata()); if (life.is_set || is_set(life.yfilter)) leaf_name_data.push_back(life.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "frequency") { if(frequency == nullptr) { frequency = std::make_shared<Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency>(); } return frequency; } if(child_yang_name == "start-time") { if(start_time == nullptr) { start_time = std::make_shared<Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime>(); } return start_time; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(frequency != nullptr) { _children["frequency"] = frequency; } if(start_time != nullptr) { _children["start-time"] = start_time; } return _children; } void Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "seconds") { seconds = value; seconds.value_namespace = name_space; seconds.value_namespace_prefix = name_space_prefix; } if(value_path == "life") { life = value; life.value_namespace = name_space; life.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "seconds") { seconds.yfilter = yfilter; } if(value_path == "life") { life.yfilter = yfilter; } } bool Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::has_leaf_or_child_of_name(const std::string & name) const { if(name == "frequency" || name == "start-time" || name == "seconds" || name == "life") return true; return false; } Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency::Frequency() : frequency_val{YType::uint32, "frequency-val"}, range{YType::str, "range"} { yang_name = "frequency"; yang_parent_name = "schedule-period"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency::~Frequency() { } bool Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency::has_data() const { if (is_presence_container) return true; return frequency_val.is_set || range.is_set; } bool Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency::has_operation() const { return is_set(yfilter) || ydk::is_set(frequency_val.yfilter) || ydk::is_set(range.yfilter); } std::string Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "frequency"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (frequency_val.is_set || is_set(frequency_val.yfilter)) leaf_name_data.push_back(frequency_val.get_name_leafdata()); if (range.is_set || is_set(range.yfilter)) leaf_name_data.push_back(range.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "frequency-val") { frequency_val = value; frequency_val.value_namespace = name_space; frequency_val.value_namespace_prefix = name_space_prefix; } if(value_path == "range") { range = value; range.value_namespace = name_space; range.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "frequency-val") { frequency_val.yfilter = yfilter; } if(value_path == "range") { range.yfilter = yfilter; } } bool Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Frequency::has_leaf_or_child_of_name(const std::string & name) const { if(name == "frequency-val" || name == "range") return true; return false; } Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime::StartTime() : now{YType::empty, "now"} { yang_name = "start-time"; yang_parent_name = "schedule-period"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime::~StartTime() { } bool Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime::has_data() const { if (is_presence_container) return true; return now.is_set; } bool Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime::has_operation() const { return is_set(yfilter) || ydk::is_set(now.yfilter); } std::string Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "start-time"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (now.is_set || is_set(now.yfilter)) leaf_name_data.push_back(now.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "now") { now = value; now.value_namespace = name_space; now.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "now") { now.yfilter = yfilter; } } bool Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::StartTime::has_leaf_or_child_of_name(const std::string & name) const { if(name == "now") return true; return false; } Native::Ip::Sla::Schedule::Schedule() : entry_number{YType::str, "entry-number"}, ageout{YType::uint32, "ageout"}, life{YType::str, "life"}, recurring{YType::empty, "recurring"} , start_time(std::make_shared<Native::Ip::Sla::Schedule::StartTime>()) { start_time->parent = this; yang_name = "schedule"; yang_parent_name = "sla"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::Schedule::~Schedule() { } bool Native::Ip::Sla::Schedule::has_data() const { if (is_presence_container) return true; return entry_number.is_set || ageout.is_set || life.is_set || recurring.is_set || (start_time != nullptr && start_time->has_data()); } bool Native::Ip::Sla::Schedule::has_operation() const { return is_set(yfilter) || ydk::is_set(entry_number.yfilter) || ydk::is_set(ageout.yfilter) || ydk::is_set(life.yfilter) || ydk::is_set(recurring.yfilter) || (start_time != nullptr && start_time->has_operation()); } std::string Native::Ip::Sla::Schedule::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Schedule::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "schedule"; ADD_KEY_TOKEN(entry_number, "entry-number"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Schedule::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (entry_number.is_set || is_set(entry_number.yfilter)) leaf_name_data.push_back(entry_number.get_name_leafdata()); if (ageout.is_set || is_set(ageout.yfilter)) leaf_name_data.push_back(ageout.get_name_leafdata()); if (life.is_set || is_set(life.yfilter)) leaf_name_data.push_back(life.get_name_leafdata()); if (recurring.is_set || is_set(recurring.yfilter)) leaf_name_data.push_back(recurring.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Schedule::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "start-time") { if(start_time == nullptr) { start_time = std::make_shared<Native::Ip::Sla::Schedule::StartTime>(); } return start_time; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Schedule::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(start_time != nullptr) { _children["start-time"] = start_time; } return _children; } void Native::Ip::Sla::Schedule::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "entry-number") { entry_number = value; entry_number.value_namespace = name_space; entry_number.value_namespace_prefix = name_space_prefix; } if(value_path == "ageout") { ageout = value; ageout.value_namespace = name_space; ageout.value_namespace_prefix = name_space_prefix; } if(value_path == "life") { life = value; life.value_namespace = name_space; life.value_namespace_prefix = name_space_prefix; } if(value_path == "recurring") { recurring = value; recurring.value_namespace = name_space; recurring.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Schedule::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "entry-number") { entry_number.yfilter = yfilter; } if(value_path == "ageout") { ageout.yfilter = yfilter; } if(value_path == "life") { life.yfilter = yfilter; } if(value_path == "recurring") { recurring.yfilter = yfilter; } } bool Native::Ip::Sla::Schedule::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-time" || name == "entry-number" || name == "ageout" || name == "life" || name == "recurring") return true; return false; } Native::Ip::Sla::Schedule::StartTime::StartTime() : after{YType::str, "after"}, hour_min{YType::str, "hour-min"}, hour_min_sec{YType::str, "hour-min-sec"}, now{YType::empty, "now"}, pending{YType::empty, "pending"}, random{YType::uint32, "random"} { yang_name = "start-time"; yang_parent_name = "schedule"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::Schedule::StartTime::~StartTime() { } bool Native::Ip::Sla::Schedule::StartTime::has_data() const { if (is_presence_container) return true; return after.is_set || hour_min.is_set || hour_min_sec.is_set || now.is_set || pending.is_set || random.is_set; } bool Native::Ip::Sla::Schedule::StartTime::has_operation() const { return is_set(yfilter) || ydk::is_set(after.yfilter) || ydk::is_set(hour_min.yfilter) || ydk::is_set(hour_min_sec.yfilter) || ydk::is_set(now.yfilter) || ydk::is_set(pending.yfilter) || ydk::is_set(random.yfilter); } std::string Native::Ip::Sla::Schedule::StartTime::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "start-time"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Schedule::StartTime::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (after.is_set || is_set(after.yfilter)) leaf_name_data.push_back(after.get_name_leafdata()); if (hour_min.is_set || is_set(hour_min.yfilter)) leaf_name_data.push_back(hour_min.get_name_leafdata()); if (hour_min_sec.is_set || is_set(hour_min_sec.yfilter)) leaf_name_data.push_back(hour_min_sec.get_name_leafdata()); if (now.is_set || is_set(now.yfilter)) leaf_name_data.push_back(now.get_name_leafdata()); if (pending.is_set || is_set(pending.yfilter)) leaf_name_data.push_back(pending.get_name_leafdata()); if (random.is_set || is_set(random.yfilter)) leaf_name_data.push_back(random.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Schedule::StartTime::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Schedule::StartTime::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Schedule::StartTime::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "after") { after = value; after.value_namespace = name_space; after.value_namespace_prefix = name_space_prefix; } if(value_path == "hour-min") { hour_min = value; hour_min.value_namespace = name_space; hour_min.value_namespace_prefix = name_space_prefix; } if(value_path == "hour-min-sec") { hour_min_sec = value; hour_min_sec.value_namespace = name_space; hour_min_sec.value_namespace_prefix = name_space_prefix; } if(value_path == "now") { now = value; now.value_namespace = name_space; now.value_namespace_prefix = name_space_prefix; } if(value_path == "pending") { pending = value; pending.value_namespace = name_space; pending.value_namespace_prefix = name_space_prefix; } if(value_path == "random") { random = value; random.value_namespace = name_space; random.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::Schedule::StartTime::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "after") { after.yfilter = yfilter; } if(value_path == "hour-min") { hour_min.yfilter = yfilter; } if(value_path == "hour-min-sec") { hour_min_sec.yfilter = yfilter; } if(value_path == "now") { now.yfilter = yfilter; } if(value_path == "pending") { pending.yfilter = yfilter; } if(value_path == "random") { random.yfilter = yfilter; } } bool Native::Ip::Sla::Schedule::StartTime::has_leaf_or_child_of_name(const std::string & name) const { if(name == "after" || name == "hour-min" || name == "hour-min-sec" || name == "now" || name == "pending" || name == "random") return true; return false; } Native::Ip::Sla::ReactionConfiguration::ReactionConfiguration() : entry_number{YType::uint64, "entry-number"} , react(std::make_shared<Native::Ip::Sla::ReactionConfiguration::React>()) { react->parent = this; yang_name = "reaction-configuration"; yang_parent_name = "sla"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::ReactionConfiguration::~ReactionConfiguration() { } bool Native::Ip::Sla::ReactionConfiguration::has_data() const { if (is_presence_container) return true; return entry_number.is_set || (react != nullptr && react->has_data()); } bool Native::Ip::Sla::ReactionConfiguration::has_operation() const { return is_set(yfilter) || ydk::is_set(entry_number.yfilter) || (react != nullptr && react->has_operation()); } std::string Native::Ip::Sla::ReactionConfiguration::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::ReactionConfiguration::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "reaction-configuration"; ADD_KEY_TOKEN(entry_number, "entry-number"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::ReactionConfiguration::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (entry_number.is_set || is_set(entry_number.yfilter)) leaf_name_data.push_back(entry_number.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::ReactionConfiguration::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "react") { if(react == nullptr) { react = std::make_shared<Native::Ip::Sla::ReactionConfiguration::React>(); } return react; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::ReactionConfiguration::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(react != nullptr) { _children["react"] = react; } return _children; } void Native::Ip::Sla::ReactionConfiguration::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "entry-number") { entry_number = value; entry_number.value_namespace = name_space; entry_number.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::ReactionConfiguration::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "entry-number") { entry_number.yfilter = yfilter; } } bool Native::Ip::Sla::ReactionConfiguration::has_leaf_or_child_of_name(const std::string & name) const { if(name == "react" || name == "entry-number") return true; return false; } Native::Ip::Sla::ReactionConfiguration::React::React() : connectionloss(nullptr) // presence node , rtt(nullptr) // presence node { yang_name = "react"; yang_parent_name = "reaction-configuration"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::ReactionConfiguration::React::~React() { } bool Native::Ip::Sla::ReactionConfiguration::React::has_data() const { if (is_presence_container) return true; return (connectionloss != nullptr && connectionloss->has_data()) || (rtt != nullptr && rtt->has_data()); } bool Native::Ip::Sla::ReactionConfiguration::React::has_operation() const { return is_set(yfilter) || (connectionloss != nullptr && connectionloss->has_operation()) || (rtt != nullptr && rtt->has_operation()); } std::string Native::Ip::Sla::ReactionConfiguration::React::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "react"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::ReactionConfiguration::React::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::ReactionConfiguration::React::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "connectionLoss") { if(connectionloss == nullptr) { connectionloss = std::make_shared<Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss>(); } return connectionloss; } if(child_yang_name == "rtt") { if(rtt == nullptr) { rtt = std::make_shared<Native::Ip::Sla::ReactionConfiguration::React::Rtt>(); } return rtt; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::ReactionConfiguration::React::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(connectionloss != nullptr) { _children["connectionLoss"] = connectionloss; } if(rtt != nullptr) { _children["rtt"] = rtt; } return _children; } void Native::Ip::Sla::ReactionConfiguration::React::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Sla::ReactionConfiguration::React::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Sla::ReactionConfiguration::React::has_leaf_or_child_of_name(const std::string & name) const { if(name == "connectionLoss" || name == "rtt") return true; return false; } Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ConnectionLoss() : threshold_type(std::make_shared<Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType>()) { threshold_type->parent = this; yang_name = "connectionLoss"; yang_parent_name = "react"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::~ConnectionLoss() { } bool Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::has_data() const { if (is_presence_container) return true; return (threshold_type != nullptr && threshold_type->has_data()); } bool Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::has_operation() const { return is_set(yfilter) || (threshold_type != nullptr && threshold_type->has_operation()); } std::string Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "connectionLoss"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "threshold-type") { if(threshold_type == nullptr) { threshold_type = std::make_shared<Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType>(); } return threshold_type; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(threshold_type != nullptr) { _children["threshold-type"] = threshold_type; } return _children; } void Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::has_leaf_or_child_of_name(const std::string & name) const { if(name == "threshold-type") return true; return false; } Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::ThresholdType() : xofy(std::make_shared<Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy>()) { xofy->parent = this; yang_name = "threshold-type"; yang_parent_name = "connectionLoss"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::~ThresholdType() { } bool Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::has_data() const { if (is_presence_container) return true; return (xofy != nullptr && xofy->has_data()); } bool Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::has_operation() const { return is_set(yfilter) || (xofy != nullptr && xofy->has_operation()); } std::string Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "threshold-type"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "xOfy") { if(xofy == nullptr) { xofy = std::make_shared<Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy>(); } return xofy; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(xofy != nullptr) { _children["xOfy"] = xofy; } return _children; } void Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::has_leaf_or_child_of_name(const std::string & name) const { if(name == "xOfy") return true; return false; } Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::XOfy() : x_val{YType::uint8, "x-val"}, y_val{YType::uint8, "y-val"}, action_type{YType::enumeration, "action-type"} { yang_name = "xOfy"; yang_parent_name = "threshold-type"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::~XOfy() { } bool Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::has_data() const { if (is_presence_container) return true; return x_val.is_set || y_val.is_set || action_type.is_set; } bool Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::has_operation() const { return is_set(yfilter) || ydk::is_set(x_val.yfilter) || ydk::is_set(y_val.yfilter) || ydk::is_set(action_type.yfilter); } std::string Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "xOfy"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (x_val.is_set || is_set(x_val.yfilter)) leaf_name_data.push_back(x_val.get_name_leafdata()); if (y_val.is_set || is_set(y_val.yfilter)) leaf_name_data.push_back(y_val.get_name_leafdata()); if (action_type.is_set || is_set(action_type.yfilter)) leaf_name_data.push_back(action_type.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "x-val") { x_val = value; x_val.value_namespace = name_space; x_val.value_namespace_prefix = name_space_prefix; } if(value_path == "y-val") { y_val = value; y_val.value_namespace = name_space; y_val.value_namespace_prefix = name_space_prefix; } if(value_path == "action-type") { action_type = value; action_type.value_namespace = name_space; action_type.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "x-val") { x_val.yfilter = yfilter; } if(value_path == "y-val") { y_val.yfilter = yfilter; } if(value_path == "action-type") { action_type.yfilter = yfilter; } } bool Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::has_leaf_or_child_of_name(const std::string & name) const { if(name == "x-val" || name == "y-val" || name == "action-type") return true; return false; } Native::Ip::Sla::ReactionConfiguration::React::Rtt::Rtt() : threshold_value(std::make_shared<Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue>()) { threshold_value->parent = this; yang_name = "rtt"; yang_parent_name = "react"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Native::Ip::Sla::ReactionConfiguration::React::Rtt::~Rtt() { } bool Native::Ip::Sla::ReactionConfiguration::React::Rtt::has_data() const { if (is_presence_container) return true; return (threshold_value != nullptr && threshold_value->has_data()); } bool Native::Ip::Sla::ReactionConfiguration::React::Rtt::has_operation() const { return is_set(yfilter) || (threshold_value != nullptr && threshold_value->has_operation()); } std::string Native::Ip::Sla::ReactionConfiguration::React::Rtt::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "rtt"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::ReactionConfiguration::React::Rtt::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::ReactionConfiguration::React::Rtt::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "threshold-value") { if(threshold_value == nullptr) { threshold_value = std::make_shared<Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue>(); } return threshold_value; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::ReactionConfiguration::React::Rtt::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(threshold_value != nullptr) { _children["threshold-value"] = threshold_value; } return _children; } void Native::Ip::Sla::ReactionConfiguration::React::Rtt::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Sla::ReactionConfiguration::React::Rtt::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Sla::ReactionConfiguration::React::Rtt::has_leaf_or_child_of_name(const std::string & name) const { if(name == "threshold-value") return true; return false; } Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::ThresholdValue() : upper_limit_val{YType::uint32, "upper-limit-val"}, lower_limit_val{YType::uint32, "lower-limit-val"}, threshold_type{YType::enumeration, "threshold-type"}, action_type{YType::enumeration, "action-type"} { yang_name = "threshold-value"; yang_parent_name = "rtt"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::~ThresholdValue() { } bool Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::has_data() const { if (is_presence_container) return true; return upper_limit_val.is_set || lower_limit_val.is_set || threshold_type.is_set || action_type.is_set; } bool Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::has_operation() const { return is_set(yfilter) || ydk::is_set(upper_limit_val.yfilter) || ydk::is_set(lower_limit_val.yfilter) || ydk::is_set(threshold_type.yfilter) || ydk::is_set(action_type.yfilter); } std::string Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "threshold-value"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (upper_limit_val.is_set || is_set(upper_limit_val.yfilter)) leaf_name_data.push_back(upper_limit_val.get_name_leafdata()); if (lower_limit_val.is_set || is_set(lower_limit_val.yfilter)) leaf_name_data.push_back(lower_limit_val.get_name_leafdata()); if (threshold_type.is_set || is_set(threshold_type.yfilter)) leaf_name_data.push_back(threshold_type.get_name_leafdata()); if (action_type.is_set || is_set(action_type.yfilter)) leaf_name_data.push_back(action_type.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "upper-limit-val") { upper_limit_val = value; upper_limit_val.value_namespace = name_space; upper_limit_val.value_namespace_prefix = name_space_prefix; } if(value_path == "lower-limit-val") { lower_limit_val = value; lower_limit_val.value_namespace = name_space; lower_limit_val.value_namespace_prefix = name_space_prefix; } if(value_path == "threshold-type") { threshold_type = value; threshold_type.value_namespace = name_space; threshold_type.value_namespace_prefix = name_space_prefix; } if(value_path == "action-type") { action_type = value; action_type.value_namespace = name_space; action_type.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "upper-limit-val") { upper_limit_val.yfilter = yfilter; } if(value_path == "lower-limit-val") { lower_limit_val.yfilter = yfilter; } if(value_path == "threshold-type") { threshold_type.yfilter = yfilter; } if(value_path == "action-type") { action_type.yfilter = yfilter; } } bool Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::has_leaf_or_child_of_name(const std::string & name) const { if(name == "upper-limit-val" || name == "lower-limit-val" || name == "threshold-type" || name == "action-type") return true; return false; } Native::Ip::Sla::Server::Server() : twamp(nullptr) // presence node { yang_name = "server"; yang_parent_name = "sla"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Sla::Server::~Server() { } bool Native::Ip::Sla::Server::has_data() const { if (is_presence_container) return true; return (twamp != nullptr && twamp->has_data()); } bool Native::Ip::Sla::Server::has_operation() const { return is_set(yfilter) || (twamp != nullptr && twamp->has_operation()); } std::string Native::Ip::Sla::Server::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Server::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "server"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Server::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Server::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "twamp") { if(twamp == nullptr) { twamp = std::make_shared<Native::Ip::Sla::Server::Twamp>(); } return twamp; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Server::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(twamp != nullptr) { _children["twamp"] = twamp; } return _children; } void Native::Ip::Sla::Server::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Sla::Server::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Sla::Server::has_leaf_or_child_of_name(const std::string & name) const { if(name == "twamp") return true; return false; } Native::Ip::Sla::Server::Twamp::Twamp() { yang_name = "twamp"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } Native::Ip::Sla::Server::Twamp::~Twamp() { } bool Native::Ip::Sla::Server::Twamp::has_data() const { if (is_presence_container) return true; return false; } bool Native::Ip::Sla::Server::Twamp::has_operation() const { return is_set(yfilter); } std::string Native::Ip::Sla::Server::Twamp::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-sla:sla/server/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Sla::Server::Twamp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "twamp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Sla::Server::Twamp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Sla::Server::Twamp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Sla::Server::Twamp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Sla::Server::Twamp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Sla::Server::Twamp::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Sla::Server::Twamp::has_leaf_or_child_of_name(const std::string & name) const { return false; } Native::Ip::Rsvp::Rsvp() : authentication(nullptr) // presence node , signalling(std::make_shared<Native::Ip::Rsvp::Signalling>()) { signalling->parent = this; yang_name = "rsvp"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Rsvp::~Rsvp() { } bool Native::Ip::Rsvp::has_data() const { if (is_presence_container) return true; return (authentication != nullptr && authentication->has_data()) || (signalling != nullptr && signalling->has_data()); } bool Native::Ip::Rsvp::has_operation() const { return is_set(yfilter) || (authentication != nullptr && authentication->has_operation()) || (signalling != nullptr && signalling->has_operation()); } std::string Native::Ip::Rsvp::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Rsvp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-rsvp:rsvp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "authentication") { if(authentication == nullptr) { authentication = std::make_shared<Native::Ip::Rsvp::Authentication>(); } return authentication; } if(child_yang_name == "signalling") { if(signalling == nullptr) { signalling = std::make_shared<Native::Ip::Rsvp::Signalling>(); } return signalling; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(authentication != nullptr) { _children["authentication"] = authentication; } if(signalling != nullptr) { _children["signalling"] = signalling; } return _children; } void Native::Ip::Rsvp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Rsvp::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Rsvp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "authentication" || name == "signalling") return true; return false; } Native::Ip::Rsvp::Authentication::Authentication() : challenge{YType::empty, "challenge"}, key_chain{YType::str, "key-chain"}, type{YType::enumeration, "type"}, window_size{YType::uint8, "window-size"} , neighbor(std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor>()) , lifetime(std::make_shared<Native::Ip::Rsvp::Authentication::Lifetime>()) { neighbor->parent = this; lifetime->parent = this; yang_name = "authentication"; yang_parent_name = "rsvp"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } Native::Ip::Rsvp::Authentication::~Authentication() { } bool Native::Ip::Rsvp::Authentication::has_data() const { if (is_presence_container) return true; return challenge.is_set || key_chain.is_set || type.is_set || window_size.is_set || (neighbor != nullptr && neighbor->has_data()) || (lifetime != nullptr && lifetime->has_data()); } bool Native::Ip::Rsvp::Authentication::has_operation() const { return is_set(yfilter) || ydk::is_set(challenge.yfilter) || ydk::is_set(key_chain.yfilter) || ydk::is_set(type.yfilter) || ydk::is_set(window_size.yfilter) || (neighbor != nullptr && neighbor->has_operation()) || (lifetime != nullptr && lifetime->has_operation()); } std::string Native::Ip::Rsvp::Authentication::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-rsvp:rsvp/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Rsvp::Authentication::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "authentication"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Authentication::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (challenge.is_set || is_set(challenge.yfilter)) leaf_name_data.push_back(challenge.get_name_leafdata()); if (key_chain.is_set || is_set(key_chain.yfilter)) leaf_name_data.push_back(key_chain.get_name_leafdata()); if (type.is_set || is_set(type.yfilter)) leaf_name_data.push_back(type.get_name_leafdata()); if (window_size.is_set || is_set(window_size.yfilter)) leaf_name_data.push_back(window_size.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Authentication::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "neighbor") { if(neighbor == nullptr) { neighbor = std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor>(); } return neighbor; } if(child_yang_name == "lifetime") { if(lifetime == nullptr) { lifetime = std::make_shared<Native::Ip::Rsvp::Authentication::Lifetime>(); } return lifetime; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Authentication::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(neighbor != nullptr) { _children["neighbor"] = neighbor; } if(lifetime != nullptr) { _children["lifetime"] = lifetime; } return _children; } void Native::Ip::Rsvp::Authentication::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "challenge") { challenge = value; challenge.value_namespace = name_space; challenge.value_namespace_prefix = name_space_prefix; } if(value_path == "key-chain") { key_chain = value; key_chain.value_namespace = name_space; key_chain.value_namespace_prefix = name_space_prefix; } if(value_path == "type") { type = value; type.value_namespace = name_space; type.value_namespace_prefix = name_space_prefix; } if(value_path == "window-size") { window_size = value; window_size.value_namespace = name_space; window_size.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Rsvp::Authentication::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "challenge") { challenge.yfilter = yfilter; } if(value_path == "key-chain") { key_chain.yfilter = yfilter; } if(value_path == "type") { type.yfilter = yfilter; } if(value_path == "window-size") { window_size.yfilter = yfilter; } } bool Native::Ip::Rsvp::Authentication::has_leaf_or_child_of_name(const std::string & name) const { if(name == "neighbor" || name == "lifetime" || name == "challenge" || name == "key-chain" || name == "type" || name == "window-size") return true; return false; } Native::Ip::Rsvp::Authentication::Neighbor::Neighbor() : access_list(std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::AccessList>()) , address(std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::Address>()) { access_list->parent = this; address->parent = this; yang_name = "neighbor"; yang_parent_name = "authentication"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Rsvp::Authentication::Neighbor::~Neighbor() { } bool Native::Ip::Rsvp::Authentication::Neighbor::has_data() const { if (is_presence_container) return true; return (access_list != nullptr && access_list->has_data()) || (address != nullptr && address->has_data()); } bool Native::Ip::Rsvp::Authentication::Neighbor::has_operation() const { return is_set(yfilter) || (access_list != nullptr && access_list->has_operation()) || (address != nullptr && address->has_operation()); } std::string Native::Ip::Rsvp::Authentication::Neighbor::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-rsvp:rsvp/authentication/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Rsvp::Authentication::Neighbor::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "neighbor"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Authentication::Neighbor::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Authentication::Neighbor::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "access-list") { if(access_list == nullptr) { access_list = std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::AccessList>(); } return access_list; } if(child_yang_name == "address") { if(address == nullptr) { address = std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::Address>(); } return address; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Authentication::Neighbor::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(access_list != nullptr) { _children["access-list"] = access_list; } if(address != nullptr) { _children["address"] = address; } return _children; } void Native::Ip::Rsvp::Authentication::Neighbor::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Rsvp::Authentication::Neighbor::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Rsvp::Authentication::Neighbor::has_leaf_or_child_of_name(const std::string & name) const { if(name == "access-list" || name == "address") return true; return false; } Native::Ip::Rsvp::Authentication::Neighbor::AccessList::AccessList() : number(this, {"acl_number"}) , name(this, {"acl_name"}) { yang_name = "access-list"; yang_parent_name = "neighbor"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Rsvp::Authentication::Neighbor::AccessList::~AccessList() { } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<number.len(); index++) { if(number[index]->has_data()) return true; } for (std::size_t index=0; index<name.len(); index++) { if(name[index]->has_data()) return true; } return false; } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::has_operation() const { for (std::size_t index=0; index<number.len(); index++) { if(number[index]->has_operation()) return true; } for (std::size_t index=0; index<name.len(); index++) { if(name[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Rsvp::Authentication::Neighbor::AccessList::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-rsvp:rsvp/authentication/neighbor/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Rsvp::Authentication::Neighbor::AccessList::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "access-list"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Authentication::Neighbor::AccessList::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Authentication::Neighbor::AccessList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "number") { auto ent_ = std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number>(); ent_->parent = this; number.append(ent_); return ent_; } if(child_yang_name == "name") { auto ent_ = std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name>(); ent_->parent = this; name.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Authentication::Neighbor::AccessList::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : number.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } count_ = 0; for (auto ent_ : name.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Rsvp::Authentication::Neighbor::AccessList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Rsvp::Authentication::Neighbor::AccessList::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::has_leaf_or_child_of_name(const std::string & name) const { if(name == "number" || name == "name") return true; return false; } Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Number() : acl_number{YType::uint8, "acl-number"}, challenge{YType::empty, "challenge"}, key_chain{YType::str, "key-chain"}, type{YType::enumeration, "type"}, window_size{YType::uint8, "window-size"} , lifetime(std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime>()) { lifetime->parent = this; yang_name = "number"; yang_parent_name = "access-list"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::~Number() { } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::has_data() const { if (is_presence_container) return true; return acl_number.is_set || challenge.is_set || key_chain.is_set || type.is_set || window_size.is_set || (lifetime != nullptr && lifetime->has_data()); } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::has_operation() const { return is_set(yfilter) || ydk::is_set(acl_number.yfilter) || ydk::is_set(challenge.yfilter) || ydk::is_set(key_chain.yfilter) || ydk::is_set(type.yfilter) || ydk::is_set(window_size.yfilter) || (lifetime != nullptr && lifetime->has_operation()); } std::string Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-rsvp:rsvp/authentication/neighbor/access-list/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "number"; ADD_KEY_TOKEN(acl_number, "acl-number"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (acl_number.is_set || is_set(acl_number.yfilter)) leaf_name_data.push_back(acl_number.get_name_leafdata()); if (challenge.is_set || is_set(challenge.yfilter)) leaf_name_data.push_back(challenge.get_name_leafdata()); if (key_chain.is_set || is_set(key_chain.yfilter)) leaf_name_data.push_back(key_chain.get_name_leafdata()); if (type.is_set || is_set(type.yfilter)) leaf_name_data.push_back(type.get_name_leafdata()); if (window_size.is_set || is_set(window_size.yfilter)) leaf_name_data.push_back(window_size.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "lifetime") { if(lifetime == nullptr) { lifetime = std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime>(); } return lifetime; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(lifetime != nullptr) { _children["lifetime"] = lifetime; } return _children; } void Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "acl-number") { acl_number = value; acl_number.value_namespace = name_space; acl_number.value_namespace_prefix = name_space_prefix; } if(value_path == "challenge") { challenge = value; challenge.value_namespace = name_space; challenge.value_namespace_prefix = name_space_prefix; } if(value_path == "key-chain") { key_chain = value; key_chain.value_namespace = name_space; key_chain.value_namespace_prefix = name_space_prefix; } if(value_path == "type") { type = value; type.value_namespace = name_space; type.value_namespace_prefix = name_space_prefix; } if(value_path == "window-size") { window_size = value; window_size.value_namespace = name_space; window_size.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "acl-number") { acl_number.yfilter = yfilter; } if(value_path == "challenge") { challenge.yfilter = yfilter; } if(value_path == "key-chain") { key_chain.yfilter = yfilter; } if(value_path == "type") { type.yfilter = yfilter; } if(value_path == "window-size") { window_size.yfilter = yfilter; } } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::has_leaf_or_child_of_name(const std::string & name) const { if(name == "lifetime" || name == "acl-number" || name == "challenge" || name == "key-chain" || name == "type" || name == "window-size") return true; return false; } Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime::Lifetime() : hh_mm_ss{YType::str, "hh-mm-ss"} { yang_name = "lifetime"; yang_parent_name = "number"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime::~Lifetime() { } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime::has_data() const { if (is_presence_container) return true; return hh_mm_ss.is_set; } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime::has_operation() const { return is_set(yfilter) || ydk::is_set(hh_mm_ss.yfilter); } std::string Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lifetime"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (hh_mm_ss.is_set || is_set(hh_mm_ss.yfilter)) leaf_name_data.push_back(hh_mm_ss.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "hh-mm-ss") { hh_mm_ss = value; hh_mm_ss.value_namespace = name_space; hh_mm_ss.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "hh-mm-ss") { hh_mm_ss.yfilter = yfilter; } } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Lifetime::has_leaf_or_child_of_name(const std::string & name) const { if(name == "hh-mm-ss") return true; return false; } Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Name() : acl_name{YType::str, "acl-name"}, challenge{YType::empty, "challenge"}, key_chain{YType::str, "key-chain"}, type{YType::enumeration, "type"}, window_size{YType::uint8, "window-size"} , lifetime(std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime>()) { lifetime->parent = this; yang_name = "name"; yang_parent_name = "access-list"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::~Name() { } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::has_data() const { if (is_presence_container) return true; return acl_name.is_set || challenge.is_set || key_chain.is_set || type.is_set || window_size.is_set || (lifetime != nullptr && lifetime->has_data()); } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::has_operation() const { return is_set(yfilter) || ydk::is_set(acl_name.yfilter) || ydk::is_set(challenge.yfilter) || ydk::is_set(key_chain.yfilter) || ydk::is_set(type.yfilter) || ydk::is_set(window_size.yfilter) || (lifetime != nullptr && lifetime->has_operation()); } std::string Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-rsvp:rsvp/authentication/neighbor/access-list/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "name"; ADD_KEY_TOKEN(acl_name, "acl-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (acl_name.is_set || is_set(acl_name.yfilter)) leaf_name_data.push_back(acl_name.get_name_leafdata()); if (challenge.is_set || is_set(challenge.yfilter)) leaf_name_data.push_back(challenge.get_name_leafdata()); if (key_chain.is_set || is_set(key_chain.yfilter)) leaf_name_data.push_back(key_chain.get_name_leafdata()); if (type.is_set || is_set(type.yfilter)) leaf_name_data.push_back(type.get_name_leafdata()); if (window_size.is_set || is_set(window_size.yfilter)) leaf_name_data.push_back(window_size.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "lifetime") { if(lifetime == nullptr) { lifetime = std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime>(); } return lifetime; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(lifetime != nullptr) { _children["lifetime"] = lifetime; } return _children; } void Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "acl-name") { acl_name = value; acl_name.value_namespace = name_space; acl_name.value_namespace_prefix = name_space_prefix; } if(value_path == "challenge") { challenge = value; challenge.value_namespace = name_space; challenge.value_namespace_prefix = name_space_prefix; } if(value_path == "key-chain") { key_chain = value; key_chain.value_namespace = name_space; key_chain.value_namespace_prefix = name_space_prefix; } if(value_path == "type") { type = value; type.value_namespace = name_space; type.value_namespace_prefix = name_space_prefix; } if(value_path == "window-size") { window_size = value; window_size.value_namespace = name_space; window_size.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "acl-name") { acl_name.yfilter = yfilter; } if(value_path == "challenge") { challenge.yfilter = yfilter; } if(value_path == "key-chain") { key_chain.yfilter = yfilter; } if(value_path == "type") { type.yfilter = yfilter; } if(value_path == "window-size") { window_size.yfilter = yfilter; } } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::has_leaf_or_child_of_name(const std::string & name) const { if(name == "lifetime" || name == "acl-name" || name == "challenge" || name == "key-chain" || name == "type" || name == "window-size") return true; return false; } Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime::Lifetime() : hh_mm_ss{YType::str, "hh-mm-ss"} { yang_name = "lifetime"; yang_parent_name = "name"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime::~Lifetime() { } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime::has_data() const { if (is_presence_container) return true; return hh_mm_ss.is_set; } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime::has_operation() const { return is_set(yfilter) || ydk::is_set(hh_mm_ss.yfilter); } std::string Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lifetime"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (hh_mm_ss.is_set || is_set(hh_mm_ss.yfilter)) leaf_name_data.push_back(hh_mm_ss.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "hh-mm-ss") { hh_mm_ss = value; hh_mm_ss.value_namespace = name_space; hh_mm_ss.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "hh-mm-ss") { hh_mm_ss.yfilter = yfilter; } } bool Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Lifetime::has_leaf_or_child_of_name(const std::string & name) const { if(name == "hh-mm-ss") return true; return false; } Native::Ip::Rsvp::Authentication::Neighbor::Address::Address() : ipv4(this, {"ipv4_address"}) { yang_name = "address"; yang_parent_name = "neighbor"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Rsvp::Authentication::Neighbor::Address::~Address() { } bool Native::Ip::Rsvp::Authentication::Neighbor::Address::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipv4.len(); index++) { if(ipv4[index]->has_data()) return true; } return false; } bool Native::Ip::Rsvp::Authentication::Neighbor::Address::has_operation() const { for (std::size_t index=0; index<ipv4.len(); index++) { if(ipv4[index]->has_operation()) return true; } return is_set(yfilter); } std::string Native::Ip::Rsvp::Authentication::Neighbor::Address::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-rsvp:rsvp/authentication/neighbor/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Rsvp::Authentication::Neighbor::Address::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "address"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Authentication::Neighbor::Address::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Authentication::Neighbor::Address::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipv4") { auto ent_ = std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4>(); ent_->parent = this; ipv4.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Authentication::Neighbor::Address::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipv4.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Native::Ip::Rsvp::Authentication::Neighbor::Address::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Native::Ip::Rsvp::Authentication::Neighbor::Address::set_filter(const std::string & value_path, YFilter yfilter) { } bool Native::Ip::Rsvp::Authentication::Neighbor::Address::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv4") return true; return false; } Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Ipv4() : ipv4_address{YType::str, "ipv4-address"}, challenge{YType::empty, "challenge"}, key_chain{YType::str, "key-chain"}, type{YType::enumeration, "type"}, window_size{YType::uint8, "window-size"} , lifetime(std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime>()) { lifetime->parent = this; yang_name = "ipv4"; yang_parent_name = "address"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::~Ipv4() { } bool Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::has_data() const { if (is_presence_container) return true; return ipv4_address.is_set || challenge.is_set || key_chain.is_set || type.is_set || window_size.is_set || (lifetime != nullptr && lifetime->has_data()); } bool Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::has_operation() const { return is_set(yfilter) || ydk::is_set(ipv4_address.yfilter) || ydk::is_set(challenge.yfilter) || ydk::is_set(key_chain.yfilter) || ydk::is_set(type.yfilter) || ydk::is_set(window_size.yfilter) || (lifetime != nullptr && lifetime->has_operation()); } std::string Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-rsvp:rsvp/authentication/neighbor/address/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv4"; ADD_KEY_TOKEN(ipv4_address, "ipv4-address"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipv4_address.is_set || is_set(ipv4_address.yfilter)) leaf_name_data.push_back(ipv4_address.get_name_leafdata()); if (challenge.is_set || is_set(challenge.yfilter)) leaf_name_data.push_back(challenge.get_name_leafdata()); if (key_chain.is_set || is_set(key_chain.yfilter)) leaf_name_data.push_back(key_chain.get_name_leafdata()); if (type.is_set || is_set(type.yfilter)) leaf_name_data.push_back(type.get_name_leafdata()); if (window_size.is_set || is_set(window_size.yfilter)) leaf_name_data.push_back(window_size.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "lifetime") { if(lifetime == nullptr) { lifetime = std::make_shared<Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime>(); } return lifetime; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(lifetime != nullptr) { _children["lifetime"] = lifetime; } return _children; } void Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipv4-address") { ipv4_address = value; ipv4_address.value_namespace = name_space; ipv4_address.value_namespace_prefix = name_space_prefix; } if(value_path == "challenge") { challenge = value; challenge.value_namespace = name_space; challenge.value_namespace_prefix = name_space_prefix; } if(value_path == "key-chain") { key_chain = value; key_chain.value_namespace = name_space; key_chain.value_namespace_prefix = name_space_prefix; } if(value_path == "type") { type = value; type.value_namespace = name_space; type.value_namespace_prefix = name_space_prefix; } if(value_path == "window-size") { window_size = value; window_size.value_namespace = name_space; window_size.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipv4-address") { ipv4_address.yfilter = yfilter; } if(value_path == "challenge") { challenge.yfilter = yfilter; } if(value_path == "key-chain") { key_chain.yfilter = yfilter; } if(value_path == "type") { type.yfilter = yfilter; } if(value_path == "window-size") { window_size.yfilter = yfilter; } } bool Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::has_leaf_or_child_of_name(const std::string & name) const { if(name == "lifetime" || name == "ipv4-address" || name == "challenge" || name == "key-chain" || name == "type" || name == "window-size") return true; return false; } Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime::Lifetime() : hh_mm_ss{YType::str, "hh-mm-ss"} { yang_name = "lifetime"; yang_parent_name = "ipv4"; is_top_level_class = false; has_list_ancestor = true; } Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime::~Lifetime() { } bool Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime::has_data() const { if (is_presence_container) return true; return hh_mm_ss.is_set; } bool Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime::has_operation() const { return is_set(yfilter) || ydk::is_set(hh_mm_ss.yfilter); } std::string Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lifetime"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (hh_mm_ss.is_set || is_set(hh_mm_ss.yfilter)) leaf_name_data.push_back(hh_mm_ss.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "hh-mm-ss") { hh_mm_ss = value; hh_mm_ss.value_namespace = name_space; hh_mm_ss.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "hh-mm-ss") { hh_mm_ss.yfilter = yfilter; } } bool Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Lifetime::has_leaf_or_child_of_name(const std::string & name) const { if(name == "hh-mm-ss") return true; return false; } Native::Ip::Rsvp::Authentication::Lifetime::Lifetime() : hh_mm_ss{YType::str, "hh-mm-ss"} { yang_name = "lifetime"; yang_parent_name = "authentication"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Rsvp::Authentication::Lifetime::~Lifetime() { } bool Native::Ip::Rsvp::Authentication::Lifetime::has_data() const { if (is_presence_container) return true; return hh_mm_ss.is_set; } bool Native::Ip::Rsvp::Authentication::Lifetime::has_operation() const { return is_set(yfilter) || ydk::is_set(hh_mm_ss.yfilter); } std::string Native::Ip::Rsvp::Authentication::Lifetime::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-rsvp:rsvp/authentication/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Rsvp::Authentication::Lifetime::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lifetime"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Authentication::Lifetime::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (hh_mm_ss.is_set || is_set(hh_mm_ss.yfilter)) leaf_name_data.push_back(hh_mm_ss.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Authentication::Lifetime::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Authentication::Lifetime::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Rsvp::Authentication::Lifetime::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "hh-mm-ss") { hh_mm_ss = value; hh_mm_ss.value_namespace = name_space; hh_mm_ss.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Rsvp::Authentication::Lifetime::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "hh-mm-ss") { hh_mm_ss.yfilter = yfilter; } } bool Native::Ip::Rsvp::Authentication::Lifetime::has_leaf_or_child_of_name(const std::string & name) const { if(name == "hh-mm-ss") return true; return false; } Native::Ip::Rsvp::Signalling::Signalling() : initial_retransmit_delay{YType::uint16, "initial-retransmit-delay"} , fast_local_repair(std::make_shared<Native::Ip::Rsvp::Signalling::FastLocalRepair>()) , hello(nullptr) // presence node , patherr(std::make_shared<Native::Ip::Rsvp::Signalling::Patherr>()) , rate_limit(nullptr) // presence node , refresh(std::make_shared<Native::Ip::Rsvp::Signalling::Refresh>()) { fast_local_repair->parent = this; patherr->parent = this; refresh->parent = this; yang_name = "signalling"; yang_parent_name = "rsvp"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Rsvp::Signalling::~Signalling() { } bool Native::Ip::Rsvp::Signalling::has_data() const { if (is_presence_container) return true; return initial_retransmit_delay.is_set || (fast_local_repair != nullptr && fast_local_repair->has_data()) || (hello != nullptr && hello->has_data()) || (patherr != nullptr && patherr->has_data()) || (rate_limit != nullptr && rate_limit->has_data()) || (refresh != nullptr && refresh->has_data()); } bool Native::Ip::Rsvp::Signalling::has_operation() const { return is_set(yfilter) || ydk::is_set(initial_retransmit_delay.yfilter) || (fast_local_repair != nullptr && fast_local_repair->has_operation()) || (hello != nullptr && hello->has_operation()) || (patherr != nullptr && patherr->has_operation()) || (rate_limit != nullptr && rate_limit->has_operation()) || (refresh != nullptr && refresh->has_operation()); } std::string Native::Ip::Rsvp::Signalling::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-rsvp:rsvp/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Rsvp::Signalling::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "signalling"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Signalling::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (initial_retransmit_delay.is_set || is_set(initial_retransmit_delay.yfilter)) leaf_name_data.push_back(initial_retransmit_delay.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Signalling::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "fast-local-repair") { if(fast_local_repair == nullptr) { fast_local_repair = std::make_shared<Native::Ip::Rsvp::Signalling::FastLocalRepair>(); } return fast_local_repair; } if(child_yang_name == "hello") { if(hello == nullptr) { hello = std::make_shared<Native::Ip::Rsvp::Signalling::Hello>(); } return hello; } if(child_yang_name == "patherr") { if(patherr == nullptr) { patherr = std::make_shared<Native::Ip::Rsvp::Signalling::Patherr>(); } return patherr; } if(child_yang_name == "rate-limit") { if(rate_limit == nullptr) { rate_limit = std::make_shared<Native::Ip::Rsvp::Signalling::RateLimit>(); } return rate_limit; } if(child_yang_name == "refresh") { if(refresh == nullptr) { refresh = std::make_shared<Native::Ip::Rsvp::Signalling::Refresh>(); } return refresh; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Signalling::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(fast_local_repair != nullptr) { _children["fast-local-repair"] = fast_local_repair; } if(hello != nullptr) { _children["hello"] = hello; } if(patherr != nullptr) { _children["patherr"] = patherr; } if(rate_limit != nullptr) { _children["rate-limit"] = rate_limit; } if(refresh != nullptr) { _children["refresh"] = refresh; } return _children; } void Native::Ip::Rsvp::Signalling::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "initial-retransmit-delay") { initial_retransmit_delay = value; initial_retransmit_delay.value_namespace = name_space; initial_retransmit_delay.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Rsvp::Signalling::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "initial-retransmit-delay") { initial_retransmit_delay.yfilter = yfilter; } } bool Native::Ip::Rsvp::Signalling::has_leaf_or_child_of_name(const std::string & name) const { if(name == "fast-local-repair" || name == "hello" || name == "patherr" || name == "rate-limit" || name == "refresh" || name == "initial-retransmit-delay") return true; return false; } Native::Ip::Rsvp::Signalling::FastLocalRepair::FastLocalRepair() : notifications{YType::uint16, "notifications"}, rate{YType::uint16, "rate"} { yang_name = "fast-local-repair"; yang_parent_name = "signalling"; is_top_level_class = false; has_list_ancestor = false; } Native::Ip::Rsvp::Signalling::FastLocalRepair::~FastLocalRepair() { } bool Native::Ip::Rsvp::Signalling::FastLocalRepair::has_data() const { if (is_presence_container) return true; return notifications.is_set || rate.is_set; } bool Native::Ip::Rsvp::Signalling::FastLocalRepair::has_operation() const { return is_set(yfilter) || ydk::is_set(notifications.yfilter) || ydk::is_set(rate.yfilter); } std::string Native::Ip::Rsvp::Signalling::FastLocalRepair::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XE-native:native/ip/Cisco-IOS-XE-rsvp:rsvp/signalling/" << get_segment_path(); return path_buffer.str(); } std::string Native::Ip::Rsvp::Signalling::FastLocalRepair::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "fast-local-repair"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Native::Ip::Rsvp::Signalling::FastLocalRepair::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (notifications.is_set || is_set(notifications.yfilter)) leaf_name_data.push_back(notifications.get_name_leafdata()); if (rate.is_set || is_set(rate.yfilter)) leaf_name_data.push_back(rate.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Native::Ip::Rsvp::Signalling::FastLocalRepair::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Ip::Rsvp::Signalling::FastLocalRepair::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Native::Ip::Rsvp::Signalling::FastLocalRepair::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "notifications") { notifications = value; notifications.value_namespace = name_space; notifications.value_namespace_prefix = name_space_prefix; } if(value_path == "rate") { rate = value; rate.value_namespace = name_space; rate.value_namespace_prefix = name_space_prefix; } } void Native::Ip::Rsvp::Signalling::FastLocalRepair::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "notifications") { notifications.yfilter = yfilter; } if(value_path == "rate") { rate.yfilter = yfilter; } } bool Native::Ip::Rsvp::Signalling::FastLocalRepair::has_leaf_or_child_of_name(const std::string & name) const { if(name == "notifications" || name == "rate") return true; return false; } const Enum::YLeaf Native::Ip::Sla::Entry::IcmpEcho::History::Filter::all {0, "all"}; const Enum::YLeaf Native::Ip::Sla::Entry::IcmpEcho::History::Filter::failures {1, "failures"}; const Enum::YLeaf Native::Ip::Sla::Entry::IcmpEcho::History::Filter::none {2, "none"}; const Enum::YLeaf Native::Ip::Sla::Entry::IcmpEcho::History::Filter::overThreshold {3, "overThreshold"}; const Enum::YLeaf Native::Ip::Sla::Entry::UdpJitter::Codec::g711alaw {0, "g711alaw"}; const Enum::YLeaf Native::Ip::Sla::Entry::UdpJitter::Codec::g711ulaw {1, "g711ulaw"}; const Enum::YLeaf Native::Ip::Sla::Entry::UdpJitter::Codec::g729a {2, "g729a"}; const Enum::YLeaf Native::Ip::Sla::Entry::UdpJitter::Control::enable {0, "enable"}; const Enum::YLeaf Native::Ip::Sla::Entry::UdpJitter::Control::disable {1, "disable"}; const Enum::YLeaf Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Name::Y_1DM {0, "1DM"}; const Enum::YLeaf Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Name::DMM {1, "DMM"}; const Enum::YLeaf Native::Ip::Sla::Entry::Ethernet::Y1731::Delay::Name::DMMv1 {2, "DMMv1"}; const Enum::YLeaf Native::Ip::Sla::Group::Schedule::ProbeIds::SchedulePeriod::Life::forever {0, "forever"}; const Enum::YLeaf Native::Ip::Sla::Schedule::Life::forever {0, "forever"}; const Enum::YLeaf Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::ActionType::none {0, "none"}; const Enum::YLeaf Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::ActionType::trapAndTrigger {1, "trapAndTrigger"}; const Enum::YLeaf Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::ActionType::trapOnly {2, "trapOnly"}; const Enum::YLeaf Native::Ip::Sla::ReactionConfiguration::React::ConnectionLoss::ThresholdType::XOfy::ActionType::triggerOnly {3, "triggerOnly"}; const Enum::YLeaf Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::ThresholdType::immediate {0, "immediate"}; const Enum::YLeaf Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::ActionType::none {0, "none"}; const Enum::YLeaf Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::ActionType::trapAndTrigger {1, "trapAndTrigger"}; const Enum::YLeaf Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::ActionType::trapOnly {2, "trapOnly"}; const Enum::YLeaf Native::Ip::Sla::ReactionConfiguration::React::Rtt::ThresholdValue::ActionType::triggerOnly {3, "triggerOnly"}; const Enum::YLeaf Native::Ip::Rsvp::Authentication::Type::md5 {0, "md5"}; const Enum::YLeaf Native::Ip::Rsvp::Authentication::Type::sha_1 {1, "sha-1"}; const Enum::YLeaf Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Type::md5 {0, "md5"}; const Enum::YLeaf Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Number::Type::sha_1 {1, "sha-1"}; const Enum::YLeaf Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Type::md5 {0, "md5"}; const Enum::YLeaf Native::Ip::Rsvp::Authentication::Neighbor::AccessList::Name::Type::sha_1 {1, "sha-1"}; const Enum::YLeaf Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Type::md5 {0, "md5"}; const Enum::YLeaf Native::Ip::Rsvp::Authentication::Neighbor::Address::Ipv4::Type::sha_1 {1, "sha-1"}; } }
30.668774
487
0.664423
[ "vector" ]
bbfdf8d266732320da2bc8e6285bbf3e81e435a7
19,687
cpp
C++
src/imgui/im_tools.cpp
Sanceilaks/lemi_project_loader
e7461e8292911b7074322390677f276f5b3cc34b
[ "MIT" ]
null
null
null
src/imgui/im_tools.cpp
Sanceilaks/lemi_project_loader
e7461e8292911b7074322390677f276f5b3cc34b
[ "MIT" ]
1
2021-05-07T10:11:51.000Z
2021-05-07T10:11:51.000Z
src/imgui/im_tools.cpp
Sanceilaks/lemi_project_loader
e7461e8292911b7074322390677f276f5b3cc34b
[ "MIT" ]
1
2021-06-13T12:19:40.000Z
2021-06-13T12:19:40.000Z
#define IMGUI_DEFINE_MATH_OPERATORS #include "im_tools.h" #include <stack> #include "imgui_internal.h" #include <Windows.h> void ImGui::BorderPrevItem(const ImVec4& color) { GetWindowDrawList()->AddRect(GetItemRectMin(), GetItemRectMax(), GetColorU32(color)); } void ImGui::FullscreenNextWindow() { SetNextWindowPos({ 0, 0 }, ImGuiCond_Always); SetNextWindowSize(GetIO().DisplaySize, ImGuiCond_Always); } void ImGui::CenterNextElem(const size_t size) { const auto win_size = GetIO().DisplaySize; SetCursorPosX((win_size.x * 0.5f) - static_cast<float>(size) + GetStyle().WindowPadding.x); } void ImGui::BeginPadding(const ImVec2& val) { PushStyleVar(ImGuiStyleVar_WindowPadding, val); } void ImGui::EndPadding() { PopStyleVar(); } namespace center_padding_global { std::stack<ImVec2> last_items_size; } void ImGui::BeginCenterVerticalPadding() { if (center_padding_global::last_items_size.empty()) return; BeginPadding(center_padding_global::last_items_size.top()); } void ImGui::EndCenterVerticalPadding() { } bool ImGui::IsVectorValid(const ImVec4& val) { return val.x && val.y && val.z && val.w; } bool ImGui::ColoredButton(const char* text, const ImVec2& size, const CustomColor_t& color) { PushStyleColor(ImGuiCol_Button, color.color); PushStyleColor(ImGuiCol_ButtonActive, color.active); PushStyleColor(ImGuiCol_ButtonHovered, color.hovered); auto res = Button(text, size); PopStyleColor(); PopStyleColor(); PopStyleColor(); return res; } bool ImGui::TopBarButton(const char* label, const ImVec2& size, const CustomColor_t& color) { auto res = InvisibleButton(label, size); const auto rect_min = GetItemRectMin(); const auto rect_max = GetItemRectMax(); const auto rect_size = GetItemRectSize(); auto x_coordinates = ImVec2(rect_min.x + rect_size.x / 12, rect_max.x - rect_size.x / 12); //GetWindowDrawList()->AddLine({ x_coordinates.x, rect_min.y }, { x_coordinates.y, rect_min.y }, // GetColorU32(GetStyle().Colors[ImGuiCol_Separator])); //GetWindowDrawList()->AddLine({ x_coordinates.x, rect_max.y }, { x_coordinates.y, rect_max.y }, // GetColorU32(GetStyle().Colors[ImGuiCol_Separator])); auto text_size = CalcTextSize(label, 0, true); const auto end = FindRenderedTextEnd(label, 0); bool hovered = IsItemHovered(); if (hovered) PushStyleColor(ImGuiCol_Text, {0, 0.6f, 0.4f, 1}); RenderTextClipped( {rect_min.x + (rect_size.x / 2 - text_size.x / 2), rect_min.y + (rect_size.y / 2 - text_size.y / 2)}, { rect_min.x + (rect_size.x / 2 + text_size.x / 2), rect_min.y + (rect_size.y / 2 + text_size.y / 2) }, label, end, &text_size); if (hovered) PopStyleColor(); if (hovered) PushStyleColor(ImGuiCol_Separator, { 0, 0.6f, 0.4f, 1 }); auto y_padding = rect_size.y / 14; GetWindowDrawList()->AddLine({ rect_min.x + 2, rect_min.y + y_padding - 2 }, { rect_min.x + 2, rect_max.y - y_padding - 2 }, GetColorU32(GetStyle().Colors[ImGuiCol_Separator]), 4); GetWindowDrawList()->AddLine({ rect_max.x, rect_min.y + y_padding }, { rect_max.x, rect_max.y - y_padding }, GetColorU32(GetStyle().Colors[ImGuiCol_Separator]), 4); if (hovered) PopStyleColor(); return res; } ImVec4 ImGui::RGBAToClippedRGBA(const ImVec4& in) { return {in.x / 255.f, in.y / 255.f, in.z / 255.f, in.w / 255.f}; } void ImGui::RGBAToClippedRGBA(const ImVec4& in, ImVec4* out) { *out = RGBAToClippedRGBA(in); } void ImGui::RGBAToClippedRGBA(const ImVec4& in, ImVec4& out) { RGBAToClippedRGBA(in, out); } std::stack<ImVec2> spacings; void ImGui::BeginTempItemSpacing(const ImVec2& spacing) { spacings.push(GetStyle().ItemSpacing); GetStyle().ItemSpacing = spacing; } void ImGui::EndTempItemSpacing() { GetStyle().ItemSpacing = spacings.top(); spacings.pop(); } bool ImGui::IsVectorValid(const ImVec2& val) { return val.x && val.y; } std::stack<ImVec2> titled_children_sizes; bool ImGui::BeginTitledChild(const char* label, const ImVec2& size) { //auto result = BeginChild(label, size, true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_AlwaysAutoResize); BeginGroup(); auto title_bar_height = GetTextLineHeight() * 1.5f; BeginTempItemSpacing({0, 0}); //SetCursorPos({ 0, 0 }); Dummy({ size.x, title_bar_height }); EndTempItemSpacing(); const auto rect_min = GetItemRectMin(); const auto rect_max = GetItemRectMax(); const auto rect_size = GetItemRectSize(); auto text_size = CalcTextSize(label, 0, true); const auto end = FindRenderedTextEnd(label, 0); const auto text_rect_min = ImVec2{ rect_min.x + (rect_size.x / 2 - text_size.x / 2), rect_min.y + (rect_size.y / 2 - text_size.y / 2) }; const auto text_rect_max = ImVec2{ rect_min.x + (rect_size.x / 2 + text_size.x / 2), rect_min.y + (rect_size.y / 2 + text_size.y / 2) }; RenderTextClipped(text_rect_min, text_rect_max, label, end, &text_size); GetWindowDrawList()->AddLine({ rect_min.x, rect_max.y }, rect_max, GetColorU32(GetStyleColorVec4(ImGuiCol_Separator))); Dummy({size.x, GetStyle().ItemSpacing.y}); SameLine(); Dummy({ size.x, GetStyle().ItemSpacing.y }); return true; } void ImGui::EndTitledChild() { EndGroup(); BorderPrevItem(GetStyleColorVec4(ImGuiCol_Border)); //EndChild(); } float ImGui::GetTitleBarHeight() { return GetTextLineHeight() + GetStyle().FramePadding.y * 2.0f; } std::stack<ImU32> begin_groups_colors_stack; void ImGui::BeginGroupPanel(const char* name, const ImVec2& size, ImU32 color/*, ImU32 text_bg_color*/) { if (color == 0) color = GetColorU32(GetStyleColorVec4(ImGuiCol_ChildBg)); begin_groups_colors_stack.push(color); //GetWindowDrawList()->ChannelsSplit(2); //GetWindowDrawList()->ChannelsSetCurrent(1); BeginGroup(); const auto cursor_pos = GetCursorScreenPos(); const auto item_spacing = GetStyle().ItemSpacing; PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f)); PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); const auto frame_height = GetFrameHeight(); BeginGroup(); auto effective_size = size; if (size.x < 0.0f) effective_size.x = GetContentRegionAvailWidth(); else effective_size.x = size.x; Dummy(ImVec2(effective_size.x, 0.0f)); Dummy(ImVec2(frame_height * 0.5f, 0.0f)); SameLine(0.0f, 0.0f); BeginGroup(); Dummy(ImVec2(frame_height * 0.5f, 0.0f)); const auto text_size = CalcTextSize(name, 0, true); //GetWindowDrawList()->AddRectFilled(cursor_pos, ImVec2(cursor_pos.x + effective_size.x, cursor_pos.y + text_size.y), text_bg_color.); SetCursorPos(ImVec2( GetCursorPos().x + ((effective_size.x - frame_height) / 2 - text_size.x / 2) /*- GetStyle().ItemSpacing.x*/, GetCursorPos().y)); TextUnformatted(name, FindRenderedTextEnd(name)); //RenderText(ImVec2(GetCursorPos().x + effective_size.x / 2 - text_size.x / 2, GetCursorPos().y), name); SameLine(0.0f, 0.0f); Dummy(ImVec2(0.0, frame_height + item_spacing.y)); BeginGroup(); PopStyleVar(2); GetCurrentWindow()->ContentRegionRect.Max.x -= frame_height * 0.5f; GetCurrentWindow()->Size.x -= frame_height; PushItemWidth(effective_size.x - frame_height); } void ImGui::EndGroupPanel() { PopItemWidth(); const auto item_spacing = GetStyle().ItemSpacing; PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f)); PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); const auto frame_height = GetFrameHeight(); EndGroup(); //ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(0, 255, 0, 64), 4.0f); EndGroup(); SameLine(0.0f, 0.0f); Dummy(ImVec2(frame_height * 0.5f, 0.0f)); Dummy(ImVec2(0.0, frame_height - frame_height * 0.5f - item_spacing.y)); EndGroup(); const auto item_min = GetItemRectMin(); const auto item_max = GetItemRectMax(); PopStyleVar(2); GetCurrentWindow()->ContentRegionRect.Max.x += frame_height * 0.5f; GetCurrentWindow()->Size.x += frame_height; Dummy(ImVec2(0.0f, 0.0f)); EndGroup(); //GetWindowDrawList()->ChannelsSetCurrent(0); GetWindowDrawList()->AddRect(item_min, item_max, GetColorU32(GetStyleColorVec4(ImGuiCol_Border))); //GetWindowDrawList()->ChannelsMerge(); begin_groups_colors_stack.pop(); } void ImGui::ToggleButton(const char* str_id, bool* v, const ImVec2& size) { const auto p = GetCursorScreenPos(); //p += ImVec2(10, 10); auto draw_list = GetWindowDrawList(); auto style = GetStyle(); const auto calc_size = CalcItemSize(size, style.FramePadding.x * 2.0f, GetTextLineHeight() + style.FramePadding.y * 2.0f); InvisibleButton(str_id, calc_size); if (IsItemClicked()) *v = !*v; const auto radius = GetItemRectSize().y * 0.5f; const auto width = GetItemRectSize().x; const auto height = GetItemRectSize().y; auto t = *v ? 1.0f : 0.0f; auto& g = *GImGui; if (g.LastActiveId == g.CurrentWindow->GetID(str_id))// && g.LastActiveIdTimer < ANIM_SPEED) { const auto t_anim = ImSaturate(g.LastActiveIdTimer / /*ANIM_SPEED*/ 0.2); t = *v ? (t_anim) : (1.0f - t_anim); } const auto col_bg = GetColorU32(ImGuiCol_ChildBg); ImU32 slider_color; if (*v) slider_color = GetColorU32(ImGuiCol_ButtonActive); else slider_color = GetColorU32(ImGuiCol_Button); draw_list->AddRect(p, ImVec2(p.x + width, p.y + height), GetColorU32(ImGuiCol_Border), height * 0.5f); draw_list->AddCircleFilled(ImVec2(p.x + radius + t * (width - radius * 2.0f), p.y + radius), radius - 1.5f, slider_color); } constexpr const char* const key_names[] = { "Unknown", "Left Button", "Right Button", "Cancel", "Middle Button", "MButton 1", "MButton 2", "Unknown", "Back", "Tab", "Unknown", "Unknown", "Clear", "Return", "Unknown", "Unknown", "Shift", "Control", "Menu", "Pause", "Capital", "Kana", "Unknown", "Junja", "Final", "Kanji", "Unknown", "Escape", "Convert", "Nonconvert", "Accept", "Modechange", "Space", "Prior", "Next", "End", "Home", "Left", "Up", "Right", "Down", "Select", "Print", "Execute", "Snapshot", "Insert", "Delete", "Help", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "LWIN", "RWIN", "APPS", "Unknown", "Sleep", "NUMPAD0", "NUMPAD1", "NUMPAD2", "NUMPAD3", "NUMPAD4", "NUMPAD5", "NUMPAD6", "NUMPAD7", "NUMPAD8", "NUMPAD9", "MULTIPLY", "ADD", "SEPARATOR", "SUBTRACT", "DECIMAL", "DIVIDE", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "NUMLOCK", "SCROLL", "OEM_NEC_EQUAL", "OEM_FJ_MASSHOU", "OEM_FJ_TOUROKU", "OEM_FJ_LOYA", "OEM_FJ_ROYA", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "LShift", "RShift", "LControl", "RControl", "LALT", "RALT" }; bool ImGui::Hotkey(const char* label, uint32_t* k, const ImVec2& size_arg, uint32_t none_key, const char* none_str) { ImGuiWindow* window = ImGui::GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); ImVec2 size = ImGui::CalcItemSize(size_arg, ImGui::CalcItemWidth(), label_size.y + style.FramePadding.y * 2.0f); const ImRect frame_bb(window->DC.CursorPos + ImVec2(label_size.x + style.ItemInnerSpacing.x, 0.0f), window->DC.CursorPos + size); const ImRect total_bb(window->DC.CursorPos, frame_bb.Max); ImGui::ItemSize(total_bb, style.FramePadding.y); if (!ImGui::ItemAdd(total_bb, id)) return false; const bool focus_requested = ImGui::FocusableItemRegister(window, id); const bool hovered = ImGui::ItemHoverable(frame_bb, id); if (hovered) { ImGui::SetHoveredID(id); g.MouseCursor = ImGuiMouseCursor_TextInput; } const bool user_clicked = hovered && io.MouseClicked[0]; if (focus_requested || user_clicked) { if (g.ActiveId != id) { // Start edition memset(io.MouseDown, 0, sizeof(io.MouseDown)); memset(io.KeysDown, 0, sizeof(io.KeysDown)); *k = 0; } ImGui::SetActiveID(id, window); ImGui::FocusWindow(window); } else if (io.MouseClicked[0]) { // Release focus when we click outside if (g.ActiveId == id) ImGui::ClearActiveID(); } bool value_changed = false; int key = *k; if (g.ActiveId == id) { for (auto i = 0; i < 5; i++) { if (io.MouseDown[i]) { switch (i) { case 0: key = VK_LBUTTON; break; case 1: key = VK_RBUTTON; break; case 2: key = VK_MBUTTON; break; case 3: key = VK_XBUTTON1; break; case 4: key = VK_XBUTTON2; break; } value_changed = true; ImGui::ClearActiveID(); } } if (!value_changed) { for (auto i = VK_BACK; i <= VK_RMENU; i++) { if (io.KeysDown[i]) { key = i; value_changed = true; ImGui::ClearActiveID(); } } } if (IsKeyPressedMap(ImGuiKey_Escape)) { *k = none_key; ImGui::ClearActiveID(); } else { *k = key; } } // Render // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is Set 'buf' might still be the old value. We Set buf to NULL to prevent accidental usage from now on. char buf_display[64] = "None"; strcpy_s(buf_display, none_str); ImGui::RenderFrame(frame_bb.Min, frame_bb.Max, /*ImGui::GetColorU32(ImVec4(0.20f, 0.25f, 0.30f, 1.0f)*/ ImGui::GetColorU32(ImGuiCol_Button), true, style.FrameRounding); if (*k != 0 && g.ActiveId != id) { strcpy_s(buf_display, key_names[*k]); } else if (g.ActiveId == id) { strcpy_s(buf_display, "<Press a key>"); } const ImRect clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size ImVec2 render_pos = frame_bb.Min + style.FramePadding; ImGui::RenderTextClipped(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding, buf_display, NULL, NULL, style.ButtonTextAlign, &clip_rect); //RenderTextClipped(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding, buf_display, NULL, NULL, GetColorU32(ImGuiCol_Text), style.ButtonTextAlign, &clip_rect); //draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, NULL, 0.0f, &clip_rect); if (label_size.x > 0) ImGui::RenderText(ImVec2(total_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), label); return value_changed; } ImVector<float> fonts_sizes; ImVector<ImFont*> fonts_ptr; void ImGui::PushFontSize(ImFont* font, float size) { font->FontSize = size; fonts_sizes.push_back(size); fonts_ptr.push_back(font); } void ImGui::PopFontSize(int size) { fonts_ptr.back()->FontSize = fonts_sizes.back(); fonts_ptr.pop_back(); fonts_sizes.pop_back(); } bool ImGui::CenterButton(const char* label, const ImVec2& size_arg) { auto label_size = CalcTextSize(label, 0, true); auto style = GetStyle(); ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); SetCursorPosX(GetWindowSize().x / 2.f - size.x / 2); return Button(label, size_arg); } bool ImGui::Spinner(const char* label, float radius, int thickness, const ImU32& color_) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); auto color = color_; if (!color) color = GetColorU32(style.Colors[ImGuiCol_Text]); ImVec2 pos = window->DC.CursorPos; ImVec2 size((radius) * 2, (radius + style.FramePadding.y) * 2); const ImRect bb(pos, ImVec2(pos.x + size.x, pos.y + size.y)); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, id)) return false; // Render window->DrawList->PathClear(); int num_segments = 30; int start = abs(ImSin(g.Time * 0.4f) * (num_segments - 5)); const float a_min = IM_PI * 2.0f * ((float)start) / (float)num_segments; const float a_max = IM_PI * 2.0f * ((float)num_segments - 3) / (float)num_segments; const ImVec2 centre = ImVec2(pos.x + radius, pos.y + radius + style.FramePadding.y); for (int i = 0; i < num_segments; i++) { const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min); window->DrawList->PathLineTo(ImVec2(centre.x + ImCos(a + g.Time * 8) * radius, centre.y + ImSin(a + g.Time * 8) * radius)); } window->DrawList->PathStroke(color, false, thickness); } #undef max void ImGui::LoadingIndicatorCircle(const char* label, const float indicator_radius, const ImVec4& main_color, const ImVec4& backdrop_color, const int circle_count, const float speed) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) { return; } ImGuiContext& g = *GImGui; const ImGuiID id = window->GetID(label); auto style = GetStyle(); const ImVec2 pos = window->DC.CursorPos; const float circle_radius = indicator_radius / 10.0f; const ImRect bb(pos, ImVec2(pos.x + indicator_radius * 2.0f, pos.y + indicator_radius * 2.0f)); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, id)) { return; } const float t = g.Time; const auto degree_offset = 2.0f * IM_PI / circle_count; for (int i = 0; i < circle_count; ++i) { const auto x = indicator_radius * std::sin(degree_offset * i); const auto y = indicator_radius * std::cos(degree_offset * i); const auto growth = std::max(0.0f, std::sin(t * speed - i * degree_offset)); ImVec4 color; color.x = main_color.x * growth + backdrop_color.x * (1.0f - growth); color.y = main_color.y * growth + backdrop_color.y * (1.0f - growth); color.z = main_color.z * growth + backdrop_color.z * (1.0f - growth); color.w = 1.0f; window->DrawList->AddCircleFilled(ImVec2(pos.x + indicator_radius + x, pos.y + indicator_radius - y), circle_radius + growth * circle_radius, GetColorU32(color)); } } bool ImGui::BufferingBar(const char* label, float value, const ImVec2& size_arg, const ImU32& bg_col, const ImU32& fg_col) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); ImVec2 pos = window->DC.CursorPos; ImVec2 size = size_arg; size.x -= style.FramePadding.x * 2; const ImRect bb(pos, ImVec2(pos.x + size.x, pos.y + size.y)); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, id)) return false; // Render const float circleStart = size.x * 0.7f; const float circleEnd = size.x; const float circleWidth = circleEnd - circleStart; window->DrawList->AddRectFilled(bb.Min, ImVec2(pos.x + circleStart, bb.Max.y), bg_col); window->DrawList->AddRectFilled(bb.Min, ImVec2(pos.x + circleStart * value, bb.Max.y), fg_col); const float t = g.Time; const float r = size.y / 2; const float speed = 1.5f; const float a = speed * 0; const float b = speed * 0.333f; const float c = speed * 0.666f; const float o1 = (circleWidth + r) * (t + a - speed * (int)((t + a) / speed)) / speed; const float o2 = (circleWidth + r) * (t + b - speed * (int)((t + b) / speed)) / speed; const float o3 = (circleWidth + r) * (t + c - speed * (int)((t + c) / speed)) / speed; window->DrawList->AddCircleFilled(ImVec2(pos.x + circleEnd - o1, bb.Min.y + r), r, bg_col); window->DrawList->AddCircleFilled(ImVec2(pos.x + circleEnd - o2, bb.Min.y + r), r, bg_col); window->DrawList->AddCircleFilled(ImVec2(pos.x + circleEnd - o3, bb.Min.y + r), r, bg_col); }
25.175192
187
0.684208
[ "render" ]
0101e44cb40a624a06b47e26413ce81a58a0cdf2
762
hpp
C++
EnjoyEngine/EnjoyEngine/ECSSystem.hpp
Jar0T/EnjoyEngine_dll
41e242a35e886a103e44f82d65586f19e0f4f81e
[ "MIT" ]
1
2020-11-01T17:18:59.000Z
2020-11-01T17:18:59.000Z
EnjoyEngine/EnjoyEngine/ECSSystem.hpp
Jar0T/EnjoyEngine_dll
41e242a35e886a103e44f82d65586f19e0f4f81e
[ "MIT" ]
21
2020-06-26T21:54:14.000Z
2020-10-20T10:50:10.000Z
EnjoyEngine/EnjoyEngine/ECSSystem.hpp
Jar0T/EnjoyEngine_dll
41e242a35e886a103e44f82d65586f19e0f4f81e
[ "MIT" ]
null
null
null
#pragma once #include "ECSComponent.hpp" #include "Time.hpp" #ifdef ENJOYENGINE_EXPORTS #define ENJOYENGINE_API __declspec(dllexport) #else #define ENJOYENGINE_API __declspec(dllimport) #endif namespace EE { class ENJOYENGINE_API BaseECSSystem { public: enum class Flags : uint32_t { NO_FLAG, OPTIONAL_COMPONENT }; private: std::vector<std::uint32_t> _componentTypes; std::vector<std::uint32_t> _componetnFlags; protected: void addComponentType(uint32_t componetnType, Flags componentFlag = Flags::NO_FLAG); public: BaseECSSystem(); virtual void updateComponents(BaseECSComponent** components); const std::vector<std::uint32_t>& getComponentTypes(); const std::vector<uint32_t>& getComponentFlags(); bool isValid(); }; }
20.052632
86
0.757218
[ "vector" ]
010462c1f50ca34659d7a9f693b3de4833980ceb
92,394
hxx
C++
main/filter/inc/filter/msfilter/escherex.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/filter/inc/filter/msfilter/escherex.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/filter/inc/filter/msfilter/escherex.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * 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. * *************************************************************/ #ifndef _SVX_ESCHEREX_HXX #define _SVX_ESCHEREX_HXX #include <memory> #include <vector> #include <boost/shared_ptr.hpp> #include <tools/solar.h> #include <tools/gen.hxx> #include <tools/list.hxx> #include <tools/stream.hxx> #include <com/sun/star/uno/Reference.h> #include <svtools/grfmgr.hxx> #include <com/sun/star/awt/Size.hpp> #include <com/sun/star/awt/Point.hpp> #include <com/sun/star/awt/Rectangle.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/PropertyState.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/drawing/BitmapMode.hpp> #include <com/sun/star/drawing/EnhancedCustomShapeParameterPair.hpp> #include <com/sun/star/drawing/Hatch.hpp> #include <svx/msdffdef.hxx> #include "filter/msfilter/msfilterdllapi.h" /*Record Name FBT-Value Instance Contents Wrd Exl PPt Ver*/ // In der Mickysoft-Doku heissen die msofbt... statt ESCHER_... #define ESCHER_DggContainer 0xF000 /* per-document data X X X */ #define ESCHER_Dgg 0xF006 /* an FDGG and several FIDCLs X X X 0 */ #define ESCHER_CLSID 0xF016 /* the CLSID of the application that put the data on the clipboard C C C 0 */ #define ESCHER_OPT 0xF00B /* count of properties the document-wide default shape properties X X X 3 */ #define ESCHER_ColorMRU 0xF11A /* count of colors the colors in the MRU swatch X X X 0 */ #define ESCHER_SplitMenuColors 0xF11E /* count of colors the colors in the top-level split menus X X X 0 */ #define ESCHER_BstoreContainer 0xF001 /* count of BLIPs all images in the document (JPEGs, metafiles, etc.) X X X */ #define ESCHER_BSE 0xF007 /* BLIP type an FBSE (one per BLIP) X X X 2 */ #define ESCHER_BlipFirst 0xF018 /* range of fbts reserved for various kinds of BLIPs X X X */ #define ESCHER_BlipLast 0xF117 /* range of fbts reserved for various kinds of BLIPs X X X */ #define ESCHER_DgContainer 0xF002 /* per-sheet/page/slide data X X X */ #define ESCHER_Dg 0xF008 /* drawing ID an FDG X X X 0 */ #define ESCHER_RegroupItems 0xF118 /* count of regroup entries several FRITs X X X 0 */ #define ESCHER_ColorScheme 0xF120 /* count of colors the colors of the source host's color scheme C C 0 */ #define ESCHER_SpgrContainer 0xF003 /* several SpContainers, the first of which is the group shape itself X X X */ #define ESCHER_SpContainer 0xF004 /* a shape X X X */ #define ESCHER_Spgr 0xF009 /* an FSPGR; only present if the shape is a group shape X X X 1 */ #define ESCHER_Sp 0xF00A /* shape type an FSP X X X 2 */ //#define ESCHER_OPT 0xF00B /* count of properties a shape property table X X X 3 */ #define ESCHER_Textbox 0xF00C /* RTF text C C C 0 */ #define ESCHER_ClientTextbox 0xF00D /* host-defined the text in the textbox, in host-defined format X X X */ #define ESCHER_Anchor 0xF00E /* a RECT, in 100000ths of an inch C C C 0 */ #define ESCHER_ChildAnchor 0xF00F /* a RECT, in units relative to the parent group X X X 0 */ #define ESCHER_ClientAnchor 0xF010 /* host-defined the location of the shape, in a host-defined format X X X */ #define ESCHER_ClientData 0xF011 /* host-defined host-specific data X X X */ #define ESCHER_OleObject 0xF11F /* a serialized IStorage for an OLE object C C C 0 */ #define ESCHER_DeletedPspl 0xF11D /* an FPSPL; only present in top-level deleted shapes X 0 */ #define ESCHER_SolverContainer 0xF005 /* count of rules the rules governing shapes X X X */ #define ESCHER_ConnectorRule 0xF012 /* an FConnectorRule X X 1 */ #define ESCHER_AlignRule 0xF013 /* an FAlignRule X X X 0 */ #define ESCHER_ArcRule 0xF014 /* an FARCRU X X X 0 */ #define ESCHER_ClientRule 0xF015 /* host-defined host-defined */ #define ESCHER_CalloutRule 0xF017 /* an FCORU X X X 0 */ #define ESCHER_Selection 0xF119 /* an FDGSL followed by the SPIDs of the shapes in the selection X 0 */ #define ESCHER_UDefProp 0xF122 #define SHAPEFLAG_GROUP 0x001 // This shape is a group shape #define SHAPEFLAG_CHILD 0x002 // Not a top-level shape #define SHAPEFLAG_PATRIARCH 0x004 // This is the topmost group shape. Exactly one of these per drawing. #define SHAPEFLAG_DELETED 0x008 // The shape has been deleted #define SHAPEFLAG_OLESHAPE 0x010 // The shape is an OLE object #define SHAPEFLAG_HAVEMASTER 0x020 // Shape has a hspMaster property #define SHAPEFLAG_FLIPH 0x040 // Shape is flipped horizontally #define SHAPEFLAG_FLIPV 0x080 // Shape is flipped vertically #define SHAPEFLAG_CONNECTOR 0x100 // Connector type of shape #define SHAPEFLAG_HAVEANCHOR 0x200 // Shape has an anchor of some kind #define SHAPEFLAG_BACKGROUND 0x400 // Background shape #define SHAPEFLAG_HAVESPT 0x800 // Shape has a shape type property #define ESCHER_ShpInst_Min 0 #define ESCHER_ShpInst_NotPrimitive ESCHER_ShpInst_Min #define ESCHER_ShpInst_Rectangle 1 #define ESCHER_ShpInst_RoundRectangle 2 #define ESCHER_ShpInst_Ellipse 3 #define ESCHER_ShpInst_Diamond 4 #define ESCHER_ShpInst_IsocelesTriangle 5 #define ESCHER_ShpInst_RightTriangle 6 #define ESCHER_ShpInst_Parallelogram 7 #define ESCHER_ShpInst_Trapezoid 8 #define ESCHER_ShpInst_Hexagon 9 #define ESCHER_ShpInst_Octagon 10 #define ESCHER_ShpInst_Plus 11 #define ESCHER_ShpInst_Star 12 #define ESCHER_ShpInst_Arrow 13 #define ESCHER_ShpInst_ThickArrow 14 #define ESCHER_ShpInst_HomePlate 15 #define ESCHER_ShpInst_Cube 16 #define ESCHER_ShpInst_Balloon 17 #define ESCHER_ShpInst_Seal 18 #define ESCHER_ShpInst_Arc 19 #define ESCHER_ShpInst_Line 20 #define ESCHER_ShpInst_Plaque 21 #define ESCHER_ShpInst_Can 22 #define ESCHER_ShpInst_Donut 23 #define ESCHER_ShpInst_TextSimple 24 #define ESCHER_ShpInst_TextOctagon 25 #define ESCHER_ShpInst_TextHexagon 26 #define ESCHER_ShpInst_TextCurve 27 #define ESCHER_ShpInst_TextWave 28 #define ESCHER_ShpInst_TextRing 29 #define ESCHER_ShpInst_TextOnCurve 30 #define ESCHER_ShpInst_TextOnRing 31 #define ESCHER_ShpInst_StraightConnector1 32 #define ESCHER_ShpInst_BentConnector2 33 #define ESCHER_ShpInst_BentConnector3 34 #define ESCHER_ShpInst_BentConnector4 35 #define ESCHER_ShpInst_BentConnector5 36 #define ESCHER_ShpInst_CurvedConnector2 37 #define ESCHER_ShpInst_CurvedConnector3 38 #define ESCHER_ShpInst_CurvedConnector4 39 #define ESCHER_ShpInst_CurvedConnector5 40 #define ESCHER_ShpInst_Callout1 41 #define ESCHER_ShpInst_Callout2 42 #define ESCHER_ShpInst_Callout3 43 #define ESCHER_ShpInst_AccentCallout1 44 #define ESCHER_ShpInst_AccentCallout2 45 #define ESCHER_ShpInst_AccentCallout3 46 #define ESCHER_ShpInst_BorderCallout1 47 #define ESCHER_ShpInst_BorderCallout2 48 #define ESCHER_ShpInst_BorderCallout3 49 #define ESCHER_ShpInst_AccentBorderCallout1 50 #define ESCHER_ShpInst_AccentBorderCallout2 51 #define ESCHER_ShpInst_AccentBorderCallout3 52 #define ESCHER_ShpInst_Ribbon 53 #define ESCHER_ShpInst_Ribbon2 54 #define ESCHER_ShpInst_Chevron 55 #define ESCHER_ShpInst_Pentagon 56 #define ESCHER_ShpInst_NoSmoking 57 #define ESCHER_ShpInst_Seal8 58 #define ESCHER_ShpInst_Seal16 59 #define ESCHER_ShpInst_Seal32 60 #define ESCHER_ShpInst_WedgeRectCallout 61 #define ESCHER_ShpInst_WedgeRRectCallout 62 #define ESCHER_ShpInst_WedgeEllipseCallout 63 #define ESCHER_ShpInst_Wave 64 #define ESCHER_ShpInst_FoldedCorner 65 #define ESCHER_ShpInst_LeftArrow 66 #define ESCHER_ShpInst_DownArrow 67 #define ESCHER_ShpInst_UpArrow 68 #define ESCHER_ShpInst_LeftRightArrow 69 #define ESCHER_ShpInst_UpDownArrow 70 #define ESCHER_ShpInst_IrregularSeal1 71 #define ESCHER_ShpInst_IrregularSeal2 72 #define ESCHER_ShpInst_LightningBolt 73 #define ESCHER_ShpInst_Heart 74 #define ESCHER_ShpInst_PictureFrame 75 #define ESCHER_ShpInst_QuadArrow 76 #define ESCHER_ShpInst_LeftArrowCallout 77 #define ESCHER_ShpInst_RightArrowCallout 78 #define ESCHER_ShpInst_UpArrowCallout 79 #define ESCHER_ShpInst_DownArrowCallout 80 #define ESCHER_ShpInst_LeftRightArrowCallout 81 #define ESCHER_ShpInst_UpDownArrowCallout 82 #define ESCHER_ShpInst_QuadArrowCallout 83 #define ESCHER_ShpInst_Bevel 84 #define ESCHER_ShpInst_LeftBracket 85 #define ESCHER_ShpInst_RightBracket 86 #define ESCHER_ShpInst_LeftBrace 87 #define ESCHER_ShpInst_RightBrace 88 #define ESCHER_ShpInst_LeftUpArrow 89 #define ESCHER_ShpInst_BentUpArrow 90 #define ESCHER_ShpInst_BentArrow 91 #define ESCHER_ShpInst_Seal24 92 #define ESCHER_ShpInst_StripedRightArrow 93 #define ESCHER_ShpInst_NotchedRightArrow 94 #define ESCHER_ShpInst_BlockArc 95 #define ESCHER_ShpInst_SmileyFace 96 #define ESCHER_ShpInst_VerticalScroll 97 #define ESCHER_ShpInst_HorizontalScroll 98 #define ESCHER_ShpInst_CircularArrow 99 #define ESCHER_ShpInst_NotchedCircularArrow 100 #define ESCHER_ShpInst_UturnArrow 101 #define ESCHER_ShpInst_CurvedRightArrow 102 #define ESCHER_ShpInst_CurvedLeftArrow 103 #define ESCHER_ShpInst_CurvedUpArrow 104 #define ESCHER_ShpInst_CurvedDownArrow 105 #define ESCHER_ShpInst_CloudCallout 106 #define ESCHER_ShpInst_EllipseRibbon 107 #define ESCHER_ShpInst_EllipseRibbon2 108 #define ESCHER_ShpInst_FlowChartProcess 109 #define ESCHER_ShpInst_FlowChartDecision 110 #define ESCHER_ShpInst_FlowChartInputOutput 111 #define ESCHER_ShpInst_FlowChartPredefinedProcess 112 #define ESCHER_ShpInst_FlowChartInternalStorage 113 #define ESCHER_ShpInst_FlowChartDocument 114 #define ESCHER_ShpInst_FlowChartMultidocument 115 #define ESCHER_ShpInst_FlowChartTerminator 116 #define ESCHER_ShpInst_FlowChartPreparation 117 #define ESCHER_ShpInst_FlowChartManualInput 118 #define ESCHER_ShpInst_FlowChartManualOperation 119 #define ESCHER_ShpInst_FlowChartConnector 120 #define ESCHER_ShpInst_FlowChartPunchedCard 121 #define ESCHER_ShpInst_FlowChartPunchedTape 122 #define ESCHER_ShpInst_FlowChartSummingJunction 123 #define ESCHER_ShpInst_FlowChartOr 124 #define ESCHER_ShpInst_FlowChartCollate 125 #define ESCHER_ShpInst_FlowChartSort 126 #define ESCHER_ShpInst_FlowChartExtract 127 #define ESCHER_ShpInst_FlowChartMerge 128 #define ESCHER_ShpInst_FlowChartOfflineStorage 129 #define ESCHER_ShpInst_FlowChartOnlineStorage 130 #define ESCHER_ShpInst_FlowChartMagneticTape 131 #define ESCHER_ShpInst_FlowChartMagneticDisk 132 #define ESCHER_ShpInst_FlowChartMagneticDrum 133 #define ESCHER_ShpInst_FlowChartDisplay 134 #define ESCHER_ShpInst_FlowChartDelay 135 #define ESCHER_ShpInst_TextPlainText 136 #define ESCHER_ShpInst_TextStop 137 #define ESCHER_ShpInst_TextTriangle 138 #define ESCHER_ShpInst_TextTriangleInverted 139 #define ESCHER_ShpInst_TextChevron 140 #define ESCHER_ShpInst_TextChevronInverted 141 #define ESCHER_ShpInst_TextRingInside 142 #define ESCHER_ShpInst_TextRingOutside 143 #define ESCHER_ShpInst_TextArchUpCurve 144 #define ESCHER_ShpInst_TextArchDownCurve 145 #define ESCHER_ShpInst_TextCircleCurve 146 #define ESCHER_ShpInst_TextButtonCurve 147 #define ESCHER_ShpInst_TextArchUpPour 148 #define ESCHER_ShpInst_TextArchDownPour 149 #define ESCHER_ShpInst_TextCirclePour 150 #define ESCHER_ShpInst_TextButtonPour 151 #define ESCHER_ShpInst_TextCurveUp 152 #define ESCHER_ShpInst_TextCurveDown 153 #define ESCHER_ShpInst_TextCascadeUp 154 #define ESCHER_ShpInst_TextCascadeDown 155 #define ESCHER_ShpInst_TextWave1 156 #define ESCHER_ShpInst_TextWave2 157 #define ESCHER_ShpInst_TextWave3 158 #define ESCHER_ShpInst_TextWave4 159 #define ESCHER_ShpInst_TextInflate 160 #define ESCHER_ShpInst_TextDeflate 161 #define ESCHER_ShpInst_TextInflateBottom 162 #define ESCHER_ShpInst_TextDeflateBottom 163 #define ESCHER_ShpInst_TextInflateTop 164 #define ESCHER_ShpInst_TextDeflateTop 165 #define ESCHER_ShpInst_TextDeflateInflate 166 #define ESCHER_ShpInst_TextDeflateInflateDeflate 167 #define ESCHER_ShpInst_TextFadeRight 168 #define ESCHER_ShpInst_TextFadeLeft 169 #define ESCHER_ShpInst_TextFadeUp 170 #define ESCHER_ShpInst_TextFadeDown 171 #define ESCHER_ShpInst_TextSlantUp 172 #define ESCHER_ShpInst_TextSlantDown 173 #define ESCHER_ShpInst_TextCanUp 174 #define ESCHER_ShpInst_TextCanDown 175 #define ESCHER_ShpInst_FlowChartAlternateProcess 176 #define ESCHER_ShpInst_FlowChartOffpageConnector 177 #define ESCHER_ShpInst_Callout90 178 #define ESCHER_ShpInst_AccentCallout90 179 #define ESCHER_ShpInst_BorderCallout90 180 #define ESCHER_ShpInst_AccentBorderCallout90 181 #define ESCHER_ShpInst_LeftRightUpArrow 182 #define ESCHER_ShpInst_Sun 183 #define ESCHER_ShpInst_Moon 184 #define ESCHER_ShpInst_BracketPair 185 #define ESCHER_ShpInst_BracePair 186 #define ESCHER_ShpInst_Seal4 187 #define ESCHER_ShpInst_DoubleWave 188 #define ESCHER_ShpInst_ActionButtonBlank 189 #define ESCHER_ShpInst_ActionButtonHome 190 #define ESCHER_ShpInst_ActionButtonHelp 191 #define ESCHER_ShpInst_ActionButtonInformation 192 #define ESCHER_ShpInst_ActionButtonForwardNext 193 #define ESCHER_ShpInst_ActionButtonBackPrevious 194 #define ESCHER_ShpInst_ActionButtonEnd 195 #define ESCHER_ShpInst_ActionButtonBeginning 196 #define ESCHER_ShpInst_ActionButtonReturn 197 #define ESCHER_ShpInst_ActionButtonDocument 198 #define ESCHER_ShpInst_ActionButtonSound 199 #define ESCHER_ShpInst_ActionButtonMovie 200 #define ESCHER_ShpInst_HostControl 201 #define ESCHER_ShpInst_TextBox 202 #define ESCHER_ShpInst_COUNT 203 #define ESCHER_ShpInst_Max 0x0FFF #define ESCHER_ShpInst_Nil ESCHER_ShpInst_Max enum ESCHER_BlibType { // GEL provided types... ERROR = 0, // An error occurred during loading UNKNOWN, // An unknown blip type EMF, // Windows Enhanced Metafile WMF, // Windows Metafile PICT, // Macintosh PICT PEG, // JFIF PNG, // PNG DIB, // Windows DIB FirstClient = 32, // First client defined blip type LastClient = 255 // Last client defined blip type }; enum ESCHER_FillStyle { ESCHER_FillSolid, // Fill with a solid color ESCHER_FillPattern, // Fill with a pattern (bitmap) ESCHER_FillTexture, // A texture (pattern with its own color map) ESCHER_FillPicture, // Center a picture in the shape ESCHER_FillShade, // Shade from start to end points ESCHER_FillShadeCenter, // Shade from bounding rectangle to end point ESCHER_FillShadeShape, // Shade from shape outline to end point ESCHER_FillShadeScale, ESCHER_FillShadeTitle, ESCHER_FillBackground }; enum ESCHER_wMode { ESCHER_wColor, // only used for predefined shades ESCHER_wAutomatic, // depends on object type ESCHER_wGrayScale, // shades of gray only ESCHER_wLightGrayScale, // shades of light gray only ESCHER_wInverseGray, // dark gray mapped to light gray, etc. ESCHER_wGrayOutline, // pure gray and white ESCHER_wBlackTextLine, // black text and lines, all else grayscale ESCHER_wHighContrast, // pure black and white mode (no grays) ESCHER_wBlack, // solid black msobwWhite, // solid white ESCHER_wDontShow, // object not drawn ESCHER_wNumModes // number of Black and white modes }; // enum ESCHER_ShapePath { ESCHER_ShapeLines, // A line of straight segments ESCHER_ShapeLinesClosed, // A closed polygonal object ESCHER_ShapeCurves, // A line of Bezier curve segments ESCHER_ShapeCurvesClosed, // A closed shape with curved edges ESCHER_ShapeComplex // pSegmentInfo must be non-empty }; enum ESCHER_WrapMode { ESCHER_WrapSquare, ESCHER_WrapByPoints, ESCHER_WrapNone, ESCHER_WrapTopBottom, ESCHER_WrapThrough }; // enum ESCHER_bwMode { ESCHER_bwColor, // only used for predefined shades ESCHER_bwAutomatic, // depends on object type ESCHER_bwGrayScale, // shades of gray only ESCHER_bwLightGrayScale, // shades of light gray only ESCHER_bwInverseGray, // dark gray mapped to light gray, etc. ESCHER_bwGrayOutline, // pure gray and white ESCHER_bwBlackTextLine, // black text and lines, all else grayscale ESCHER_bwHighContrast, // pure black and white mode (no grays) ESCHER_bwBlack, // solid black ESCHER_bwWhite, // solid white ESCHER_bwDontShow, // object not drawn ESCHER_bwNumModes // number of Black and white modes }; enum ESCHER_AnchorText { ESCHER_AnchorTop, ESCHER_AnchorMiddle, ESCHER_AnchorBottom, ESCHER_AnchorTopCentered, ESCHER_AnchorMiddleCentered, ESCHER_AnchorBottomCentered, ESCHER_AnchorTopBaseline, ESCHER_AnchorBottomBaseline, ESCHER_AnchorTopCenteredBaseline, ESCHER_AnchorBottomCenteredBaseline }; enum ESCHER_cDir { ESCHER_cDir0, // Right ESCHER_cDir90, // Down ESCHER_cDir180, // Left ESCHER_cDir270 // Up }; // connector style enum ESCHER_cxSTYLE { ESCHER_cxstyleStraight = 0, ESCHER_cxstyleBent, ESCHER_cxstyleCurved, ESCHER_cxstyleNone }; // text flow enum ESCHER_txfl { ESCHER_txflHorzN, // Horizontal non-@ ESCHER_txflTtoBA, // Top to Bottom @-font ESCHER_txflBtoT, // Bottom to Top non-@ ESCHER_txflTtoBN, // Top to Bottom non-@ ESCHER_txflHorzA, // Horizontal @-font ESCHER_txflVertN // Vertical, non-@ }; // text direction (needed for Bi-Di support) enum ESCHER_txDir { ESCHER_txdirLTR, // left-to-right text direction ESCHER_txdirRTL, // right-to-left text direction ESCHER_txdirContext // context text direction }; // Callout Type enum ESCHER_spcot { ESCHER_spcotRightAngle = 1, ESCHER_spcotOneSegment = 2, ESCHER_spcotTwoSegment = 3, ESCHER_spcotThreeSegment = 4 }; // Callout Angle enum ESCHER_spcoa { ESCHER_spcoaAny, ESCHER_spcoa30, ESCHER_spcoa45, ESCHER_spcoa60, ESCHER_spcoa90, ESCHER_spcoa0 }; // Callout Drop enum ESCHER_spcod { ESCHER_spcodTop, ESCHER_spcodCenter, ESCHER_spcodBottom, ESCHER_spcodSpecified }; // FontWork alignment enum ESCHER_GeoTextAlign { ESCHER_AlignTextStretch, /* Stretch each line of text to fit width. */ ESCHER_AlignTextCenter, /* Center text on width. */ ESCHER_AlignTextLeft, /* Left justify. */ ESCHER_AlignTextRight, /* Right justify. */ ESCHER_AlignTextLetterJust, /* Spread letters out to fit width. */ ESCHER_AlignTextWordJust, /* Spread words out to fit width. */ ESCHER_AlignTextInvalid /* Invalid */ }; // flags for pictures enum ESCHER_BlipFlags { ESCHER_BlipFlagDefault = 0, ESCHER_BlipFlagComment = 0, // Blip name is a comment ESCHER_BlipFlagFile, // Blip name is a file name ESCHER_BlipFlagURL, // Blip name is a full URL ESCHER_BlipFlagType = 3, // Mask to extract type /* Or the following flags with any of the above. */ ESCHER_BlipFlagDontSave = 4, // A "dont" is the depression in the metal // body work of an automobile caused when a // cyclist violently thrusts his or her nose // at it, thus a DontSave is another name for // a cycle lane. ESCHER_BlipFlagDoNotSave = 4, // For those who prefer English ESCHER_BlipFlagLinkToFile = 8 }; // enum ESCHER_3DRenderMode { ESCHER_FullRender, // Generate a full rendering ESCHER_Wireframe, // Generate a wireframe ESCHER_BoundingCube // Generate a bounding cube }; // enum ESCHER_xFormType { ESCHER_xFormAbsolute, // Apply transform in absolute space centered on shape ESCHER_xFormShape, // Apply transform to shape geometry ESCHER_xFormDrawing // Apply transform in drawing space }; // enum ESCHER_ShadowType { ESCHER_ShadowOffset, // N pixel offset shadow ESCHER_ShadowDouble, // Use second offset too ESCHER_ShadowRich, // Rich perspective shadow (cast relative to shape) ESCHER_ShadowShape, // Rich perspective shadow (cast in shape space) ESCHER_ShadowDrawing, // Perspective shadow cast in drawing space ESCHER_ShadowEmbossOrEngrave }; // - the type of a (length) measurement enum ESCHER_dzType { ESCHER_dzTypeMin = 0, ESCHER_dzTypeDefault = 0, // Default size, ignore the values ESCHER_dzTypeA = 1, // Values are in EMUs ESCHER_dzTypeV = 2, // Values are in pixels ESCHER_dzTypeShape = 3, // Values are 16.16 fractions of shape size ESCHER_dzTypeFixedAspect = 4, // Aspect ratio is fixed ESCHER_dzTypeAFixed = 5, // EMUs, fixed aspect ratio ESCHER_dzTypeVFixed = 6, // Pixels, fixed aspect ratio ESCHER_dzTypeShapeFixed = 7, // Proportion of shape, fixed aspect ratio ESCHER_dzTypeFixedAspectEnlarge= 8, // Aspect ratio is fixed, favor larger size ESCHER_dzTypeAFixedBig = 9, // EMUs, fixed aspect ratio ESCHER_dzTypeVFixedBig = 10, // Pixels, fixed aspect ratio ESCHER_dzTypeShapeFixedBig= 11, // Proportion of shape, fixed aspect ratio ESCHER_dzTypeMax = 11 }; // how to interpret the colors in a shaded fill. enum ESCHER_ShadeType { ESCHER_ShadeNone = 0, // Interpolate without correction between RGBs ESCHER_ShadeGamma = 1, // Apply gamma correction to colors ESCHER_ShadeSigma = 2, // Apply a sigma transfer function to position ESCHER_ShadeBand = 4, // Add a flat band at the start of the shade ESCHER_ShadeOneColor = 8, // This is a one color shade /* A parameter for the band or sigma function can be stored in the top 16 bits of the value - this is a proportion of *each* band of the shade to make flat (or the approximate equal value for a sigma function). NOTE: the parameter is not used for the sigma function, instead a built in value is used. This value should not be changed from the default! */ ESCHER_ShadeParameterShift = 16, ESCHER_ShadeParameterMask = 0xffff0000, ESCHER_ShadeDefault = (ESCHER_ShadeGamma|ESCHER_ShadeSigma| (16384<<ESCHER_ShadeParameterShift)) }; // compound line style enum ESCHER_LineStyle { ESCHER_LineSimple, // Single line (of width lineWidth) ESCHER_LineDouble, // Double lines of equal width ESCHER_LineThickThin, // Double lines, one thick, one thin ESCHER_LineThinThick, // Double lines, reverse order ESCHER_LineTriple // Three lines, thin, thick, thin }; // how to "fill" the line contour enum ESCHER_LineType { ESCHER_lineSolidType, // Fill with a solid color ESCHER_linePattern, // Fill with a pattern (bitmap) ESCHER_lineTexture, // A texture (pattern with its own color map) ESCHER_linePicture // Center a picture in the shape }; // dashed line style enum ESCHER_LineDashing { ESCHER_LineSolid, // Solid (continuous) pen ESCHER_LineDashSys, // PS_DASH system dash style ESCHER_LineDotSys, // PS_DOT system dash style ESCHER_LineDashDotSys, // PS_DASHDOT system dash style ESCHER_LineDashDotDotSys, // PS_DASHDOTDOT system dash style ESCHER_LineDotGEL, // square dot style ESCHER_LineDashGEL, // dash style ESCHER_LineLongDashGEL, // long dash style ESCHER_LineDashDotGEL, // dash short dash ESCHER_LineLongDashDotGEL, // long dash short dash ESCHER_LineLongDashDotDotGEL // long dash short dash short dash }; // line end effect enum ESCHER_LineEnd { ESCHER_LineNoEnd, ESCHER_LineArrowEnd, ESCHER_LineArrowStealthEnd, ESCHER_LineArrowDiamondEnd, ESCHER_LineArrowOvalEnd, ESCHER_LineArrowOpenEnd }; // size of arrowhead enum ESCHER_LineWidth { ESCHER_LineNarrowArrow, ESCHER_LineMediumWidthArrow, ESCHER_LineWideArrow }; // size of arrowhead enum ESCHER_LineEndLenght { ESCHER_LineShortArrow, ESCHER_LineMediumLenArrow, ESCHER_LineLongArrow }; // line join style. enum ESCHER_LineJoin { ESCHER_LineJoinBevel, // Join edges by a straight line ESCHER_LineJoinMiter, // Extend edges until they join ESCHER_LineJoinRound // Draw an arc between the two edges }; // line cap style (applies to ends of dash segments too). enum ESCHER_LineCap { ESCHER_LineEndCapRound, // Rounded ends - the default ESCHER_LineEndCapSquare, // Square protrudes by half line width ESCHER_LineEndCapFlat // Line ends at end point }; // Shape Properties // 1pt = 12700 EMU (English Metric Units) // 1pt = 20 Twip = 20/1440" = 1/72" // 1twip=635 EMU // 1" = 12700*72 = 914400 EMU // 1" = 25.4mm // 1mm = 36000 EMU // Transform #define ESCHER_Prop_Rotation 4 /* Fixed Point 16.16 degrees */ // Protection #define ESCHER_Prop_LockRotation 119 /* sal_Bool No rotation */ #define ESCHER_Prop_LockAspectRatio 120 /* sal_Bool Don't allow changes in aspect ratio */ #define ESCHER_Prop_LockPosition 121 /* sal_Bool Don't allow the shape to be moved */ #define ESCHER_Prop_LockAgainstSelect 122 /* sal_Bool Shape may not be selected */ #define ESCHER_Prop_LockCropping 123 /* sal_Bool No cropping this shape */ #define ESCHER_Prop_LockVertices 124 /* sal_Bool Edit Points not allowed */ #define ESCHER_Prop_LockText 125 /* sal_Bool Do not edit text */ #define ESCHER_Prop_LockAdjustHandles 126 /* sal_Bool Do not adjust */ #define ESCHER_Prop_LockAgainstGrouping 127 /* sal_Bool Do not group this shape */ // Text #define ESCHER_Prop_lTxid 128 /* LONG id for the text, value determined by the host */ #define ESCHER_Prop_dxTextLeft 129 /* LONG margins relative to shape's inscribed */ #define ESCHER_Prop_dyTextTop 130 /* LONG text rectangle (in EMUs) */ #define ESCHER_Prop_dxTextRight 131 /* LONG */ #define ESCHER_Prop_dyTextBottom 132 /* LONG */ #define ESCHER_Prop_WrapText 133 /* MSOWRAPMODE Wrap text at shape margins */ #define ESCHER_Prop_scaleText 134 /* LONG Text zoom/scale (used if fFitTextToShape) */ #define ESCHER_Prop_AnchorText 135 /* ESCHER_AnchorText How to anchor the text */ #define ESCHER_Prop_txflTextFlow 136 /* MSOTXFL Text flow */ #define ESCHER_Prop_cdirFont 137 /* MSOCDIR Font rotation */ #define ESCHER_Prop_hspNext 138 /* MSOHSP ID of the next shape (used by Word for linked textboxes) */ #define ESCHER_Prop_txdir 139 /* MSOTXDIR Bi-Di Text direction */ #define ESCHER_Prop_SelectText 187 /* sal_Bool sal_True if single click selects text, sal_False if two clicks */ #define ESCHER_Prop_AutoTextMargin 188 /* sal_Bool use host's margin calculations */ #define ESCHER_Prop_RotateText 189 /* sal_Bool Rotate text with shape */ #define ESCHER_Prop_FitShapeToText 190 /* sal_Bool Size shape to fit text size */ #define ESCHER_Prop_FitTextToShape 191 /* sal_Bool Size text to fit shape size */ // GeoText #define ESCHER_Prop_gtextUNICODE 192 /* WCHAR* UNICODE text string */ #define ESCHER_Prop_gtextRTF 193 /* char* RTF text string */ #define ESCHER_Prop_gtextAlign 194 /* MSOGEOTEXTALIGN alignment on curve */ #define ESCHER_Prop_gtextSize 195 /* LONG default point size */ #define ESCHER_Prop_gtextSpacing 196 /* LONG fixed point 16.16 */ #define ESCHER_Prop_gtextFont 197 /* WCHAR* font family name */ #define ESCHER_Prop_gtextFReverseRows 240 /* sal_Bool Reverse row order */ #define ESCHER_Prop_fGtext 241 /* sal_Bool Has text effect */ #define ESCHER_Prop_gtextFVertical 242 /* sal_Bool Rotate characters */ #define ESCHER_Prop_gtextFKern 243 /* sal_Bool Kern characters */ #define ESCHER_Prop_gtextFTight 244 /* sal_Bool Tightening or tracking */ #define ESCHER_Prop_gtextFStretch 245 /* sal_Bool Stretch to fit shape */ #define ESCHER_Prop_gtextFShrinkFit 246 /* sal_Bool Char bounding box */ #define ESCHER_Prop_gtextFBestFit 247 /* sal_Bool Scale text-on-path */ #define ESCHER_Prop_gtextFNormalize 248 /* sal_Bool Stretch char height */ #define ESCHER_Prop_gtextFDxMeasure 249 /* sal_Bool Do not measure along path */ #define ESCHER_Prop_gtextFBold 250 /* sal_Bool Bold font */ #define ESCHER_Prop_gtextFItalic 251 /* sal_Bool Italic font */ #define ESCHER_Prop_gtextFUnderline 252 /* sal_Bool Underline font */ #define ESCHER_Prop_gtextFShadow 253 /* sal_Bool Shadow font */ #define ESCHER_Prop_gtextFSmallcaps 254 /* sal_Bool Small caps font */ #define ESCHER_Prop_gtextFStrikethrough 255 /* sal_Bool Strike through font */ // Blip #define ESCHER_Prop_cropFromTop 256 /* LONG 16.16 fraction times total */ #define ESCHER_Prop_cropFromBottom 257 /* LONG image width or height, */ #define ESCHER_Prop_cropFromLeft 258 /* LONG as appropriate. */ #define ESCHER_Prop_cropFromRight 259 /* LONG */ #define ESCHER_Prop_pib 260 /* IMsoBlip* Blip to display */ #define ESCHER_Prop_pibName 261 /* WCHAR* Blip file name */ #define ESCHER_Prop_pibFlags 262 /* MSOBLIPFLAGS Blip flags */ #define ESCHER_Prop_pictureTransparent 263 /* LONG transparent color (none if ~0UL) */ #define ESCHER_Prop_pictureContrast 264 /* LONG contrast setting */ #define ESCHER_Prop_pictureBrightness 265 /* LONG brightness setting */ #define ESCHER_Prop_pictureGamma 266 /* LONG 16.16 gamma */ #define ESCHER_Prop_pictureId 267 /* LONG Host-defined ID for OLE objects (usually a pointer) */ #define ESCHER_Prop_pictureDblCrMod 268 /* MSOCLR Modification used if shape has double shadow */ #define ESCHER_Prop_pictureFillCrMod 269 /* MSOCLR */ #define ESCHER_Prop_pictureLineCrMod 270 /* MSOCLR */ #define ESCHER_Prop_pibPrint 271 /* IMsoBlip* Blip to display when printing */ #define ESCHER_Prop_pibPrintName 272 /* WCHAR* Blip file name */ #define ESCHER_Prop_pibPrintFlags 273 /* MSOBLIPFLAGS Blip flags */ #define ESCHER_Prop_fNoHitTestPicture 316 /* sal_Bool Do not hit test the picture */ #define ESCHER_Prop_pictureGray 317 /* sal_Bool grayscale display */ #define ESCHER_Prop_pictureBiLevel 318 /* sal_Bool bi-level display */ #define ESCHER_Prop_pictureActive 319 /* sal_Bool Server is active (OLE objects only) */ // Geometry #define ESCHER_Prop_geoLeft 320 /* LONG Defines the G (geometry) coordinate space. */ #define ESCHER_Prop_geoTop 321 /* LONG */ #define ESCHER_Prop_geoRight 322 /* LONG */ #define ESCHER_Prop_geoBottom 323 /* LONG */ #define ESCHER_Prop_shapePath 324 /* MSOSHAPEPATH */ #define ESCHER_Prop_pVertices 325 /* IMsoArray An array of points, in G units. */ #define ESCHER_Prop_pSegmentInfo 326 /* IMsoArray */ #define ESCHER_Prop_adjustValue 327 /* LONG Adjustment values corresponding to */ #define ESCHER_Prop_adjust2Value 328 /* LONG the positions of the adjust handles */ #define ESCHER_Prop_adjust3Value 329 /* LONG of the shape. The number of values */ #define ESCHER_Prop_adjust4Value 330 /* LONG used and their allowable ranges vary */ #define ESCHER_Prop_adjust5Value 331 /* LONG from shape type to shape type. */ #define ESCHER_Prop_adjust6Value 332 /* LONG */ #define ESCHER_Prop_adjust7Value 333 /* LONG */ #define ESCHER_Prop_adjust8Value 334 /* LONG */ #define ESCHER_Prop_adjust9Value 335 /* LONG */ #define ESCHER_Prop_adjust10Value 336 /* LONG */ #define ESCHER_Prop_fShadowOK 378 /* sal_Bool Shadow may be set */ #define ESCHER_Prop_f3DOK 379 /* sal_Bool 3D may be set */ #define ESCHER_Prop_fLineOK 380 /* sal_Bool Line style may be set */ #define ESCHER_Prop_fGtextOK 381 /* sal_Bool Text effect (FontWork) supported */ #define ESCHER_Prop_fFillShadeShapeOK 382 /* sal_Bool */ #define ESCHER_Prop_fFillOK 383 /* sal_Bool OK to fill the shape through the UI or VBA? */ // FillStyle #define ESCHER_Prop_fillType 384 /* ESCHER_FillStyle Type of fill */ #define ESCHER_Prop_fillColor 385 /* MSOCLR Foreground color */ #define ESCHER_Prop_fillOpacity 386 /* LONG Fixed 16.16 */ #define ESCHER_Prop_fillBackColor 387 /* MSOCLR Background color */ #define ESCHER_Prop_fillBackOpacity 388 /* LONG Shades only */ #define ESCHER_Prop_fillCrMod 389 /* MSOCLR Modification for BW views */ #define ESCHER_Prop_fillBlip 390 /* IMsoBlip* Pattern/texture */ #define ESCHER_Prop_fillBlipName 391 /* WCHAR* Blip file name */ #define ESCHER_Prop_fillBlipFlags 392 /* MSOBLIPFLAGS Blip flags */ #define ESCHER_Prop_fillWidth 393 /* LONG How big (A units) to make a metafile texture. */ #define ESCHER_Prop_fillHeight 394 /* LONG */ #define ESCHER_Prop_fillAngle 395 /* LONG Fade angle - degrees in 16.16 */ #define ESCHER_Prop_fillFocus 396 /* LONG Linear shaded fill focus percent */ #define ESCHER_Prop_fillToLeft 397 /* LONG Fraction 16.16 */ #define ESCHER_Prop_fillToTop 398 /* LONG Fraction 16.16 */ #define ESCHER_Prop_fillToRight 399 /* LONG Fraction 16.16 */ #define ESCHER_Prop_fillToBottom 400 /* LONG Fraction 16.16 */ #define ESCHER_Prop_fillRectLeft 401 /* LONG For shaded fills, use the specified rectangle */ #define ESCHER_Prop_fillRectTop 402 /* LONG instead of the shape's bounding rect to */ #define ESCHER_Prop_fillRectRight 403 /* LONG define how large the fade is going to be. */ #define ESCHER_Prop_fillRectBottom 404 /* LONG */ #define ESCHER_Prop_fillDztype 405 /* MSODZTYPE */ #define ESCHER_Prop_fillShadePreset 406 /* LONG Special shades */ #define ESCHER_Prop_fillShadeColors 407 /* IMsoArray a preset array of colors */ #define ESCHER_Prop_fillOriginX 408 /* LONG */ #define ESCHER_Prop_fillOriginY 409 /* LONG */ #define ESCHER_Prop_fillShapeOriginX 410 /* LONG */ #define ESCHER_Prop_fillShapeOriginY 411 /* LONG */ #define ESCHER_Prop_fillShadeType 412 /* MSOSHADETYPE Type of shading, if a shaded (gradient) fill. */ #define ESCHER_Prop_fFilled 443 /* sal_Bool Is shape filled? */ #define ESCHER_Prop_fHitTestFill 444 /* sal_Bool Should we hit test fill? */ #define ESCHER_Prop_fillShape 445 /* sal_Bool Register pattern on shape */ #define ESCHER_Prop_fillUseRect 446 /* sal_Bool Use the large rect? */ #define ESCHER_Prop_fNoFillHitTest 447 /* sal_Bool Hit test a shape as though filled */ // LineStyle #define ESCHER_Prop_lineColor 448 /* MSOCLR Color of line */ #define ESCHER_Prop_lineOpacity 449 /* LONG Not implemented */ #define ESCHER_Prop_lineBackColor 450 /* MSOCLR Background color */ #define ESCHER_Prop_lineCrMod 451 /* MSOCLR Modification for BW views */ #define ESCHER_Prop_lineType 452 /* MSOLINETYPE Type of line */ #define ESCHER_Prop_lineFillBlip 453 /* IMsoBlip* Pattern/texture */ #define ESCHER_Prop_lineFillBlipName 454 /* WCHAR* Blip file name */ #define ESCHER_Prop_lineFillBlipFlags 455 /* MSOBLIPFLAGS Blip flags */ #define ESCHER_Prop_lineFillWidth 456 /* LONG How big (A units) to make */ #define ESCHER_Prop_lineFillHeight 457 /* LONG a metafile texture. */ #define ESCHER_Prop_lineFillDztype 458 /* MSODZTYPE How to interpret fillWidth/Height numbers. */ #define ESCHER_Prop_lineWidth 459 /* LONG A units; 1pt == 12700 EMUs */ #define ESCHER_Prop_lineMiterLimit 460 /* LONG ratio (16.16) of width */ #define ESCHER_Prop_lineStyle 461 /* MSOLINESTYLE Draw parallel lines? */ #define ESCHER_Prop_lineDashing 462 /* MSOLINEDASHING Can be overridden by: */ #define ESCHER_Prop_lineDashStyle 463 /* IMsoArray As Win32 ExtCreatePen */ #define ESCHER_Prop_lineStartArrowhead 464 /* MSOLINEEND Arrow at start */ #define ESCHER_Prop_lineEndArrowhead 465 /* MSOLINEEND Arrow at end */ #define ESCHER_Prop_lineStartArrowWidth 466 /* MSOLINEENDWIDTH Arrow at start */ #define ESCHER_Prop_lineStartArrowLength 467 /* MSOLINEENDLENGTH Arrow at end */ #define ESCHER_Prop_lineEndArrowWidth 468 /* MSOLINEENDWIDTH Arrow at start */ #define ESCHER_Prop_lineEndArrowLength 469 /* MSOLINEENDLENGTH Arrow at end */ #define ESCHER_Prop_lineJoinStyle 470 /* MSOLINEJOIN How to join lines */ #define ESCHER_Prop_lineEndCapStyle 471 /* MSOLINECAP How to end lines */ #define ESCHER_Prop_fArrowheadsOK 507 /* sal_Bool Allow arrowheads if prop. is set */ #define ESCHER_Prop_fLine 508 /* sal_Bool Any line? */ #define ESCHER_Prop_fHitTestLine 509 /* sal_Bool Should we hit test lines? */ #define ESCHER_Prop_lineFillShape 510 /* sal_Bool Register pattern on shape */ #define ESCHER_Prop_fNoLineDrawDash 511 /* sal_Bool Draw a dashed line if no line */ // ShadowStyle #define ESCHER_Prop_shadowType 512 /* MSOSHADOWTYPE Type of effect */ #define ESCHER_Prop_shadowColor 513 /* MSOCLR Foreground color */ #define ESCHER_Prop_shadowHighlight 514 /* MSOCLR Embossed color */ #define ESCHER_Prop_shadowCrMod 515 /* MSOCLR Modification for BW views */ #define ESCHER_Prop_shadowOpacity 516 /* LONG Fixed 16.16 */ #define ESCHER_Prop_shadowOffsetX 517 /* LONG Offset shadow */ #define ESCHER_Prop_shadowOffsetY 518 /* LONG Offset shadow */ #define ESCHER_Prop_shadowSecondOffsetX 519 /* LONG Double offset shadow */ #define ESCHER_Prop_shadowSecondOffsetY 520 /* LONG Double offset shadow */ #define ESCHER_Prop_shadowScaleXToX 521 /* LONG 16.16 */ #define ESCHER_Prop_shadowScaleYToX 522 /* LONG 16.16 */ #define ESCHER_Prop_shadowScaleXToY 523 /* LONG 16.16 */ #define ESCHER_Prop_shadowScaleYToY 524 /* LONG 16.16 */ #define ESCHER_Prop_shadowPerspectiveX 525 /* LONG 16.16 / weight */ #define ESCHER_Prop_shadowPerspectiveY 526 /* LONG 16.16 / weight */ #define ESCHER_Prop_shadowWeight 527 /* LONG scaling factor */ #define ESCHER_Prop_shadowOriginX 528 /* LONG */ #define ESCHER_Prop_shadowOriginY 529 /* LONG */ #define ESCHER_Prop_fShadow 574 /* sal_Bool Any shadow? */ #define ESCHER_Prop_fshadowObscured 575 /* sal_Bool Excel5-style shadow */ // PerspectiveStyle #define ESCHER_Prop_perspectiveType 576 /* MSOXFORMTYPE Where transform applies */ #define ESCHER_Prop_perspectiveOffsetX 577 /* LONG The LONG values define a */ #define ESCHER_Prop_perspectiveOffsetY 578 /* LONG transformation matrix, */ #define ESCHER_Prop_perspectiveScaleXToX 579 /* LONG effectively, each value */ #define ESCHER_Prop_perspectiveScaleYToX 580 /* LONG is scaled by the */ #define ESCHER_Prop_perspectiveScaleXToY 581 /* LONG perspectiveWeight parameter. */ #define ESCHER_Prop_perspectiveScaleYToY 582 /* LONG */ #define ESCHER_Prop_perspectivePerspectiveX 583 /* LONG */ #define ESCHER_Prop_perspectivePerspectiveY 584 /* LONG */ #define ESCHER_Prop_perspectiveWeight 585 /* LONG Scaling factor */ #define ESCHER_Prop_perspectiveOriginX 586 /* LONG */ #define ESCHER_Prop_perspectiveOriginY 587 /* LONG */ #define ESCHER_Prop_fPerspective 639 /* sal_Bool On/off */ // 3D Object #define ESCHER_Prop_c3DSpecularAmt 640 /* LONG Fixed-point 16.16 */ #define ESCHER_Prop_c3DDiffuseAmt 641 /* LONG Fixed-point 16.16 */ #define ESCHER_Prop_c3DShininess 642 /* LONG Default gives OK results */ #define ESCHER_Prop_c3DEdgeThickness 643 /* LONG Specular edge thickness */ #define ESCHER_Prop_c3DExtrudeForward 644 /* LONG Distance of extrusion in EMUs */ #define ESCHER_Prop_c3DExtrudeBackward 645 /* LONG */ #define ESCHER_Prop_c3DExtrudePlane 646 /* LONG Extrusion direction */ #define ESCHER_Prop_c3DExtrusionColor 647 /* MSOCLR Basic color of extruded part of shape; the lighting model used will determine the exact shades used when rendering. */ #define ESCHER_Prop_c3DCrMod 648 /* MSOCLR Modification for BW views */ #define ESCHER_Prop_f3D 700 /* sal_Bool Does this shape have a 3D effect? */ #define ESCHER_Prop_fc3DMetallic 701 /* sal_Bool Use metallic specularity? */ #define ESCHER_Prop_fc3DUseExtrusionColor 702 /* sal_Bool */ #define ESCHER_Prop_fc3DLightFace 703 /* sal_Bool */ // 3D Style #define ESCHER_Prop_c3DYRotationAngle 704 /* LONG degrees (16.16) about y axis */ #define ESCHER_Prop_c3DXRotationAngle 705 /* LONG degrees (16.16) about x axis */ #define ESCHER_Prop_c3DRotationAxisX 706 /* LONG These specify the rotation axis; */ #define ESCHER_Prop_c3DRotationAxisY 707 /* LONG only their relative magnitudes */ #define ESCHER_Prop_c3DRotationAxisZ 708 /* LONG matter. */ #define ESCHER_Prop_c3DRotationAngle 709 /* LONG degrees (16.16) about axis */ #define ESCHER_Prop_c3DRotationCenterX 710 /* LONG rotation center x (16.16 or g-units) */ #define ESCHER_Prop_c3DRotationCenterY 711 /* LONG rotation center y (16.16 or g-units) */ #define ESCHER_Prop_c3DRotationCenterZ 712 /* LONG rotation center z (absolute (emus)) */ #define ESCHER_Prop_c3DRenderMode 713 /* MSO3DRENDERMODE Full,wireframe, or bcube */ #define ESCHER_Prop_c3DTolerance 714 /* LONG pixels (16.16) */ #define ESCHER_Prop_c3DXViewpoint 715 /* LONG X view point (emus) */ #define ESCHER_Prop_c3DYViewpoint 716 /* LONG Y view point (emus) */ #define ESCHER_Prop_c3DZViewpoint 717 /* LONG Z view distance (emus) */ #define ESCHER_Prop_c3DOriginX 718 /* LONG */ #define ESCHER_Prop_c3DOriginY 719 /* LONG */ #define ESCHER_Prop_c3DSkewAngle 720 /* LONG degree (16.16) skew angle */ #define ESCHER_Prop_c3DSkewAmount 721 /* LONG Percentage skew amount */ #define ESCHER_Prop_c3DAmbientIntensity 722 /* LONG Fixed point intensity */ #define ESCHER_Prop_c3DKeyX 723 /* LONG Key light source direc- */ #define ESCHER_Prop_c3DKeyY 724 /* LONG tion; only their relative */ #define ESCHER_Prop_c3DKeyZ 725 /* LONG magnitudes matter */ #define ESCHER_Prop_c3DKeyIntensity 726 /* LONG Fixed point intensity */ #define ESCHER_Prop_c3DFillX 727 /* LONG Fill light source direc- */ #define ESCHER_Prop_c3DFillY 728 /* LONG tion; only their relative */ #define ESCHER_Prop_c3DFillZ 729 /* LONG magnitudes matter */ #define ESCHER_Prop_c3DFillIntensity 730 /* LONG Fixed point intensity */ #define ESCHER_Prop_fc3DConstrainRotation 763 /* sal_Bool */ #define ESCHER_Prop_fc3DRotationCenterAuto 764 /* sal_Bool */ #define ESCHER_Prop_fc3DParallel 765 /* sal_Bool Parallel projection? */ #define ESCHER_Prop_fc3DKeyHarsh 766 /* sal_Bool Is key lighting harsh? */ #define ESCHER_Prop_fc3DFillHarsh 767 /* sal_Bool Is fill lighting harsh? */ // Shape #define ESCHER_Prop_hspMaster 769 /* MSOHSP master shape */ #define ESCHER_Prop_cxstyle 771 /* MSOCXSTYLE Type of connector */ #define ESCHER_Prop_bWMode 772 /* ESCHERwMode Settings for modifications to */ #define ESCHER_Prop_bWModePureBW 773 /* ESCHERwMode be made when in different */ #define ESCHER_Prop_bWModeBW 774 /* ESCHERwMode forms of black-and-white mode. */ #define ESCHER_Prop_fOleIcon 826 /* sal_Bool For OLE objects, whether the object is in icon form */ #define ESCHER_Prop_fPreferRelativeResize 827 /* sal_Bool For UI only. Prefer relative resizing. */ #define ESCHER_Prop_fLockShapeType 828 /* sal_Bool Lock the shape type (don't allow Change Shape) */ #define ESCHER_Prop_fDeleteAttachedObject 830 /* sal_Bool */ #define ESCHER_Prop_fBackground 831 /* sal_Bool If sal_True, this is the background shape. */ // Callout #define ESCHER_Prop_spcot 832 /* MSOSPCOT Callout type */ #define ESCHER_Prop_dxyCalloutGap 833 /* LONG Distance from box to first point.(EMUs) */ #define ESCHER_Prop_spcoa 834 /* MSOSPCOA Callout angle */ #define ESCHER_Prop_spcod 835 /* MSOSPCOD Callout drop type */ #define ESCHER_Prop_dxyCalloutDropSpecified 836 /* LONG if msospcodSpecified, the actual drop distance */ #define ESCHER_Prop_dxyCalloutLengthSpecified 837 /* LONG if fCalloutLengthSpecified, the actual distance */ #define ESCHER_Prop_fCallout 889 /* sal_Bool Is the shape a callout? */ #define ESCHER_Prop_fCalloutAccentBar 890 /* sal_Bool does callout have accent bar */ #define ESCHER_Prop_fCalloutTextBorder 891 /* sal_Bool does callout have a text border */ #define ESCHER_Prop_fCalloutMinusX 892 /* sal_Bool */ #define ESCHER_Prop_fCalloutMinusY 893 /* sal_Bool */ #define ESCHER_Prop_fCalloutDropAuto 894 /* sal_Bool If true, then we occasionally invert the drop distance */ #define ESCHER_Prop_fCalloutLengthSpecified 895 /* sal_Bool if true, we look at dxyCalloutLengthSpecified */ // GroupShape #define ESCHER_Prop_wzName 896 /* WCHAR* Shape Name (present only if explicitly set) */ #define ESCHER_Prop_wzDescription 897 /* WCHAR* alternate text */ #define ESCHER_Prop_pihlShape 898 /* IHlink* The hyperlink in the shape. */ #define ESCHER_Prop_pWrapPolygonVertices 899 /* IMsoArray The polygon that text will be wrapped around (Word) */ #define ESCHER_Prop_dxWrapDistLeft 900 /* LONG Left wrapping distance from text (Word) */ #define ESCHER_Prop_dyWrapDistTop 901 /* LONG Top wrapping distance from text (Word) */ #define ESCHER_Prop_dxWrapDistRight 902 /* LONG Right wrapping distance from text (Word) */ #define ESCHER_Prop_dyWrapDistBottom 903 /* LONG Bottom wrapping distance from text (Word) */ #define ESCHER_Prop_lidRegroup 904 /* LONG Regroup ID */ #define ESCHER_Prop_tableProperties 927 #define ESCHER_Prop_tableRowProperties 928 #define ESCHER_Prop_fEditedWrap 953 /* sal_Bool Has the wrap polygon been edited? */ #define ESCHER_Prop_fBehindDocument 954 /* sal_Bool Word-only (shape is behind text) */ #define ESCHER_Prop_fOnDblClickNotify 955 /* sal_Bool Notify client on a double click */ #define ESCHER_Prop_fIsButton 956 /* sal_Bool A button shape (i.e., clicking performs an action). Set for shapes with attached hyperlinks or macros. */ #define ESCHER_Prop_fOneD 957 /* sal_Bool 1D adjustment */ #define ESCHER_Prop_fHidden 958 /* sal_Bool Do not display */ #define ESCHER_Prop_fPrint 959 /* sal_Bool Print this shape */ #define ESCHER_PERSISTENTRY_PREALLOCATE 64 #define ESCHER_Persist_PrivateEntry 0x80000000 #define ESCHER_Persist_Dgg 0x00010000 #define ESCHER_Persist_Dg 0x00020000 #define ESCHER_Persist_CurrentPosition 0x00040000 #define ESCHER_Persist_Grouping_Snap 0x00050000 #define ESCHER_Persist_Grouping_Logic 0x00060000 const sal_uInt32 DFF_DGG_CLUSTER_SIZE = 0x00000400; /// Shape IDs per cluster in DGG atom. // --------------------------------------------------------------------------------------------- namespace com { namespace sun { namespace star { namespace awt { struct Gradient; } namespace drawing { struct EnhancedCustomShapeAdjustmentValue; class XShape; class XShapes; } }}} struct MSFILTER_DLLPUBLIC EscherConnectorListEntry { ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > mXConnector; ::com::sun::star::awt::Point maPointA; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > mXConnectToA; ::com::sun::star::awt::Point maPointB; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > mXConnectToB; sal_uInt32 GetConnectorRule( sal_Bool bFirst ); EscherConnectorListEntry( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rC, const ::com::sun::star::awt::Point& rPA, ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rSA , const ::com::sun::star::awt::Point& rPB, ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rSB ) : mXConnector ( rC ), maPointA ( rPA ), mXConnectToA( rSA ), maPointB ( rPB ), mXConnectToB( rSB ) {} sal_uInt32 GetClosestPoint( const Polygon& rPoly, const ::com::sun::star::awt::Point& rP ); }; struct MSFILTER_DLLPUBLIC EscherExContainer { sal_uInt32 nContPos; SvStream& rStrm; EscherExContainer( SvStream& rSt, const sal_uInt16 nRecType, const sal_uInt16 nInstance = 0 ); ~EscherExContainer(); }; struct MSFILTER_DLLPUBLIC EscherExAtom { sal_uInt32 nContPos; SvStream& rStrm; EscherExAtom( SvStream& rSt, const sal_uInt16 nRecType, const sal_uInt16 nInstance = 0, const sal_uInt8 nVersion = 0 ); ~EscherExAtom(); }; struct EscherPropertyValueHelper { static sal_Bool GetPropertyValue( ::com::sun::star::uno::Any& rAny, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > &, const String& rPropertyName, sal_Bool bTestPropertyAvailability = sal_False ); static ::com::sun::star::beans::PropertyState GetPropertyState( const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet > &, const String& rPropertyName ); }; // --------------------------------------------------------------------------------------------- struct EscherPersistEntry { sal_uInt32 mnID; sal_uInt32 mnOffset; EscherPersistEntry( sal_uInt32 nId, sal_uInt32 nOffset ) { mnID = nId; mnOffset = nOffset; }; }; // --------------------------------------------------------------------------------------------- class EscherBlibEntry { friend class EscherGraphicProvider; friend class EscherEx; protected: sal_uInt32 mnIdentifier[ 4 ]; sal_uInt32 mnPictureOffset; // offset auf die grafik im PictureStreams sal_uInt32 mnSize; // size of real graphic sal_uInt32 mnRefCount; // !! reference count sal_uInt32 mnSizeExtra; // !! size of preceding header ESCHER_BlibType meBlibType; Size maPrefSize; MapMode maPrefMapMode; sal_Bool mbIsEmpty; sal_Bool mbIsNativeGraphicPossible; public: EscherBlibEntry( sal_uInt32 nPictureOffset, const GraphicObject& rObj, const ByteString& rId, const GraphicAttr* pAttr = NULL ); ~EscherBlibEntry(); void WriteBlibEntry( SvStream& rSt, sal_Bool bWritePictureOffset, sal_uInt32 nResize = 0 ); sal_Bool IsEmpty() const { return mbIsEmpty; }; sal_Bool operator==( const EscherBlibEntry& ) const; }; // --------------------------------------------------------------------------------------------- #define _E_GRAPH_PROV_USE_INSTANCES 1 #define _E_GRAPH_PROV_DO_NOT_ROTATE_METAFILES 2 class MSFILTER_DLLPUBLIC EscherGraphicProvider { sal_uInt32 mnFlags; EscherBlibEntry** mpBlibEntrys; sal_uInt32 mnBlibBufSize; sal_uInt32 mnBlibEntrys; rtl::OUString maBaseURI; protected : sal_uInt32 ImplInsertBlib( EscherBlibEntry* p_EscherBlibEntry ); public : sal_uInt32 GetBlibStoreContainerSize( SvStream* pMergePicStreamBSE = NULL ) const; void WriteBlibStoreContainer( SvStream& rStrm, SvStream* pMergePicStreamBSE = NULL ); sal_Bool WriteBlibStoreEntry(SvStream& rStrm, sal_uInt32 nBlipId, sal_Bool bWritePictureOffset, sal_uInt32 nResize = 0); sal_uInt32 GetBlibID( SvStream& rPicOutStream, const ByteString& rGraphicId, const Rectangle& rBoundRect, const com::sun::star::awt::Rectangle* pVisArea = NULL, const GraphicAttr* pGrafikAttr = NULL ); sal_Bool HasGraphics() const { return mnBlibEntrys != 0; }; void SetNewBlipStreamOffset( sal_Int32 nOffset ); sal_Bool GetPrefSize( const sal_uInt32 nBlibId, Size& rSize, MapMode& rMapMode ); void SetBaseURI( const rtl::OUString& rBaseURI ) { maBaseURI = rBaseURI; }; const rtl::OUString& GetBaseURI(){ return maBaseURI; }; EscherGraphicProvider( sal_uInt32 nFlags = _E_GRAPH_PROV_DO_NOT_ROTATE_METAFILES ); ~EscherGraphicProvider(); }; class MSFILTER_DLLPUBLIC EscherSolverContainer { List maShapeList; List maConnectorList; public: sal_uInt32 GetShapeId( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rShape ) const; void AddShape( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > &, sal_uInt32 nId ); void AddConnector( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > &, const ::com::sun::star::awt::Point& rA, ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > &, const ::com::sun::star::awt::Point& rB, ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rConB ); void WriteSolver( SvStream& ); EscherSolverContainer(){}; ~EscherSolverContainer(); }; // --------------------------------------------------------------------------------------------- #define ESCHER_CREATEPOLYGON_LINE 1 #define ESCHER_CREATEPOLYGON_POLYLINE 2 #define ESCHER_CREATEPOLYGON_POLYPOLYGON 4 class GraphicAttr; class SdrObjCustomShape; struct EscherPropSortStruct { sal_uInt8* pBuf; sal_uInt32 nPropSize; sal_uInt32 nPropValue; sal_uInt16 nPropId; }; typedef std::vector< EscherPropSortStruct > EscherProperties; class MSFILTER_DLLPUBLIC EscherPropertyContainer { EscherGraphicProvider* pGraphicProvider; SvStream* pPicOutStrm; Rectangle* pShapeBoundRect; EscherPropSortStruct* pSortStruct; sal_uInt32 nSortCount; sal_uInt32 nSortBufSize; sal_uInt32 nCountCount; sal_uInt32 nCountSize; sal_Bool bHasComplexData; sal_uInt32 ImplGetColor( const sal_uInt32 rColor, sal_Bool bSwap = sal_True ); void ImplCreateGraphicAttributes( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & rXPropSet, sal_uInt32 nBlibId, sal_Bool bCreateCroppingAttributes ); sal_Bool ImplCreateEmbeddedBmp( const ByteString& rUniqueId ); void ImplInit(); public : EscherPropertyContainer(); EscherPropertyContainer( EscherGraphicProvider& rGraphicProvider, // the PropertyContainer needs to know SvStream* pPicOutStrm, // the GraphicProvider to be able to write Rectangle& rShapeBoundRect ); // FillBitmaps or GraphicObjects. // under some cirumstances the ShapeBoundRect is adjusted // this will happen when rotated GraphicObjects // are saved to PowerPoint ~EscherPropertyContainer(); void AddOpt( sal_uInt16 nPropertyID, const rtl::OUString& rString ); void AddOpt( sal_uInt16 nPropertyID, sal_uInt32 nPropValue, sal_Bool bBlib = sal_False ); void AddOpt( sal_uInt16 nPropertyID, sal_Bool bBlib, sal_uInt32 nPropValue, sal_uInt8* pProp, sal_uInt32 nPropSize ); sal_Bool GetOpt( sal_uInt16 nPropertyID, sal_uInt32& rPropValue ) const; sal_Bool GetOpt( sal_uInt16 nPropertyID, EscherPropSortStruct& rPropValue ) const; EscherProperties GetOpts() const; void Commit( SvStream& rSt, sal_uInt16 nVersion = 3, sal_uInt16 nRecType = ESCHER_OPT ); sal_Bool CreateShapeProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rXShape ); sal_Bool CreateOLEGraphicProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rXOleObject ); sal_Bool CreateGraphicProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rXShape, const GraphicObject& rGraphicObj ); sal_Bool CreateMediaGraphicProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rXMediaObject ); /** Creates a complex ESCHER_Prop_fillBlip containing the BLIP directly (for Excel charts). */ sal_Bool CreateEmbeddedBitmapProperties( const ::rtl::OUString& rBitmapUrl, ::com::sun::star::drawing::BitmapMode eBitmapMode ); /** Creates a complex ESCHER_Prop_fillBlip containing a hatch style (for Excel charts). */ sal_Bool CreateEmbeddedHatchProperties( const ::com::sun::star::drawing::Hatch& rHatch, const Color& rBackColor, bool bFillBackground ); // the GraphicProperties will only be created if a GraphicProvider and PicOutStrm is known // DR: #99897# if no GraphicProvider is present, a complex ESCHER_Prop_fillBlip // will be created, containing the BLIP directly (e.g. for Excel charts). sal_Bool CreateGraphicProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & rXPropSet, const String& rSource, const sal_Bool bCreateFillBitmap, const sal_Bool bCreateCroppingAttributes = sal_False, const sal_Bool bFillBitmapModeAllowed = sal_True ); sal_Bool CreateBlipPropertiesforOLEControl( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & rXPropSet, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rXShape); sal_Bool CreatePolygonProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & rXPropSet, sal_uInt32 nFlags, sal_Bool bBezier, ::com::sun::star::awt::Rectangle& rGeoRect, Polygon* pPolygon = NULL ); static sal_uInt32 GetGradientColor( const ::com::sun::star::awt::Gradient* pGradient, sal_uInt32 nStartColor ); void CreateGradientProperties( const ::com::sun::star::awt::Gradient & rGradient ); void CreateGradientProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & , sal_Bool bTransparentGradient = sal_False ); void CreateLineProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > &, sal_Bool bEdge ); void CreateFillProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > &, sal_Bool bEdge , sal_Bool bTransparentGradient = sal_False ); void CreateFillProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > &, sal_Bool bEdge , const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rXShape ); void CreateTextProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > &, sal_uInt32 nText, const sal_Bool bIsCustomShape = sal_False, const sal_Bool bIsTextFrame = sal_True ); sal_Bool CreateConnectorProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rXShape, EscherSolverContainer& rSolver, ::com::sun::star::awt::Rectangle& rGeoRect, sal_uInt16& rShapeType, sal_uInt16& rShapeFlags ); // Because shadow properties depends to the line and fillstyle, the CreateShadowProperties method should be called at last. // It activ only when at least a FillStyle or LineStyle is set. sal_Bool CreateShadowProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & ); sal_Int32 GetValueForEnhancedCustomShapeParameter( const ::com::sun::star::drawing::EnhancedCustomShapeParameter& rParameter, const std::vector< sal_Int32 >& rEquationOrder, sal_Bool bAdjustTrans = sal_False ); // creates all necessary CustomShape properties, this includes also Text-, Shadow-, Fill-, and LineProperties void CreateCustomShapeProperties( const MSO_SPT eShapeType, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & ); sal_Bool IsFontWork() const; // helper functions which are also used by the escher import static PolyPolygon GetPolyPolygon( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rXShape ); static PolyPolygon GetPolyPolygon( const ::com::sun::star::uno::Any& rSource ); static MSO_SPT GetCustomShapeType( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rXShape, sal_uInt32& nMirrorFlags ); static MSO_SPT GetCustomShapeType( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & rXShape, sal_uInt32& nMirrorFlags, rtl::OUString& rShapeType ); // helper functions which are also used in ooxml export static sal_Bool GetLineArrow( const sal_Bool bLineStart, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & rXPropSet, ESCHER_LineEnd& reLineEnd, sal_Int32& rnArrowLength, sal_Int32& rnArrowWidth ); static sal_Bool IsDefaultObject( SdrObjCustomShape* pCustoShape, const MSO_SPT eShapeType ); static void LookForPolarHandles( const MSO_SPT eShapeType, sal_Int32& nAdjustmentsWhichNeedsToBeConverted ); static sal_Bool GetAdjustmentValue( const com::sun::star::drawing::EnhancedCustomShapeAdjustmentValue & rkProp, sal_Int32 nIndex, sal_Int32 nAdjustmentsWhichNeedsToBeConverted, sal_Int32& nValue ); }; // --------------------------------------------------------------------------------------------- class MSFILTER_DLLPUBLIC EscherPersistTable { public: List maPersistTable; sal_Bool PtIsID( sal_uInt32 nID ); void PtInsert( sal_uInt32 nID, sal_uInt32 nOfs ); sal_uInt32 PtDelete( sal_uInt32 nID ); sal_uInt32 PtGetOffsetByID( sal_uInt32 nID ); sal_uInt32 PtReplace( sal_uInt32 nID, sal_uInt32 nOfs ); sal_uInt32 PtReplaceOrInsert( sal_uInt32 nID, sal_uInt32 nOfs ); sal_uInt32 PtGetCount() const { return maPersistTable.Count(); }; EscherPersistTable(); virtual ~EscherPersistTable(); }; // --------------------------------------------------------------------------------------------- class EscherEx; /// abstract base class for ESCHER_ClientTextbox, ESCHER_ClientData class MSFILTER_DLLPUBLIC EscherExClientRecord_Base { public: EscherExClientRecord_Base() {} virtual ~EscherExClientRecord_Base(); /// Application writes the record header /// using rEx.AddAtom(...) followed by /// record data written to rEx.GetStream() virtual void WriteData( EscherEx& rEx ) const = 0; }; /// abstract base class for ESCHER_ClientAnchor class MSFILTER_DLLPUBLIC EscherExClientAnchor_Base { public: EscherExClientAnchor_Base() {} virtual ~EscherExClientAnchor_Base(); /// Application writes the record header /// using rEx.AddAtom(...) followed by /// record data written to rEx.GetStream() virtual void WriteData( EscherEx& rEx, const Rectangle& rRect ) = 0; }; class EscherExHostAppData { private: EscherExClientAnchor_Base* pClientAnchor; EscherExClientRecord_Base* pClientData; EscherExClientRecord_Base* pClientTextbox; // ignore single shape if entire pages are written sal_Bool bDontWriteShape; public: EscherExHostAppData() : pClientAnchor(0), pClientData(0), pClientTextbox(0), bDontWriteShape(sal_False) {} void SetClientAnchor( EscherExClientAnchor_Base* p ) { pClientAnchor = p; } void SetClientData( EscherExClientRecord_Base* p ) { pClientData = p; } void SetClientTextbox( EscherExClientRecord_Base* p ) { pClientTextbox = p; } void SetDontWriteShape( sal_Bool b ) { bDontWriteShape = b; } EscherExClientAnchor_Base* GetClientAnchor() const { return pClientAnchor; } EscherExClientRecord_Base* GetClientData() const { return pClientData; } EscherExClientRecord_Base* GetClientTextbox() const { return pClientTextbox; } void WriteClientAnchor( EscherEx& rEx, const Rectangle& rRect ) { if( pClientAnchor ) pClientAnchor->WriteData( rEx, rRect ); } void WriteClientData( EscherEx& rEx ) { if( pClientData ) pClientData->WriteData( rEx ); } void WriteClientTextbox( EscherEx& rEx ) { if( pClientTextbox ) pClientTextbox->WriteData( rEx ); } sal_Bool DontWriteShape() const { return bDontWriteShape; } }; // ============================================================================ /** Instance for global DFF data, shared through various instances of EscherEx. */ class MSFILTER_DLLPUBLIC EscherExGlobal : public EscherGraphicProvider { public: explicit EscherExGlobal( sal_uInt32 nGraphicProvFlags = _E_GRAPH_PROV_DO_NOT_ROTATE_METAFILES ); virtual ~EscherExGlobal(); /** Returns a new drawing ID for a new drawing container (DGCONTAINER). */ sal_uInt32 GenerateDrawingId(); /** Creates and returns a new shape identifier, updates the internal shape counters and registers the identifier in the DGG cluster table. @param nDrawingId Drawing identifier has to be passed to be able to generate shape identifiers for multiple drawings simultaniously. */ sal_uInt32 GenerateShapeId( sal_uInt32 nDrawingId, bool bIsInSpgr ); /** Returns the number of shapes in the current drawing, based on number of calls to the GenerateShapeId() function. */ sal_uInt32 GetDrawingShapeCount( sal_uInt32 nDrawingId ) const; /** Returns the last shape identifier generated by the GenerateShapeId() function. */ sal_uInt32 GetLastShapeId( sal_uInt32 nDrawingId ) const; /** Sets the flag indicating that the DGGCONTAINER exists. */ inline void SetDggContainer() { mbHasDggCont = true; } /** Sets the flag indicating that the DGGCONTAINER exists. */ inline bool HasDggContainer() const { return mbHasDggCont; } /** Returns the total size of the DGG atom (including header). */ sal_uInt32 GetDggAtomSize() const; /** Writes the complete DGG atom to the passed stream (overwrites existing data!). */ void WriteDggAtom( SvStream& rStrm ) const; /** Called if a picture shall be written and no picture stream is set at class ImplEscherExSdr. On first invokation, this function calls the virtual member function ImplQueryPictureStream(). The return value will be cached internally for subsequent calls and for the GetPictureStream() function. */ SvStream* QueryPictureStream(); /** Returns the picture stream if existing (queried), otherwise null. */ inline SvStream* GetPictureStream() { return mpPicStrm; } private: /** Derived classes may implement to create a new stream used to store the picture data. The implementation has to take care about lifetime of the returned stream (it will not be destructed automatically). This function is called exactly once. The return value will be cached internally for repeated calls of the public QueryPictureStream() function. */ virtual SvStream* ImplQueryPictureStream(); private: struct ClusterEntry { sal_uInt32 mnDrawingId; /// Identifier of drawing this cluster belongs to (one-based index into maDrawingInfos). sal_uInt32 mnNextShapeId; /// Next free shape identifier in this cluster. inline explicit ClusterEntry( sal_uInt32 nDrawingId ) : mnDrawingId( nDrawingId ), mnNextShapeId( 0 ) {} }; typedef ::std::vector< ClusterEntry > ClusterTable; struct DrawingInfo { sal_uInt32 mnClusterId; /// Currently used cluster (one-based index into maClusterTable). sal_uInt32 mnShapeCount; /// Current number of shapes in this drawing. sal_uInt32 mnLastShapeId; /// Last shape identifier generated for this drawing. inline explicit DrawingInfo( sal_uInt32 nClusterId ) : mnClusterId( nClusterId ), mnShapeCount( 0 ), mnLastShapeId( 0 ) {} }; typedef ::std::vector< DrawingInfo > DrawingInfoVector; ClusterTable maClusterTable; /// List with cluster IDs (used object IDs in drawings). DrawingInfoVector maDrawingInfos; /// Data about all used drawings. SvStream* mpPicStrm; /// Cached result of ImplQueryPictureStream(). bool mbHasDggCont; /// True = the DGGCONTAINER has been initialized. bool mbPicStrmQueried; /// True = ImplQueryPictureStream() has been called. }; typedef ::boost::shared_ptr< EscherExGlobal > EscherExGlobalRef; // --------------------------------------------------------------------------------------------- class SdrObject; class SdrPage; class ImplEscherExSdr; class MSFILTER_DLLPUBLIC EscherEx : public EscherPersistTable { protected: typedef ::std::auto_ptr< ImplEscherExSdr > ImplEscherExSdrPtr; EscherExGlobalRef mxGlobal; ImplEscherExSdrPtr mpImplEscherExSdr; SvStream* mpOutStrm; sal_uInt32 mnStrmStartOfs; std::vector< sal_uInt32 > mOffsets; std::vector< sal_uInt16 > mRecTypes; sal_uInt32 mnCurrentDg; sal_uInt32 mnCountOfs; sal_uInt32 mnGroupLevel; sal_uInt16 mnHellLayerId; sal_Bool mbEscherSpgr; sal_Bool mbEscherDg; sal_Bool mbOleEmf; // OLE is EMF instead of WMF virtual sal_Bool DoSeek( sal_uInt32 nKey ); public: explicit EscherEx( const EscherExGlobalRef& rxGlobal, SvStream& rOutStrm ); virtual ~EscherEx(); /** Creates and returns a new shape identifier, updates the internal shape counters and registers the identifier in the DGG cluster table. */ inline sal_uInt32 GenerateShapeId() { return mxGlobal->GenerateShapeId( mnCurrentDg, mbEscherSpgr ); } /** Returns the graphic provider from the global object that has been passed to the constructor. */ inline EscherGraphicProvider& GetGraphicProvider() { return *mxGlobal; } /** Called if a picture shall be written and no picture stream is set at class ImplEscherExSdr. */ inline SvStream* QueryPictureStream() { return mxGlobal->QueryPictureStream(); } /// Fuegt in den EscherStream interne Daten ein, dieser Vorgang /// darf und muss nur einmal ausgefuehrt werden. /// Wenn pPicStreamMergeBSE angegeben ist, werden die BLIPs /// aus diesem Stream in die MsofbtBSE Records des EscherStream /// gemerged, wie es fuer Excel (und Word?) benoetigt wird. virtual void Flush( SvStream* pPicStreamMergeBSE = NULL ); /** Inserts the passed number of bytes at the current position of the output stream. Inserts dummy bytes and moves all following stream data, and updates all internal stream offsets stored in the PersistTable and the affected container sizes, which makes this operation very expensive. (!) @param nBytes The number of bytes to be inserted into the stream. @param bExpandEndOfAtom If set to true, an atom that currently ends exactly at the current stream position will be expanded to include the inserted data. If set to false, an atom that currently ends exactly at the current stream position will not be expanded to include the inserted data (used to insert e.g. a new atom after an existing atom). Note that containers that end exactly at the current stream position are always expanded to include the inserted data. */ void InsertAtCurrentPos( sal_uInt32 nBytes, bool bExpandEndOfAtom ); void InsertPersistOffset( sal_uInt32 nKey, sal_uInt32 nOffset ); // Es wird nicht geprueft, ob sich jener schluessel schon in der PersistantTable befindet void ReplacePersistOffset( sal_uInt32 nKey, sal_uInt32 nOffset ); sal_uInt32 GetPersistOffset( sal_uInt32 nKey ); sal_Bool SeekToPersistOffset( sal_uInt32 nKey ); virtual sal_Bool InsertAtPersistOffset( sal_uInt32 nKey, sal_uInt32 nValue );// nValue wird im Stream an entrsprechender Stelle eingefuegt(overwrite modus), ohne dass sich die // aktuelle StreamPosition aendert SvStream& GetStream() const { return *mpOutStrm; } sal_uLong GetStreamPos() const { return mpOutStrm->Tell(); } virtual sal_Bool SeekBehindRecHeader( sal_uInt16 nRecType ); // der stream muss vor einem gueltigen Record Header oder Atom stehen // features beim erzeugen folgender Container: // // ESCHER_DggContainer: ein EscherDgg Atom wird automatisch erzeugt und verwaltet // ESCHER_DgContainer: ein EscherDg Atom wird automatisch erzeugt und verwaltet // ESCHER_SpgrContainer: // ESCHER_SpContainer: virtual void OpenContainer( sal_uInt16 nEscherContainer, int nRecInstance = 0 ); virtual void CloseContainer(); virtual void BeginAtom(); virtual void EndAtom( sal_uInt16 nRecType, int nRecVersion = 0, int nRecInstance = 0 ); virtual void AddAtom( sal_uInt32 nAtomSitze, sal_uInt16 nRecType, int nRecVersion = 0, int nRecInstance = 0 ); virtual void AddChildAnchor( const Rectangle& rRectangle ); virtual void AddClientAnchor( const Rectangle& rRectangle ); virtual sal_uInt32 EnterGroup( const String& rShapeName, const Rectangle* pBoundRect = 0 ); sal_uInt32 EnterGroup( const Rectangle* pBoundRect = NULL ); sal_uInt32 GetGroupLevel() const { return mnGroupLevel; }; virtual sal_Bool SetGroupSnapRect( sal_uInt32 nGroupLevel, const Rectangle& rRect ); virtual sal_Bool SetGroupLogicRect( sal_uInt32 nGroupLevel, const Rectangle& rRect ); virtual void LeaveGroup(); // ein ESCHER_Sp wird geschrieben ( Ein ESCHER_DgContainer muss dazu geoeffnet sein !!) virtual void AddShape( sal_uInt32 nShpInstance, sal_uInt32 nFlagIds, sal_uInt32 nShapeID = 0 ); virtual void Commit( EscherPropertyContainer& rProps, const Rectangle& rRect ); sal_uInt32 GetColor( const sal_uInt32 nColor, sal_Bool bSwap = sal_True ); sal_uInt32 GetColor( const Color& rColor, sal_Bool bSwap = sal_True ); // ...Sdr... implemented in eschesdo.cxx void AddSdrPage( const SdrPage& rPage ); void AddUnoShapes( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& rxShapes ); /// returns the ShapeID sal_uInt32 AddSdrObject( const SdrObject& rObj ); /// If objects are written through AddSdrObject the /// SolverContainer has to be written, and maybe some /// maintenance to be done. void EndSdrObjectPage(); /// Called before a shape is written, application supplies /// ClientRecords. May set AppData::bDontWriteShape so the /// shape is ignored. virtual EscherExHostAppData* StartShape( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& rShape, const Rectangle* pChildAnchor ); /// Called after a shape is written to inform the application /// of the resulted shape type and ID. virtual void EndShape( sal_uInt16 nShapeType, sal_uInt32 nShapeID ); /// Called before an AdditionalText EnterGroup occurs. /// The current shape will be written in three parts: /// a group shape, the shape itself, and an extra textbox shape. /// The complete flow is: /// StartShape sets HostData1. /// EnterAdditionalTextGroup sets HostData2, App may modify /// HostData1 and keep track of the change. /// The group shape is written with HostData2. /// Another StartShape with the same (!) object sets HostData3. /// The current shape is written with HostData3. /// EndShape is called for the current shape. /// Another StartShape with the same (!) object sets HostData4. /// The textbox shape is written with HostData4. /// EndShape is called for the textbox shape. /// EndShape is called for the group shape, this provides /// the same functionality as an ordinary recursive group. virtual EscherExHostAppData* EnterAdditionalTextGroup(); /// Called if an ESCHER_Prop_lTxid shall be written virtual sal_uInt32 QueryTextID( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >&, sal_uInt32 nShapeId ); // add an dummy rectangle shape into the escher stream sal_uInt32 AddDummyShape(); static const SdrObject* GetSdrObject( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& rXShape ); void SetHellLayerId( sal_uInt16 nId ) { mnHellLayerId = nId; } sal_uInt16 GetHellLayerId() const { return mnHellLayerId; } private: EscherEx( const EscherEx& ); EscherEx& operator=( const EscherEx& ); // prevent C-style cast to former base class EscherGraphicProvider operator EscherGraphicProvider&(); operator EscherGraphicProvider const&(); }; #endif
56.998149
228
0.60478
[ "geometry", "object", "shape", "vector", "model", "transform", "3d", "solid" ]
010a98298165b56c631307165deea9049bd04620
2,072
cc
C++
hologram_dashboard/server/request_handler/hologram_data_availability_reader.cc
googleinterns/sarahchen-intern-2020
6ca0891655b89221aa52ac4db104a80559f3701b
[ "Apache-2.0" ]
1
2020-06-04T23:10:54.000Z
2020-06-04T23:10:54.000Z
hologram_dashboard/server/request_handler/hologram_data_availability_reader.cc
googleinterns/sarahchen-intern-2020
6ca0891655b89221aa52ac4db104a80559f3701b
[ "Apache-2.0" ]
6
2020-05-29T18:46:35.000Z
2022-03-02T09:31:41.000Z
hologram_dashboard/server/request_handler/hologram_data_availability_reader.cc
googleinterns/sarahchen-intern-2020
6ca0891655b89221aa52ac4db104a80559f3701b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 "hologram_data_availability_reader.h" namespace wireless_android_play_analytics { HologramDataAvailabilityReader::HologramDataAvailabilityReader() { assert(!absl::GetFlag(FLAGS_database_root_path).empty()); std::string config_path = absl::StrCat(absl::GetFlag(FLAGS_database_root_path), "hologram_config.ascii"); Parse(config_path, &configs); } void HologramDataAvailabilityReader::Parse (absl::string_view path, google::protobuf::Message* message) { std::ifstream ins; ins.open(std::string(path)); google::protobuf::io::IstreamInputStream istream_input_stream(&ins); assert(google::protobuf::TextFormat::Parse(&istream_input_stream, message)); } std::vector<HologramDataAvailability> HologramDataAvailabilityReader:: GetAvailabilityInfo(absl::string_view system_dir) { std::vector<HologramDataAvailability> output( configs.data_source_config_size()); std::string protos_path = absl::StrCat(absl::GetFlag(FLAGS_database_root_path), system_dir); int output_index = 0; for (const HologramConfig& config : configs.data_source_config()) { // This simulates the second key (source type). std::string data_set_path = absl::StrCat(protos_path, SourceType_Name(config.source_type()), ".textproto"); Parse(data_set_path, &output[output_index++]); } return output; } } // namespace wireless_android_play_analytics
37
80
0.723938
[ "vector" ]
010df3c77996822c08f82b72727763385caf9ecd
14,090
hpp
C++
include/oglplus/ext/ARB_compatibility.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
364
2015-01-01T09:38:23.000Z
2022-03-22T05:32:00.000Z
include/oglplus/ext/ARB_compatibility.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
55
2015-01-06T16:42:55.000Z
2020-07-09T04:21:41.000Z
include/oglplus/ext/ARB_compatibility.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
57
2015-01-07T18:35:49.000Z
2022-03-22T05:32:04.000Z
/** * @file oglplus/ext/ARB_compatibility.hpp * @brief Wrapper for the ARB_compatibility extension * * @author Matus Chochlik * * Copyright 2010-2019 Matus Chochlik. 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) */ #pragma once #ifndef OGLPLUS_EXT_ARB_COMPATIBILITY_1203031902_HPP #define OGLPLUS_EXT_ARB_COMPATIBILITY_1203031902_HPP #include <oglplus/ext/ARB_compatibility/attrib_group.hpp> #include <oglplus/ext/ARB_compatibility/matrix_mode.hpp> #include <oglplus/ext/ARB_compatibility/primitive_type.hpp> #include <oglplus/extension.hpp> #include <oglplus/texture_unit.hpp> #include <oglplus/math/matrix.hpp> namespace oglplus { #if OGLPLUS_DOCUMENTATION_ONLY || GL_ARB_compatibility /// Wrapper for the ARB_compatibility extension /** * @glsymbols * @glextref{ARB,compatibility} * * @ingroup gl_extensions */ class ARB_compatibility { public: OGLPLUS_EXTENSION_CLASS(ARB, compatibility) /// Begins geometric object specification /** * @glsymbols * @glfunref{Begin} */ static void Begin(CompatibilityPrimitiveType mode) { OGLPLUS_GLFUNC(Begin)(GLenum(mode)); } /// Ends geometric object specification /** * @glsymbols * @glfunref{End} */ static void End() { OGLPLUS_GLFUNC(End)(); OGLPLUS_VERIFY_SIMPLE(End); } /// Pushes specified server attribute group variables on the stack /** * @glsymbols * @glfunref{PushAttrib} */ static void PushAttrib(Bitfield<CompatibilityAttributeGroup> attr_groups) { OGLPLUS_GLFUNC(PushAttrib)(GLbitfield(attr_groups)); OGLPLUS_VERIFY_SIMPLE(PushAttrib); } /// Pushes specified client attribute group variables on the stack /** * @glsymbols * @glfunref{PushClientAttrib} */ static void PushClientAttrib( Bitfield<CompatibilityClientAttributeGroup> attrib_groups) { OGLPLUS_GLFUNC(PushClientAttrib)(GLbitfield(attrib_groups)); OGLPLUS_VERIFY_SIMPLE(PushClientAttrib); } /// Pop previously pushed server attribute group variables from the stack /** * @glsymbols * @glfunref{PopAttrib} */ static void PopAttrib() { OGLPLUS_GLFUNC(PopAttrib)(); OGLPLUS_VERIFY_SIMPLE(PopAttrib); } /// Pop previously pushed client attribute group variables from the stack /** * @glsymbols * @glfunref{PopClientAttrib} */ static void PopClientAttrib() { OGLPLUS_GLFUNC(PopClientAttrib)(); OGLPLUS_VERIFY_SIMPLE(PopClientAttrib); } /// Sets the matrix mode for the subsequent commands /** * @glsymbols * @glfunref{MatrixMode} */ static void MatrixMode(CompatibilityMatrixMode mode) { OGLPLUS_GLFUNC(MatrixMode)(GLenum(mode)); OGLPLUS_VERIFY_SIMPLE(MatrixMode); } /// Loads a identity matrix /** * @glsymbols * @glfunref{LoadIdentity} */ static void LoadIdentity() { OGLPLUS_GLFUNC(LoadIdentity)(); OGLPLUS_VERIFY_SIMPLE(LoadIdentity); } /// Loads the specified @p matrix /** * @glsymbols * @glfunref{LoadMatrix} */ static void LoadMatrix(const Mat4f& matrix) { OGLPLUS_GLFUNC(LoadMatrixf)(Data(Transposed(matrix))); OGLPLUS_VERIFY_SIMPLE(LoadMatrixf); } /// Loads the specified @p matrix /** * @glsymbols * @glfunref{LoadMatrix} */ static void LoadMatrix(const Mat4d& matrix) { OGLPLUS_GLFUNC(LoadMatrixd)(Data(Transposed(matrix))); OGLPLUS_VERIFY_SIMPLE(LoadMatrixd); } private: static void Vertex_(GLint x, GLint y) { OGLPLUS_GLFUNC(Vertex2i)(x, y); } static void Vertex_(GLint x, GLint y, GLint z) { OGLPLUS_GLFUNC(Vertex3i)(x, y, z); } static void Vertex_(GLint x, GLint y, GLint z, GLint w) { OGLPLUS_GLFUNC(Vertex4i)(x, y, z, w); } static void Vertex_(GLfloat x, GLfloat y) { OGLPLUS_GLFUNC(Vertex2f)(x, y); } static void Vertex_(GLfloat x, GLfloat y, GLfloat z) { OGLPLUS_GLFUNC(Vertex3f)(x, y, z); } static void Vertex_(GLfloat x, GLfloat y, GLfloat z, GLfloat w) { OGLPLUS_GLFUNC(Vertex4f)(x, y, z, w); } static void Vertex_(GLdouble x, GLdouble y) { OGLPLUS_GLFUNC(Vertex2d)(x, y); } static void Vertex_(GLdouble x, GLdouble y, GLdouble z) { OGLPLUS_GLFUNC(Vertex3d)(x, y, z); } static void Vertex_(GLdouble x, GLdouble y, GLdouble z, GLdouble w) { OGLPLUS_GLFUNC(Vertex4d)(x, y, z, w); } public: /// Specifies vertex position x,y coordinates /** * @glsymbols * @glfunref{Vertex} */ template <typename Type> static void Vertex(Type x, Type y) { Vertex_(x, y); } /// Specifies vertex position x,y,z coordinates /** * @glsymbols * @glfunref{Vertex} */ template <typename Type> static void Vertex(Type x, Type y, Type z) { Vertex_(x, y, z); } /// Specifies vertex position x,y,z,w coordinates /** * @glsymbols * @glfunref{Vertex} */ template <typename Type> static void Vertex(Type x, Type y, Type z, Type w) { Vertex_(x, y, z, w); } private: static void TexCoord_(GLint s) { OGLPLUS_GLFUNC(TexCoord1i)(s); } static void TexCoord_(GLint s, GLint t) { OGLPLUS_GLFUNC(TexCoord2i)(s, t); } static void TexCoord_(GLint s, GLint t, GLint r) { OGLPLUS_GLFUNC(TexCoord3i)(s, t, r); } static void TexCoord_(GLint s, GLint t, GLint r, GLint q) { OGLPLUS_GLFUNC(TexCoord4i)(s, t, r, q); } static void TexCoord_(GLfloat s) { OGLPLUS_GLFUNC(TexCoord1f)(s); } static void TexCoord_(GLfloat s, GLfloat t) { OGLPLUS_GLFUNC(TexCoord2f)(s, t); } static void TexCoord_(GLfloat s, GLfloat t, GLfloat r) { OGLPLUS_GLFUNC(TexCoord3f)(s, t, r); } static void TexCoord_(GLfloat s, GLfloat t, GLfloat r, GLfloat q) { OGLPLUS_GLFUNC(TexCoord4f)(s, t, r, q); } static void TexCoord_(GLdouble s) { OGLPLUS_GLFUNC(TexCoord1d)(s); } static void TexCoord_(GLdouble s, GLdouble t) { OGLPLUS_GLFUNC(TexCoord2d)(s, t); } static void TexCoord_(GLdouble s, GLdouble t, GLdouble r) { OGLPLUS_GLFUNC(TexCoord3d)(s, t, r); } static void TexCoord_(GLdouble s, GLdouble t, GLdouble r, GLdouble q) { OGLPLUS_GLFUNC(TexCoord4d)(s, t, r, q); } public: /// Specifies vertex position s coordinate /** * @glsymbols * @glfunref{TexCoord} */ template <typename Type> static void TexCoord(Type s) { TexCoord_(s); } /// Specifies vertex position s,t coordinates /** * @glsymbols * @glfunref{TexCoord} */ template <typename Type> static void TexCoord(Type s, Type t) { TexCoord_(s, t); } /// Specifies vertex position s,t,r coordinates /** * @glsymbols * @glfunref{TexCoord} */ template <typename Type> static void TexCoord(Type s, Type t, Type r) { TexCoord_(s, t, r); } /// Specifies vertex position s,t,r,q coordinates /** * @glsymbols * @glfunref{TexCoord} */ template <typename Type> static void TexCoord(Type s, Type t, Type r, Type q) { TexCoord_(s, t, r, q); } private: static void MultiTexCoord_(GLenum tex_unit, GLint s) { OGLPLUS_GLFUNC(MultiTexCoord1i)(tex_unit, s); } static void MultiTexCoord_(GLenum tex_unit, GLint s, GLint t) { OGLPLUS_GLFUNC(MultiTexCoord2i)(tex_unit, s, t); } static void MultiTexCoord_(GLenum tex_unit, GLint s, GLint t, GLint r) { OGLPLUS_GLFUNC(MultiTexCoord3i)(tex_unit, s, t, r); } static void MultiTexCoord_( GLenum tex_unit, GLint s, GLint t, GLint r, GLint q) { OGLPLUS_GLFUNC(MultiTexCoord4i)(tex_unit, s, t, r, q); } static void MultiTexCoord_(GLenum tex_unit, GLfloat s) { OGLPLUS_GLFUNC(MultiTexCoord1f)(tex_unit, s); } static void MultiTexCoord_(GLenum tex_unit, GLfloat s, GLfloat t) { OGLPLUS_GLFUNC(MultiTexCoord2f)(tex_unit, s, t); } static void MultiTexCoord_( GLenum tex_unit, GLfloat s, GLfloat t, GLfloat r) { OGLPLUS_GLFUNC(MultiTexCoord3f)(tex_unit, s, t, r); } static void MultiTexCoord_( GLenum tex_unit, GLfloat s, GLfloat t, GLfloat r, GLfloat q) { OGLPLUS_GLFUNC(MultiTexCoord4f)(tex_unit, s, t, r, q); } static void MultiTexCoord_(GLenum tex_unit, GLdouble s) { OGLPLUS_GLFUNC(MultiTexCoord1d)(tex_unit, s); } static void MultiTexCoord_(GLenum tex_unit, GLdouble s, GLdouble t) { OGLPLUS_GLFUNC(MultiTexCoord2d)(tex_unit, s, t); } static void MultiTexCoord_( GLenum tex_unit, GLdouble s, GLdouble t, GLdouble r) { OGLPLUS_GLFUNC(MultiTexCoord3d)(tex_unit, s, t, r); } static void MultiTexCoord_( GLenum tex_unit, GLdouble s, GLdouble t, GLdouble r, GLdouble q) { OGLPLUS_GLFUNC(MultiTexCoord4d)(tex_unit, s, t, r, q); } public: /// Specifies vertex position s coordinate /** * @glsymbols * @glfunref{MultiTexCoord} */ template <typename Type> static void MultiTexCoord(TextureUnitSelector tex_unit, Type s) { MultiTexCoord_(GLenum(GL_TEXTURE0 + GLuint(tex_unit)), s); } /// Specifies vertex position s,t coordinates /** * @glsymbols * @glfunref{MultiTexCoord} */ template <typename Type> static void MultiTexCoord(TextureUnitSelector tex_unit, Type s, Type t) { MultiTexCoord_(GLenum(GL_TEXTURE0 + GLuint(tex_unit)), s, t); } /// Specifies vertex position s,t,r coordinates /** * @glsymbols * @glfunref{MultiTexCoord} */ template <typename Type> static void MultiTexCoord( TextureUnitSelector tex_unit, Type s, Type t, Type r) { MultiTexCoord_(GLenum(GL_TEXTURE0 + GLuint(tex_unit)), s, t, r); } /// Specifies vertex position s,t,r,q coordinates /** * @glsymbols * @glfunref{MultiTexCoord} */ template <typename Type> static void MultiTexCoord( TextureUnitSelector tex_unit, Type s, Type t, Type r, Type q) { MultiTexCoord_(GLenum(GL_TEXTURE0 + GLuint(tex_unit)), s, t, r, q); } private: static void Normal_(GLint x, GLint y, GLint z) { OGLPLUS_GLFUNC(Normal3i)(x, y, z); } static void Normal_(GLfloat x, GLfloat y, GLfloat z) { OGLPLUS_GLFUNC(Normal3f)(x, y, z); } static void Normal_(GLdouble x, GLdouble y, GLdouble z) { OGLPLUS_GLFUNC(Normal3d)(x, y, z); } public: /// Specifies vertex x,y,z normal components /** * @glsymbols * @glfunref{Normal} */ template <typename Type> static void Normal(Type x, Type y, Type z) { Normal_(x, y, z); } private: static void FogCoord_(GLfloat c) { OGLPLUS_GLFUNC(FogCoordf)(c); } static void FogCoord_(GLdouble c) { OGLPLUS_GLFUNC(FogCoordd)(c); } public: /// Specifies vertex coordinates /** * @glsymbols * @glfunref{FogCoord} */ template <typename Type> static void FogCoord(Type c) { FogCoord_(c); } private: static void Color_(GLubyte r, GLubyte g, GLubyte b) { OGLPLUS_GLFUNC(Color3ub)(r, g, b); } static void Color_(GLubyte r, GLubyte g, GLubyte b, GLubyte a) { OGLPLUS_GLFUNC(Color4ub)(r, g, b, a); } static void Color_(GLint r, GLint g, GLint b) { OGLPLUS_GLFUNC(Color3i)(r, g, b); } static void Color_(GLint r, GLint g, GLint b, GLint a) { OGLPLUS_GLFUNC(Color4i)(r, g, b, a); } static void Color_(GLfloat r, GLfloat g, GLfloat b) { OGLPLUS_GLFUNC(Color3f)(r, g, b); } static void Color_(GLfloat r, GLfloat g, GLfloat b, GLfloat a) { OGLPLUS_GLFUNC(Color4f)(r, g, b, a); } static void Color_(GLdouble r, GLdouble g, GLdouble b) { OGLPLUS_GLFUNC(Color3d)(r, g, b); } static void Color_(GLdouble r, GLdouble g, GLdouble b, GLdouble a) { OGLPLUS_GLFUNC(Color4d)(r, g, b, a); } public: /// Specifies vertex r,g,b color components /** * @glsymbols * @glfunref{Color} */ template <typename Type> static void Color(Type r, Type g, Type b) { Color_(r, g, b); } /// Specifies vertex r,g,b,a color components /** * @glsymbols * @glfunref{Color} */ template <typename Type> static void Color(Type r, Type g, Type b, Type a) { Color_(r, g, b, a); } private: static void SColor_(GLubyte r, GLubyte g, GLubyte b) { OGLPLUS_GLFUNC(SecondaryColor3ub)(r, g, b); } static void SColor_(GLint r, GLint g, GLint b) { OGLPLUS_GLFUNC(SecondaryColor3i)(r, g, b); } static void SColor_(GLfloat r, GLfloat g, GLfloat b) { OGLPLUS_GLFUNC(SecondaryColor3f)(r, g, b); } static void SColor_(GLdouble r, GLdouble g, GLdouble b) { OGLPLUS_GLFUNC(SecondaryColor3d)(r, g, b); } public: /// Specifies vertex r,g,b secondary color components /** * @glsymbols * @glfunref{SecondaryColor} */ template <typename Type> static void SecondaryColor(Type r, Type g, Type b) { SColor_(r, g, b); } private: static void Index_(GLint i) { OGLPLUS_GLFUNC(Indexi)(i); } static void Index_(GLfloat i) { OGLPLUS_GLFUNC(Indexf)(i); } static void Index_(GLdouble i) { OGLPLUS_GLFUNC(Indexd)(i); } public: /// Specifies vertex coordinates /** * @glsymbols * @glfunref{Index} */ template <typename Type> static void Index(Type i) { Index_(i); } }; #endif } // namespace oglplus #endif // include guard
25.711679
79
0.622356
[ "object" ]
011bba3cf3e7225537447196d1aaaaf7556b6d2e
11,643
cpp
C++
src/ofApp.cpp
JesseScott/Decanter
c9c205282d2af11de395237ba8b5b19af0466b0b
[ "MIT" ]
1
2017-10-25T17:42:33.000Z
2017-10-25T17:42:33.000Z
src/ofApp.cpp
JesseScott/Decanter
c9c205282d2af11de395237ba8b5b19af0466b0b
[ "MIT" ]
null
null
null
src/ofApp.cpp
JesseScott/Decanter
c9c205282d2af11de395237ba8b5b19af0466b0b
[ "MIT" ]
null
null
null
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { // Screen ofSetWindowTitle("beeeeeeeer"); ofBackground(255); // Font mainFont.loadFont("font/Ostrich.ttf", 40); subFont.loadFont("font/Ostrich.ttf", 25); // Misc verbose = false; cellWidth = 480; cellHeight = 360; // Camera camWidth = 640; camHeight = 480; nearBeer = 160; farBeer = 320; cropWidth = camWidth/2; cropOffset = nearBeer; lineCounter = 0; tmpR = 0; tmpG = 0; tmpB = 0; vector<ofVideoDevice> devices = camera.listDevices(); if(verbose) { for(int i = 0; i < devices.size(); i++){ cout << devices[i].id << ": " << devices[i].deviceName; if( devices[i].bAvailable ){ cout << endl; } else { cout << " - unavailable " << endl; } } } camera.setDeviceID(0); camera.setDesiredFrameRate(60); camera.setVerbose(true); camera.initGrabber(camWidth, camHeight); croppedCamera.allocate(cropWidth, camHeight, OF_IMAGE_COLOR_ALPHA); // Audio int bufferSize = 256; left.assign(bufferSize, 0.0); right.assign(bufferSize, 0.0); volHistory.assign(camWidth, 0.0); bufferCounter = 0; drawCounter = 0; smoothedVol = 0.0; scaledVol = 0.0; soundStream.setup(this, 0, 2, 44100, bufferSize, 4); soundStream.start(); // FBOs averageLines.allocate(camWidth, camHeight, GL_RGBA); averageLines.begin(); ofClear(255,255,255, 0); averageLines.end(); sortedLines.allocate(camWidth, camHeight, GL_RGBA); sortedLines.begin(); ofClear(255,255,255, 0); sortedLines.end(); dataSet.allocate(camWidth, camHeight, GL_RGBA); dataSet.begin(); ofClear(255,255,255, 0); dataSet.end(); interpretivePanel.allocate(camWidth, camHeight, GL_RGBA); interpretivePanel.begin(); ofClear(255,255,255, 0); interpretivePanel.end(); audioFbo.allocate(camWidth, camHeight, GL_RGBA); audioFbo.begin(); ofClear(255,255,255, 0); audioFbo.end(); drawAvgLines = true; // Syphon mainOutputSyphonServer.setName("Screen Output"); individualTextureSyphonServer.setName("Texture Output"); mClient.setup(); mClient.set("","Simple Server"); tex.allocate(camWidth, camHeight, GL_RGBA); pixelArray.allocate(camWidth, camHeight, OF_PIXELS_RGBA); colorPixels = new unsigned char[640*480*4]; cout << " -- END OF SETUP -- " << endl; } //-------------------------------------------------------------- void ofApp::update() { // Camera camera.update(); if (camera.isFrameNew()){ // Get Camera Pixels cameraPixels = camera.getPixels(); // Pull Cam Pix & Crop tmpCamera.setFromPixels(cameraPixels, camWidth, camHeight, OF_IMAGE_COLOR); croppedCamera.setFromPixels(tmpCamera); croppedCamera.crop(cropOffset, 0, camWidth - cropWidth, camHeight); croppedCamera.resize(camWidth, camHeight); // Set CameraPix from Cropped Image cameraPixels = croppedCamera.getPixels(); int totalPixels = camWidth * camHeight; lineCounter = 0; bool startAdding = false; // Get Average Colours for (int i = 0; i < totalPixels; i++) { // Adding Colors tmpR += cameraPixels[i*3]; tmpG += cameraPixels[i*3+1]; tmpB += cameraPixels[i*3+2]; // Store Color if(i % camWidth == 0) { // get the average value tmpR = tmpR / camWidth; tmpG = tmpG / camWidth; tmpB = tmpB / camWidth; // Set Avg Colours To Color Array lineColors[lineCounter].r = tmpR; lineColors[lineCounter].g = tmpG; lineColors[lineCounter].b = tmpB; // Add Averages tmpR += tmpR; tmpG += tmpG; tmpB += tmpB; // Set Block Averages if(lineCounter % 10 == 0) { blockColors[lineCounter/10].r = tmpR; blockColors[lineCounter/10].g = tmpG; blockColors[lineCounter/10].b = tmpB; } // Reset Temp Colors tmpR = 0; tmpG = 0; tmpB = 0; // Iterate lineCounter++; } } // Audio scaledVol = ofMap(smoothedVol, 0.0, 0.17, 0.0, 1.0, true); volHistory.push_back( scaledVol ); if( volHistory.size() >= 400 ){ volHistory.erase(volHistory.begin(), volHistory.begin()+1); } // Draw FBOs averageLines.begin(); ofClear(128, 128, 128, 255); for(int i = 0; i < camHeight; i++) { ofSetColor(lineColors[i]); ofLine(0, i, camWidth, i); } averageLines.end(); sortedLines.begin(); ofClear(128, 128, 128, 255); for(int i = 0; i < camHeight/10; i++) { ofSetColor(blockColors[i]); ofRect(0, -10 + i*10, camWidth, -10 + i*10); } sortedLines.end(); dataSet.begin(); ofClear(0, 0, 0, 5); ofSetBackgroundColor(0); for(int i = 0; i < camHeight; i++) { if(i % 10 == 0) { ofSetColor(lineColors[i].r, 0, 0); char r = lineColors[i].r; mainFont.drawString(ofToString(r), (i*2) + 15, lineCounter/5); ofSetColor(0, lineColors[i].g, 0); char g = lineColors[i].g; mainFont.drawString(ofToString(g), (i*2) + 15, 150 + lineCounter/5); ofSetColor(0, 0, lineColors[i].b); char b = lineColors[i].b; mainFont.drawString(ofToString(b), (i*2) + 15, 300 + lineCounter/5); } } dataSet.end(); interpretivePanel.begin(); ofClear(0, 0, 0, 255); ofSetBackgroundColor(0); ofSetColor(255); string title = "DECANTER"; mainFont.drawString(title, camWidth/2 - 85, camHeight/2 - 50); ofSetColor(200); string subtitle = "- a generative audio alcoholic experience -"; subFont.drawString(subtitle, camWidth/4 - 75, camHeight/2); interpretivePanel.end(); audioFbo.begin(); ofClear(0, 0, 0, 255); ofSetLineWidth(3); ofSetColor(245, 58, 135); ofBeginShape(); for (unsigned int i = 0; i < left.size(); i++){ ofVertex(i*3, 100 -left[i]*180.0f); } ofEndShape(false); ofBeginShape(); for (unsigned int i = 0; i < right.size(); i++){ ofVertex(i*3, 200 -right[i]*180.0f); } ofEndShape(false); ofBeginShape(); for (unsigned int i = 0; i < volHistory.size(); i++){ if( i == 0 ) ofVertex(i, camHeight); ofVertex(i, camHeight - volHistory[i] * 150); if( i == volHistory.size() -1 ) ofVertex(i, camHeight); } ofEndShape(false); audioFbo.end(); // Texture For Syphon if(drawAvgLines) { averageLines.readToPixels(pixelArray); } else { sortedLines.readToPixels(pixelArray); } colorPixels = pixelArray.getPixels(); tex.loadData(colorPixels, 640, 480, GL_RGBA); } } //-------------------------------------------------------------- void ofApp::draw() { // Raw Camera ofSetColor(255); camera.draw(0, 0, cellWidth, cellHeight); // 0, 0 || TL // Average Colour Lines ofSetColor(255); averageLines.draw(cellWidth, 0, cellWidth, cellHeight); // 0, 0 || TC // Sorted Colour Lines ofSetColor(255); sortedLines.draw(cellWidth*2, 0, cellWidth, cellHeight); // 960, 0 || TR // Data Set ofSetColor(255); //dataSet.draw(0, cellHeight, cellWidth, cellHeight); // 0, 360 || ML // Interpretive Text ofSetColor(255); interpretivePanel.draw(cellWidth, cellHeight, cellWidth, cellHeight); // 360, 360 || MC // Audio Waverform audioFbo.draw(cellWidth*2, cellHeight, cellWidth, cellHeight); // Cropped Camera croppedCamera.draw(0, cellHeight, cellWidth, cellHeight); // 0, 360 || ML // Texture //tex.draw(cellWidth, cellHeight, cellWidth, cellHeight); // 480, 360 || MC // ofSetColor(255, 0, 0); // ofLine(ofGetWidth()/2, 0, ofGetWidth()/2, 720); // Syphon mainOutputSyphonServer.publishScreen(); individualTextureSyphonServer.publishTexture(&tex); // Debug if(verbose) { ofSetColor(0); char fpsStr[255]; sprintf(fpsStr, "frame rate: %f", ofGetFrameRate()); ofDrawBitmapString(fpsStr, 50, ofGetWindowHeight() - 50); } } //-------------------------------------------------------------- void ofApp::audioIn(float * input, int bufferSize, int nChannels){ float curVol = 0.0; int numCounted = 0; for (int i = 0; i < bufferSize; i++){ left[i] = input[i*2]*0.5; right[i] = input[i*2+1]*0.5; curVol += left[i] * left[i]; curVol += right[i] * right[i]; numCounted+=2; } curVol /= (float)numCounted; curVol = sqrt( curVol ); smoothedVol *= 0.93; smoothedVol += 0.07 * curVol; bufferCounter++; } //-------------------------------------------------------------- void ofApp::exit() { ofLogNotice("Exiting App"); // Close Camera camera.close(); // Close Audio soundStream.stop(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ // Camera Settings if (key == 's' || key == 'S') { camera.videoSettings(); //ofSaveFrame(); } // FBO -> Syphon if (key == 'f' || key == 'F') { drawAvgLines = !drawAvgLines; cout << "DAL = " << ofToString(drawAvgLines) << endl; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
27.459906
93
0.478485
[ "vector" ]
012528ab308e82ca6467d2420519e38391104c49
2,079
cpp
C++
boost_example/IoContextPool.cpp
1261385937/beast_example
88bade87f25a8ebcfe8e6f68825a055959ac720a
[ "MIT" ]
1
2019-04-25T04:59:22.000Z
2019-04-25T04:59:22.000Z
boost_example/IoContextPool.cpp
1261385937/beast_example
88bade87f25a8ebcfe8e6f68825a055959ac720a
[ "MIT" ]
null
null
null
boost_example/IoContextPool.cpp
1261385937/beast_example
88bade87f25a8ebcfe8e6f68825a055959ac720a
[ "MIT" ]
null
null
null
#include "IoContextPool.h" #include <vector> #include <thread> #include "boost/asio/io_context.hpp" #include "log.h" struct dividend::IoContextPool::Impl { std::vector<std::unique_ptr<std::thread>> thread_vec; std::vector<std::unique_ptr<boost::asio::io_context>> io_context_vec; std::vector<std::unique_ptr<boost::asio::io_context::work>> work_vec; //keep io_context.run() alive }; dividend::IoContextPool::IoContextPool(int pool_size) : io_context_index_(0) , impl_(std::make_unique<Impl>()) { for (int i = 0; i < pool_size; ++i) { auto io_context_ptr = std::make_unique<boost::asio::io_context>(); auto work_ptr = std::make_unique<boost::asio::io_context::work>(*io_context_ptr); impl_->io_context_vec.emplace_back(std::move(io_context_ptr)); impl_->work_vec.emplace_back(std::move(work_ptr)); } } dividend::IoContextPool::~IoContextPool() = default; void dividend::IoContextPool::start() { auto size = impl_->io_context_vec.size(); for (auto i = 0; i < static_cast<int>(size); ++i) { auto thread_ptr = std::make_unique<std::thread>([self = shared_from_this(), this, i]() { try { impl_->io_context_vec[i]->run(); } catch (std::exception& e) { SPDLOG_ERROR("io_service thread exit with {}", e.what()); } catch (...) { SPDLOG_ERROR("io_service thread exit with unknown exception\n"); } }); impl_->thread_vec.emplace_back(std::move(thread_ptr)); } } void dividend::IoContextPool::stop() { auto work_vec_size = impl_->work_vec.size(); for (auto i = 0; i < static_cast<int>(work_vec_size); ++i) { //work_vec_[i]->~work(); impl_->work_vec[i].reset(); } auto size = impl_->thread_vec.size(); for (int i = 0; i < static_cast<int>(size); ++i) { if (impl_->thread_vec[i]->joinable()) impl_->thread_vec[i]->join(); } } boost::asio::io_context& dividend::IoContextPool::get_io_context() { auto& io_context = *(impl_->io_context_vec[io_context_index_]); ++io_context_index_; if (io_context_index_ == static_cast<int>(impl_->io_context_vec.size())) io_context_index_ = 0; return io_context; }
26.653846
100
0.686388
[ "vector" ]
0126c93cc8163da5f5c373e5d16bce976317516e
2,100
cpp
C++
answers/Google code jam/Round A China New Grad Test 2014 Problem B. Rational Number Tree.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
3
2015-09-04T21:32:31.000Z
2020-12-06T00:37:32.000Z
answers/Google code jam/Round A China New Grad Test 2014 Problem B. Rational Number Tree.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
null
null
null
answers/Google code jam/Round A China New Grad Test 2014 Problem B. Rational Number Tree.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
null
null
null
// #define _FILE_DEBUG_ //#define _C_LAN_ //#define _DEBUG_OUTPUT_ #ifdef _FILE_DEBUG_ #include <fstream> #endif #include <iostream> #include <stdio.h> using namespace std; #include <vector> #include <queue> #include <algorithm> int main(int argc, char *argv[]) { #ifdef _FILE_DEBUG_ ifstream fin; fin.open("../input.txt"); cin.rdbuf(fin.rdbuf()); #ifdef _C_LAN_ freopen("../input.txt", "r", stdin); #endif #endif #ifdef _FILE_DEBUG_ ofstream fout; fout.open("../output.txt"); cout.rdbuf(fout.rdbuf()); #ifdef _C_LAN_ freopen("../output.txt", "w", stdout); #endif #endif std::vector<std::pair<long long, long long> > pair_list; std::queue<std::pair<long long, long long> > pair_queue; std::pair<long long, long long> p(1, 1); pair_queue.push(p); pair_list.push_back(p); while (! pair_queue.empty() && pair_list.size() < 1048576) { p = pair_queue.front(); pair_queue.pop(); std::pair<long long, long long> tmp(p.first, p.first + p.second); pair_list.push_back(tmp); pair_queue.push(tmp); tmp = std::make_pair(p.first + p.second, p.second); pair_list.push_back(tmp); pair_queue.push(tmp); } int case_num; std::cin >> case_num; for (int i = 0; i < case_num; ++ i) { int type; std::cin >> type; long long num0, num1; std::vector<std::pair<long long, long long> >::iterator it; std::cout << "Case #" << i + 1 << ": "; switch (type) { case 1: std::cin >> num0; -- num0; if (num0 < pair_list.size()) { std::cout << pair_list[num0].first << " " << pair_list[num0].second << std::endl; } else { std::cout << "error0" << std::endl; } break; case 2: std::cin >> num0 >> num1; p = std::make_pair(num0, num1); it = std::find(pair_list.begin(), pair_list.end(), p); if (it != pair_list.end()) { std::cout << std::distance(pair_list.begin(), it) + 1 << std::endl; } else { std::cout << "error1" << std::endl; } break; default: std::cout << "error3" << std::endl; break; } } return 0; }
22.580645
86
0.587619
[ "vector" ]
012c59e2a7c24470a093b88446789716623158c1
3,216
hpp
C++
smacc2_sm_reference_library/sm_aws_warehouse_navigation/include/sm_aws_warehouse_navigation/states/st_acquire_sensors.hpp
reelrbtx/SMACC2
ac61cb1599f215fd9f0927247596796fc53f82bf
[ "Apache-2.0" ]
48
2021-05-28T01:33:20.000Z
2022-03-24T03:16:03.000Z
smacc2_sm_reference_library/sm_aws_warehouse_navigation/include/sm_aws_warehouse_navigation/states/st_acquire_sensors.hpp
reelrbtx/SMACC2
ac61cb1599f215fd9f0927247596796fc53f82bf
[ "Apache-2.0" ]
75
2021-06-25T22:11:21.000Z
2022-03-30T13:05:38.000Z
smacc2_sm_reference_library/sm_aws_warehouse_navigation/include/sm_aws_warehouse_navigation/states/st_acquire_sensors.hpp
reelrbtx/SMACC2
ac61cb1599f215fd9f0927247596796fc53f82bf
[ "Apache-2.0" ]
14
2021-06-16T12:10:57.000Z
2022-03-01T18:23:27.000Z
// Copyright 2021 RobosoftAI Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <smacc2/smacc.hpp> using namespace std::chrono_literals; namespace sm_aws_warehouse_navigation { // STATE DECLARATION struct StAcquireSensors : smacc2::SmaccState<StAcquireSensors, SmAwsWarehouseNavigation> { using SmaccState::SmaccState; // TRANSITION TABLE typedef mpl::list< // Transition<EvCbSuccess<CbWaitNav2Nodes, OrNavigation>, StInitialNavigateForward, SUCCESS> // , Transition<EvActionAborted<ClNav2Z, OrNavigation>, StAcquireSensors, ABORT> Transition<EvCbSuccess<CbWaitTransform, OrNavigation>, StStartNavigation, SUCCESS> > reactions; cl_nav2z::Amcl * amcl_; // STATE FUNCTIONS static void staticConfigure() { configure_orthogonal<OrNavigation, CbWaitTransform>("odom", "map", rclcpp::Duration(30000s)); //configure_orthogonal<OrNavigation, CbWaitPose>(); // configure_orthogonal<OrNavigation, CbWaitActionServer>(std::chrono::milliseconds(10000)); // configure_orthogonal<OrNavigation, CbWaitNav2Nodes>(std::vector<Nav2Nodes>{ // Nav2Nodes::PlannerServer, Nav2Nodes::ControllerServer, Nav2Nodes::BtNavigator}); } void runtimeConfigure() { // illegal wait workaround // rclcpp::sleep_for(6s); // ClNav2Z * navClient; // getOrthogonal<OrNavigation>()->requiresClient(navClient); // amcl_ = navClient->getComponent<Amcl>(); } void onEntry() { //sendInitialPoseEstimation(); //auto res = exec("ros2"); //RCLCPP_INFO(getLogger(), "launch result: %s", res.c_str()); } void sendInitialPoseEstimation() { geometry_msgs::msg::PoseWithCovarianceStamped initialposemsg; //bool useSimTime = getNode()->get_parameter("use_sim_time").as_bool(); //getNode()->set_parameter("use_sim_time",true); initialposemsg.header.stamp = getNode()->now(); initialposemsg.header.frame_id = "map"; initialposemsg.pose.pose.position.x = 3.415412425994873; initialposemsg.pose.pose.position.y = 2.0; initialposemsg.pose.pose.position.z = 0; initialposemsg.pose.pose.orientation.x = 0; initialposemsg.pose.pose.orientation.y = 0; initialposemsg.pose.pose.orientation.z = 1; initialposemsg.pose.pose.orientation.w = 0; //z: 0.9999985465626609 // w: 0.00170495529732811 initialposemsg.pose.covariance = { 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.06853891909122467}; amcl_->setInitialPose(initialposemsg); } void onExit() {} }; } // namespace sm_aws_warehouse_navigation
32.16
97
0.703669
[ "vector" ]
0130e44a88cd9ff1096ebabaceb41d04710e0432
3,632
hpp
C++
include/muse_smc/smc/traits/hypothesis.hpp
doge-of-the-day/muse_smc
a44a8840571639a99826408a43b29d7f74d8739b
[ "BSD-3-Clause" ]
1
2020-12-10T10:51:28.000Z
2020-12-10T10:51:28.000Z
include/muse_smc/smc/traits/hypothesis.hpp
doge-of-the-day/muse_smc
a44a8840571639a99826408a43b29d7f74d8739b
[ "BSD-3-Clause" ]
null
null
null
include/muse_smc/smc/traits/hypothesis.hpp
doge-of-the-day/muse_smc
a44a8840571639a99826408a43b29d7f74d8739b
[ "BSD-3-Clause" ]
2
2019-11-07T02:02:05.000Z
2021-06-21T09:12:03.000Z
#ifndef MUSE_SMC_TRAITS_HYPOTHESIS_HPP #define MUSE_SMC_TRAITS_HYPOTHESIS_HPP #include <type_traits> namespace muse_smc { namespace traits { /** * @brief Defines the data type the filter is working with. * @tparam Hypothesis_T sample type to set the trait for */ template <typename Hypothesis_T> struct Data { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); }; /** * @brief Defines the data provider type the filter is working with. * @tparam Hypothesis_T sample type to set the trait for */ template <typename Hypothesis_T> struct DataProvider { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); }; /** * @brief Defines the state type the filter is working with. * @tparam Hypothesis_T sample type to set the trait for */ template <typename Hypothesis_T> struct State { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); }; template <typename Hypothesis_T> struct StateAccess { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); // static inline State<Hypothesis_T>::type & get(Hypothesis_T &h); // static inline State<Hypothesis_T>::type const & get(const Hypothesis_T &h); }; /** * @brief Defines the transform type the filter is working with. * @tparam Hypothesis_T sample type to set the trait for */ template <typename Hypothesis_T> struct Transform { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); }; /** * @brief Defines the covariance type the filter is working with. * @tparam Hypothesis_T sample type to set the trait for */ template <typename Hypothesis_T> struct Covariance { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); }; /** * @brief Defines the state space boundary type the filter is working with. * @tparam Hypothesis_T sample type to set the trait for */ template <typename Hypothesis_T> struct StateSpaceBoundary { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); }; template <typename Hypothesis_T> struct Time { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); }; template <typename Hypothesis_T> struct TimeFrame { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); }; template <typename Hypothesis_T> struct Duration { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); }; template <typename Hypothesis_T> struct Rate { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); }; template <typename Hypothesis_T> struct Weight { static_assert(!std::is_same<Hypothesis_T, Hypothesis_T>::value, "Trait not overriden for sample type. Please define field type."); }; } // namespace traits } // namespace muse_smc #endif // MUSE_SMC_HYPOTHESIS_TRAITS_HPP
33.943925
82
0.718337
[ "transform" ]
01341e372e809fb9d48c50841b911db5f756909a
6,687
cpp
C++
fizzbuzz/fizzbuzz.cpp
uxvworks/code_tests
8e64a399a2785fa14968ce2a722513e9f937a5d5
[ "MIT" ]
null
null
null
fizzbuzz/fizzbuzz.cpp
uxvworks/code_tests
8e64a399a2785fa14968ce2a722513e9f937a5d5
[ "MIT" ]
null
null
null
fizzbuzz/fizzbuzz.cpp
uxvworks/code_tests
8e64a399a2785fa14968ce2a722513e9f937a5d5
[ "MIT" ]
null
null
null
// // Copyright (C) 2016 Phillip Yeager // Contact: Phillip Yeager <uxv.works@gmail.com> // // 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. // #include <algorithm> #include <cmath> #include <ctime> #include <iostream> #include <vector> #define TTMATH_DONT_USE_WCHAR #include "ttmath/ttmath.h" // A program to generate the first n Fibonacci numbers F(n), printing... // "Buzz" when F(n) is divisible by 3. // "Fizz" when F(n) is divisible by 5. // "BuzzFizz" when F(n) is prime. // Value F(n) otherwise. // NOTE on TTMath BigNum support: // To make FizzBuzz more fun, the program uses TTMath. // TTMath is a small library which allows one to perform arithmetic // operations with big unsigned integers, among other things. // TTMath is developed under the BSD license which means that it is // free for both personal and commercial use. // It does not need to be compiled first because the whole library // is written as C++ templates. // For more information see http://www.ttmath.org // MY_UINT_BITS defines the TTMath operand size used in FizzBuzz // This controls how big you can go with FizzBuzz // The supported number of decimal digits can be estimated with // digits = floor(MY_UINT_BITS*(log10(2.0))); // Some tested examples and resulting Fibonacci index: // 64 --->> n < 93 // 1024 --->> n < 1,476 // 8192 --->> n < 11,801 // 32768 --->> n < 47,201 // 1024*64 --->> n < 94,401 // 8192*64 --->> n < 755,196 #define MY_UINT_BITS 8192 // NOTE about TTMATH_BITS(x) // on a 32bit platform the macro returns 4 (4*32=128) // on a 64bit platform the macro returns 2 (2*64=128) typedef ttmath::UInt<TTMATH_BITS(MY_UINT_BITS)> mUint_t; // Table of Indexes of known Fibonacci Primes from // http://oeis.org/A001605 // Some of the larger entries may only correspond to probable primes. static const uint32_t FiboPrimes[] = { 3,4,5,7,11,13,17,23,29,43,47,83,131,137,359,431, 433,449,509,569,571,2971,4723,5387,9311,9677, 14431,25561,30757,35999,37511,50833,81839,104911, 130021,148091,201107,397379,433781,590041,593689, 604711,931517,1049897,1285607,1636007,1803059, 1968721,2904353 }; std::vector<uint32_t> FPvec (FiboPrimes, FiboPrimes + sizeof(FiboPrimes) / sizeof(FiboPrimes[0]) ); // is_FiboPrime() accepts the index of a Fibonacci number and returns // whether it is prime or not. It does this by checking a fairly // small table of known Fibonacci Prime Indices. // This may appear to be cheating, however it's justified over the alternative // because of electricity savings, time savings and simplicity of the code. // In any event, the instructions asked to "generate" only Fibonacci numbers... bool is_FiboPrime(uint32_t n) { bool exists = std::binary_search (FPvec.begin(), FPvec.end(), n); return (exists); } // spit_fuzz() accepts a Fibonacci number (num) and its index (n) // and spits out the required console verbage. // One of the steps involved is to do a Prime number check. // Verbage can be disabled with p_en=false void spit_fizz(uint32_t n, const mUint_t& num, bool p_en=true) { bool empty_line = true; // TODO: Confirm that the index shall be displayed. // Hard to follow output without including it... if (p_en) std::cout << n << " "; if ((num%3) == 0) { if (p_en) std::cout << "Buzz "; empty_line = false; } if ((num%5) == 0) { if (p_en) std::cout << "Fizz "; empty_line = false; } if (empty_line && is_FiboPrime(n)) { if (p_en) std::cout << "BuzzFizz!! "; empty_line = false; } if (empty_line) { if (p_en) std::cout << num; empty_line = false; } if (p_en) std::cout << std::endl; } // fibo_seq_X() steps through the sequence of Fibonacci numbers while // checking for the desired FizzBuzz attributes. // // param n The desired final index into the sequence, updated prior to // return with actual index achieved. This will be the same as // requested unless overflow of operand size occurred. // param result The final Fibonacci number reached, updated prior to return. // param p_en Optional means of disabling the intermediate console output. // return Whether the limit of the operand size (mUint_t) was reached. // bool fibo_seq_X(uint32_t& n, mUint_t& result, bool p_en=true) { mUint_t b,c; uint32_t i; bool overflow = false; result = 1; b = 1; for (i = 1; i < n && !overflow; ++i) { spit_fizz(i, result, p_en); c = b; if (b.Add(result)) // b = b + result; { overflow = true; } result = c; } spit_fizz(i, result, p_en); n = i; return(overflow); } int main(int argc, char **argv) { // set print_details false to quiet the console output // that is useful for timing the fizzbuzz... bool print_details = true; double digits = floor(MY_UINT_BITS*(log10(2.0))); std::cout << std::endl << "Welcome to FIZZBUZZ!" << std::endl << "Your current operand size is "<< MY_UINT_BITS << "bits, your result will be limited to " << digits << " decimal digits" << std::endl << "If you need more digits, then modify MY_UINT_BITS in fizzbuzz.cpp" << std::endl << std::endl; int input = 0; std::cout << "Enter the length of FIZZBUZZ sequence to run: "; std::cin >> input; if (input < 1 ) return 0; uint32_t n_finish = input; mUint_t fbn; long ticks = std::clock(); bool retval = fibo_seq_X(n_finish, fbn, print_details); ticks = std::clock() - ticks; if (retval && (n_finish < (uint32_t)input)) { std::cout << std::endl << "HIGHEST RESULT: " << n_finish << " " << fbn << std::endl; std::cout << "ERROR: data overflow condition after n = " << n_finish << std::endl; std::cout << "Please recompile fizzbuzz.cpp with more MY_UINT_BITS" << std::endl; } else { std::cout << std::endl << "SUCCESS: " << n_finish << " " << fbn << std::endl; } // probably only useful if print_details set to false std::cout << "CPUtime seconds: " << float(ticks)/CLOCKS_PER_SEC << std::endl; return 0; }
32.461165
99
0.61971
[ "vector" ]
014bc0f1763642610c26cedb76fddccb9ba33416
69,893
cpp
C++
tests/DtlsClientServerTest.cpp
tarm-project/tarm-io
6aebd85573f65017decf81be073c8b13ce6ac12c
[ "MIT" ]
4
2021-01-14T15:19:35.000Z
2022-01-09T09:22:18.000Z
tests/DtlsClientServerTest.cpp
ink-splatters/tarm-io
6aebd85573f65017decf81be073c8b13ce6ac12c
[ "MIT" ]
null
null
null
tests/DtlsClientServerTest.cpp
ink-splatters/tarm-io
6aebd85573f65017decf81be073c8b13ce6ac12c
[ "MIT" ]
1
2020-08-05T21:14:59.000Z
2020-08-05T21:14:59.000Z
/*---------------------------------------------------------------------------------------------- * Copyright (c) 2020 - present Alexander Voitenko * Licensed under the MIT License. See License.txt in the project root for license information. *----------------------------------------------------------------------------------------------*/ #include "UTCommon.h" #include "fs/Path.h" #include "net/Dtls.h" #include "net/Udp.h" #include "ByteSwap.h" #include "ScopeExitGuard.h" #include "Timer.h" #include <chrono> #include <string> #include <thread> #include <vector> // Just to include platform-specific networking headers #include <uv.h> struct DtlsClientServerTest : public testing::Test, public LogRedirector { protected: std::uint16_t m_default_port = 30541; std::string m_default_addr = "127.0.0.1"; const io::fs::Path m_test_path = exe_path().string(); const io::fs::Path m_cert_path = m_test_path / "certificate.pem"; const io::fs::Path m_key_path = m_test_path / "key.pem"; }; TEST_F(DtlsClientServerTest, client_without_actions) { io::EventLoop loop; auto client = new io::net::DtlsClient(loop); client->schedule_removal(); ASSERT_EQ(io::StatusCode::OK, loop.run()); } TEST_F(DtlsClientServerTest, server_without_actions) { io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); server->schedule_removal(); ASSERT_EQ(io::StatusCode::OK, loop.run()); } TEST_F(DtlsClientServerTest, server_with_invalid_address) { io::EventLoop loop; std::size_t server_on_new_connection_count = 0; std::size_t server_on_receive_count = 0; std::size_t server_on_close_count = 0; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto error = server->listen({"", m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); ++server_on_new_connection_count; }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++server_on_receive_count; }, 1000 * 100, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { ++server_on_close_count; } ); EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::INVALID_ARGUMENT, error.code()); server->schedule_removal(); EXPECT_EQ(0, server_on_new_connection_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(0, server_on_new_connection_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); } TEST_F(DtlsClientServerTest, bind_privileged) { // Windows does not have privileged ports TARM_IO_TEST_SKIP_ON_WINDOWS(); io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error = server->listen({m_default_addr, 100}, nullptr ); EXPECT_TRUE(listen_error); EXPECT_EQ(io::StatusCode::PERMISSION_DENIED, listen_error.code()); server->schedule_removal(); ASSERT_EQ(io::StatusCode::OK, loop.run()); } TEST_F(DtlsClientServerTest, client_and_server_send_message_each_other) { io::EventLoop loop; const char client_message[] = "Hello from client!"; const char server_message[] = "Hello from server!"; std::size_t server_new_connection_counter = 0; std::size_t server_data_receive_counter = 0; std::size_t server_data_send_counter = 0; std::size_t client_new_connection_counter = 0; std::size_t client_data_receive_counter = 0; std::size_t client_data_send_counter = 0; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); EXPECT_EQ(server, &client.server()); ++server_new_connection_counter; }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++server_data_receive_counter; std::string s(data.buf.get(), data.size); EXPECT_EQ(client_message, s); client.send_data(server_message, sizeof(server_message) - 1, // -1 is to not send last 0 [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_data_send_counter; } ); } ); ASSERT_FALSE(listen_error) << listen_error.string(); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_new_connection_counter; client.send_data(client_message, sizeof(client_message) - 1, // -1 is to not send last 0 [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_data_send_counter; } ); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); std::string s(data.buf.get(), data.size); EXPECT_EQ(server_message, s); ++client_data_receive_counter; // All interaction is done at this point server->schedule_removal(); client.schedule_removal(); } ); EXPECT_EQ(0, server_new_connection_counter); EXPECT_EQ(0, server_data_receive_counter); EXPECT_EQ(0, server_data_send_counter); EXPECT_EQ(0, client_new_connection_counter); EXPECT_EQ(0, client_data_receive_counter); EXPECT_EQ(0, client_data_send_counter); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, server_new_connection_counter); EXPECT_EQ(1, server_data_receive_counter); EXPECT_EQ(1, server_data_send_counter); EXPECT_EQ(1, client_new_connection_counter); EXPECT_EQ(1, client_data_receive_counter); EXPECT_EQ(1, client_data_send_counter); } TEST_F(DtlsClientServerTest, connected_peer_timeout) { io::EventLoop loop; const std::size_t TIMEOUT_MS = 200; const std::string client_message = "Hello from client!"; std::size_t server_new_connection_counter = 0; std::size_t server_data_receive_counter = 0; std::size_t server_peer_timeout_counter = 0; std::size_t client_new_connection_counter = 0; std::size_t client_data_receive_counter = 0; std::size_t client_data_send_counter = 0; std::chrono::high_resolution_clock::time_point t1; std::chrono::high_resolution_clock::time_point t2; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); ++server_new_connection_counter; }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++server_data_receive_counter; t1 = std::chrono::high_resolution_clock::now(); }, TIMEOUT_MS, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); ++server_peer_timeout_counter; server->schedule_removal(); t2 = std::chrono::high_resolution_clock::now(); EXPECT_TIMEOUT_MS(TIMEOUT_MS, std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1)); } ); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_new_connection_counter; client.send_data(client_message, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error); ++client_data_send_counter; client.schedule_removal(); } ); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++client_data_receive_counter; } ); EXPECT_EQ(0, server_new_connection_counter); EXPECT_EQ(0, server_data_receive_counter); EXPECT_EQ(0, server_peer_timeout_counter); EXPECT_EQ(0, client_new_connection_counter); EXPECT_EQ(0, client_data_receive_counter); EXPECT_EQ(0, client_data_send_counter); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, server_new_connection_counter); EXPECT_EQ(1, server_data_receive_counter); EXPECT_EQ(1, server_peer_timeout_counter); EXPECT_EQ(1, client_new_connection_counter); EXPECT_EQ(0, client_data_receive_counter); EXPECT_EQ(1, client_data_send_counter); } TEST_F(DtlsClientServerTest, client_and_server_in_threads_send_message_each_other) { // Note: pretty much the same test as 'client_and_server_send_message_each_other' // but in threads. const std::string server_message = "Hello from server!"; const std::string client_message = "Hello from client!"; std::size_t server_new_connection_counter = 0; std::size_t server_data_receive_counter = 0; std::size_t server_data_send_counter = 0; std::thread server_thread([&]() { io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error){ EXPECT_FALSE(error); ++server_new_connection_counter; }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++server_data_receive_counter; std::string s(data.buf.get(), data.size); EXPECT_EQ(client_message, s); client.send_data(server_message, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_data_send_counter; server->schedule_removal(); } ); } ); ASSERT_EQ(io::StatusCode::OK, loop.run()); }); std::size_t client_new_connection_counter = 0; std::size_t client_data_receive_counter = 0; std::size_t client_data_send_counter = 0; std::thread client_thread([&]() { io::EventLoop loop; // Giving a time to start a server std::this_thread::sleep_for(std::chrono::milliseconds(1000)); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_new_connection_counter; client.send_data(client_message, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error); ++client_data_send_counter; } ); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); std::string s(data.buf.get(), data.size); EXPECT_EQ(server_message, s); ++client_data_receive_counter; client.schedule_removal(); } ); ASSERT_EQ(io::StatusCode::OK, loop.run()); }); server_thread.join(); client_thread.join(); EXPECT_EQ(1, server_new_connection_counter); EXPECT_EQ(1, server_data_receive_counter); EXPECT_EQ(1, server_data_send_counter); EXPECT_EQ(1, client_new_connection_counter); EXPECT_EQ(1, client_data_receive_counter); EXPECT_EQ(1, client_data_send_counter); } TEST_F(DtlsClientServerTest, client_send_1mb_chunk) { // Note: 1 mb cunks are larger than DTLS could handle io::EventLoop loop; const std::uint32_t LARGE_DATA_SIZE = 1024 * 1024; const std::uint32_t NORMAL_DATA_SIZE = 2 * 1024; std::shared_ptr<char> client_buf(new char[LARGE_DATA_SIZE], std::default_delete<char[]>()); std::memset(client_buf.get(), 0, LARGE_DATA_SIZE); std::size_t client_data_send_counter = 0; std::size_t server_data_send_counter = 0; // A bit of callback hell here ]:-) auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); server->listen({m_default_addr, m_default_port}, nullptr, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); EXPECT_EQ(NORMAL_DATA_SIZE, data.size); client.send_data(client_buf, LARGE_DATA_SIZE, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); client.send_data(client_buf, LARGE_DATA_SIZE, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); client.send_data(client_buf, NORMAL_DATA_SIZE, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); ++server_data_send_counter; server->schedule_removal(); } ); } ); } ); } ); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { client.send_data(client_buf, LARGE_DATA_SIZE, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); client.send_data(client_buf, LARGE_DATA_SIZE, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); client.send_data(client_buf, NORMAL_DATA_SIZE, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error); ++client_data_send_counter; } ); } ); } ); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); EXPECT_EQ(NORMAL_DATA_SIZE, data.size); client.schedule_removal(); } ); EXPECT_EQ(0, client_data_send_counter); EXPECT_EQ(0, server_data_send_counter); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_data_send_counter); EXPECT_EQ(1, server_data_send_counter); } TEST_F(DtlsClientServerTest, dtls_negotiated_version) { io::EventLoop loop; std::size_t client_new_connection_counter = 0; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); EXPECT_EQ(io::net::max_supported_dtls_version(), client.negotiated_dtls_version()); server->schedule_removal(); }, nullptr ); auto client = new io::net::DtlsClient(loop); EXPECT_EQ(io::net::DtlsVersion::UNKNOWN, client->negotiated_dtls_version()); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_new_connection_counter; EXPECT_EQ(io::net::max_supported_dtls_version(), client.negotiated_dtls_version()); client.schedule_removal(); }, nullptr ); EXPECT_EQ(0, client_new_connection_counter); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_new_connection_counter); } /* TEST_F(DtlsClientServerTest, default_constructor) { io::EventLoop loop; this->log_to_stdout(); auto client = new io::net::DtlsClient(loop); client->connect("51.15.68.114", 1234, [](io::net::DtlsClient& client, const io::Error&) { EXPECT_FALSE(error); std::cout << "Connected!!!" << std::endl; client.send_data("bla_bla_bla"); }, [](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); std::cout.write(buf, size); } ); ASSERT_EQ(io::StatusCode::OK, loop.run()); } TEST_F(DtlsClientServerTest, default_constructor) { io::EventLoop loop; this->log_to_stdout(); auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); server->listen("0.0.0.0", 1234, [&](io::net::DtlsConnectedClient& client){ std::cout << "On new connection!!!" << std::endl; client.send_data("Hello world!\n"); }, [&](io::net::DtlsConnectedClient&, const io::DataChunk& data){ std::cout.write(buf, size); server->schedule_removal(); } ); ASSERT_EQ(io::StatusCode::OK, loop.run()); } */ TEST_F(DtlsClientServerTest, client_with_restricted_dtls_version) { const std::string message = "Hello!"; std::size_t client_on_connect_callback_count = 0; std::size_t client_on_send_callback_count = 0; std::size_t server_on_connect_callback_count = 0; std::size_t server_on_receive_callback_count = 0; io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); ++server_on_connect_callback_count; EXPECT_EQ(io::net::min_supported_dtls_version(), client.negotiated_dtls_version()); }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++server_on_receive_callback_count; EXPECT_EQ(message.size(), data.size); std::string received_message(data.buf.get(), data.size); EXPECT_EQ(message, received_message); server->schedule_removal(); } ); ASSERT_FALSE(listen_error); auto client = new io::net::DtlsClient(loop, io::net::DtlsVersionRange{io::net::min_supported_dtls_version(), io::net::min_supported_dtls_version()}); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error); EXPECT_EQ(io::net::min_supported_dtls_version(), client.negotiated_dtls_version()); ++client_on_connect_callback_count; client.send_data(message, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error); ++client_on_send_callback_count; client.schedule_removal(); }); } ); EXPECT_EQ(0, client_on_connect_callback_count); EXPECT_EQ(0, client_on_send_callback_count); EXPECT_EQ(0, server_on_connect_callback_count); EXPECT_EQ(0, server_on_receive_callback_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_connect_callback_count); EXPECT_EQ(1, client_on_send_callback_count); EXPECT_EQ(1, server_on_connect_callback_count); EXPECT_EQ(1, server_on_receive_callback_count); } TEST_F(DtlsClientServerTest, server_with_restricted_dtls_version) { const std::string message = "Hello!"; std::size_t client_on_connect_callback_count = 0; std::size_t client_on_send_callback_count = 0; std::size_t server_on_connect_callback_count = 0; std::size_t server_on_receive_callback_count = 0; io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path, io::net::DtlsVersionRange{io::net::min_supported_dtls_version(), io::net::min_supported_dtls_version()}); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); ++server_on_connect_callback_count; EXPECT_EQ(io::net::min_supported_dtls_version(), client.negotiated_dtls_version()); }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++server_on_receive_callback_count; EXPECT_EQ(message.size(), data.size); std::string received_message(data.buf.get(), data.size); EXPECT_EQ(message, received_message); server->schedule_removal(); } ); ASSERT_FALSE(listen_error); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error); EXPECT_EQ(io::net::min_supported_dtls_version(), client.negotiated_dtls_version()); ++client_on_connect_callback_count; client.send_data(message, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error); ++client_on_send_callback_count; client.schedule_removal(); }); } ); EXPECT_EQ(0, client_on_connect_callback_count); EXPECT_EQ(0, client_on_send_callback_count); EXPECT_EQ(0, server_on_connect_callback_count); EXPECT_EQ(0, server_on_receive_callback_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_connect_callback_count); EXPECT_EQ(1, client_on_send_callback_count); EXPECT_EQ(1, server_on_connect_callback_count); EXPECT_EQ(1, server_on_receive_callback_count); } TEST_F(DtlsClientServerTest, client_and_server_dtls_version_mismatch) { if (io::net::min_supported_dtls_version() == io::net::max_supported_dtls_version()) { TARM_IO_TEST_SKIP(); } std::size_t client_on_connect_callback_count = 0; std::size_t client_on_receive_callback_count = 0; std::size_t server_on_connect_callback_count = 0; std::size_t server_on_receive_callback_count = 0; io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path, io::net::DtlsVersionRange{io::net::max_supported_dtls_version(), io::net::max_supported_dtls_version()}); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); EXPECT_EQ(io::net::DtlsVersion::UNKNOWN, client.negotiated_dtls_version()); ++server_on_connect_callback_count; server->schedule_removal(); }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++server_on_receive_callback_count; } ); ASSERT_FALSE(listen_error); auto client = new io::net::DtlsClient(loop, io::net::DtlsVersionRange{io::net::min_supported_dtls_version(), io::net::min_supported_dtls_version()}); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); EXPECT_EQ(io::net::DtlsVersion::UNKNOWN, client.negotiated_dtls_version()); ++client_on_connect_callback_count; client.schedule_removal(); }, [&](io::net::DtlsClient&, const io::DataChunk&, const io::Error& error) { EXPECT_FALSE(error); ++client_on_receive_callback_count; } ); EXPECT_EQ(0, client_on_connect_callback_count); EXPECT_EQ(0, client_on_receive_callback_count); EXPECT_EQ(0, server_on_connect_callback_count); EXPECT_EQ(0, server_on_receive_callback_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_connect_callback_count); EXPECT_EQ(0, client_on_receive_callback_count); EXPECT_EQ(1, server_on_connect_callback_count); EXPECT_EQ(0, server_on_receive_callback_count); } TEST_F(DtlsClientServerTest, save_received_buffer) { io::EventLoop loop; const std::string client_message_1 = "1: Hello from client!"; const std::string client_message_2 = "2: Hello from client!"; const std::string server_message_1 = "1: Hello from server!"; const std::string server_message_2 = "2: Hello from server!"; std::size_t server_data_receive_counter = 0; std::size_t client_data_receive_counter = 0; std::shared_ptr<const char> client_saved_buf; std::shared_ptr<const char> server_saved_buf; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++server_data_receive_counter; std::string s(data.buf.get(), data.size); if (server_data_receive_counter == 1) { EXPECT_EQ(client_message_1, s); server_saved_buf = data.buf; } else { EXPECT_EQ(client_message_2, s); } client.send_data((server_data_receive_counter == 1 ? server_message_1 : server_message_2)); } ); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); client.send_data(client_message_1); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++client_data_receive_counter; std::string s(data.buf.get(), data.size); if (server_data_receive_counter == 1) { EXPECT_EQ(server_message_1, s); client_saved_buf = data.buf; client.send_data(client_message_2); } else { EXPECT_EQ(server_message_2, s); // All interaction is done at this point server->schedule_removal(); client.schedule_removal(); } } ); EXPECT_EQ(0, server_data_receive_counter); EXPECT_EQ(0, client_data_receive_counter); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(2, server_data_receive_counter); EXPECT_EQ(2, client_data_receive_counter); // As we do not save size, reuse it from initial messages constants EXPECT_EQ(server_message_1, std::string(client_saved_buf.get(), server_message_1.size())); EXPECT_EQ(client_message_1, std::string(server_saved_buf.get(), client_message_1.size())); } TEST_F(DtlsClientServerTest, fail_to_init_ssl_on_client) { // Note: in this test we set invalid ciphers list -> SSL is not able to init io::EventLoop loop; std::size_t server_connect_counter = 0; std::size_t server_data_receive_counter = 0; std::size_t client_data_receive_counter = 0; std::size_t client_connect_counter = 0; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); ++server_connect_counter; }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++server_data_receive_counter; } ); const auto previous_ciphers = io::global::ciphers_list(); io::global::set_ciphers_list("!@#$%^&*()"); io::ScopeExitGuard scope_guard([=]() { io::global::set_ciphers_list(previous_ciphers); }); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); ++client_connect_counter; client.schedule_removal(); server->schedule_removal(); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++client_data_receive_counter; } ); EXPECT_EQ(0, server_connect_counter); EXPECT_EQ(0, server_data_receive_counter); EXPECT_EQ(0, client_data_receive_counter); EXPECT_EQ(0, client_connect_counter); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(0, server_connect_counter); EXPECT_EQ(0, server_data_receive_counter); EXPECT_EQ(0, client_data_receive_counter); EXPECT_EQ(1, client_connect_counter); } TEST_F(DtlsClientServerTest, close_connection_from_server_side) { io::EventLoop loop; std::size_t client_on_close_count = 0; std::size_t client_on_receive_count = 0; const std::string client_message = "Hello from client!"; const std::string server_message = "Hello from server!"; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); client.send_data(server_message, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); client.close(); } ); } ); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); client.send_data(client_message, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); } ); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { ++client_on_receive_count; }, [&](io::net::DtlsClient& client, const io::Error& error) { server->schedule_removal(); client.schedule_removal(); ++client_on_close_count; } ); EXPECT_EQ(0, client_on_close_count); EXPECT_EQ(0, client_on_receive_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_close_count); EXPECT_EQ(1, client_on_receive_count); } TEST_F(DtlsClientServerTest, close_connection_from_client_side_with_no_data_sent) { io::EventLoop loop; std::size_t client_on_new_connection_count = 0; std::size_t client_on_receive_count = 0; std::size_t client_on_close_count = 0; std::size_t server_on_new_connection_count = 0; std::size_t server_on_receive_count = 0; std::size_t server_on_close_count = 0; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); ++server_on_new_connection_count; }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { // Not expecting this call ++server_on_receive_count; }, 1000 * 100, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { ++server_on_close_count; server->schedule_removal(); } ); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_on_new_connection_count; client.close(); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { // Not expecting this call ++client_on_receive_count; }, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error); ++client_on_close_count; client.schedule_removal(); } ); EXPECT_EQ(0, client_on_new_connection_count); EXPECT_EQ(0, client_on_receive_count); EXPECT_EQ(0, client_on_close_count); EXPECT_EQ(0, server_on_new_connection_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_new_connection_count); EXPECT_EQ(0, client_on_receive_count); EXPECT_EQ(1, client_on_close_count); EXPECT_EQ(1, server_on_new_connection_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(1, server_on_close_count); } TEST_F(DtlsClientServerTest, close_connection_from_client_side_with_with_data_sent) { io::EventLoop loop; const std::vector<std::string> client_data_to_send = { "a", "b", "c", "d", "e", "f", "g", "h", "i" }; std::size_t client_on_new_connection_count = 0; std::size_t client_on_receive_count = 0; std::size_t client_on_close_count = 0; std::size_t server_on_new_connection_count = 0; std::size_t server_on_receive_count = 0; std::size_t server_on_close_count = 0; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); ++server_on_new_connection_count; }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++server_on_receive_count; }, 1000 * 100, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { ++server_on_close_count; server->schedule_removal(); } ); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_on_new_connection_count; for (auto v : client_data_to_send) { client.send_data(v, [=, &client_data_to_send](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); if (v == client_data_to_send.back()) { client.close(); } }); } }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { // Not expecting this call ++client_on_receive_count; }, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error); ++client_on_close_count; client.schedule_removal(); } ); EXPECT_EQ(0, client_on_new_connection_count); EXPECT_EQ(0, client_on_receive_count); EXPECT_EQ(0, client_on_close_count); EXPECT_EQ(0, server_on_new_connection_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_new_connection_count); EXPECT_EQ(0, client_on_receive_count); EXPECT_EQ(1, client_on_close_count); EXPECT_EQ(1, server_on_new_connection_count); EXPECT_EQ(client_data_to_send.size(), server_on_receive_count); EXPECT_EQ(1, server_on_close_count); } TEST_F(DtlsClientServerTest, client_with_invalid_dtls_version) { if (io::net::min_supported_dtls_version() == io::net::max_supported_dtls_version()) { TARM_IO_TEST_SKIP(); } std::size_t client_on_connect_count = 0; // Note: Min > Max in this test io::EventLoop loop; auto client = new io::net::DtlsClient(loop, io::net::DtlsVersionRange{io::net::max_supported_dtls_version(), io::net::min_supported_dtls_version()}); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); ++client_on_connect_count; client.schedule_removal(); } ); EXPECT_EQ(0, client_on_connect_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_connect_count); } TEST_F(DtlsClientServerTest, server_with_invalid_dtls_version) { if (io::net::min_supported_dtls_version() == io::net::max_supported_dtls_version()) { TARM_IO_TEST_SKIP(); } std::size_t server_on_new_connection_count = 0; std::size_t server_on_receive_count = 0; std::size_t server_on_close_count = 0; // Note: Min > Max in this test io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path, io::net::DtlsVersionRange{io::net::max_supported_dtls_version(), io::net::min_supported_dtls_version()}); auto error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error); ++server_on_new_connection_count; }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error); ++server_on_receive_count; }, 1000 * 100, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { ++server_on_close_count; } ); EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); server->schedule_removal(); EXPECT_EQ(0, server_on_new_connection_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(0, server_on_new_connection_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); } TEST_F(DtlsClientServerTest, client_with_invalid_address) { std::size_t client_on_connect_count = 0; io::EventLoop loop; auto client = new io::net::DtlsClient(loop); client->connect({"0.0", m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::INVALID_ARGUMENT, error.code()); ++client_on_connect_count; client.schedule_removal(); } ); EXPECT_EQ(0, client_on_connect_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_connect_count); } TEST_F(DtlsClientServerTest, server_address_in_use) { io::EventLoop loop; auto server_1 = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error_1 = server_1->listen({m_default_addr, m_default_port}, nullptr); EXPECT_FALSE(listen_error_1); auto server_2 = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error_2 = server_2->listen({m_default_addr, m_default_port}, nullptr); EXPECT_TRUE(listen_error_2); EXPECT_EQ(io::StatusCode::ADDRESS_ALREADY_IN_USE, listen_error_2.code()); server_1->schedule_removal(); server_2->schedule_removal(); ASSERT_EQ(io::StatusCode::OK, loop.run()); } TEST_F(DtlsClientServerTest, client_with_invalid_address_and_no_connect_callback) { // Note: crash test io::EventLoop loop; auto client = new io::net::DtlsClient(loop); client->connect({"0.0", m_default_port}, nullptr ); client->schedule_removal(); ASSERT_EQ(io::StatusCode::OK, loop.run()); } TEST_F(DtlsClientServerTest, client_no_timeout_on_data_send) { const std::size_t COMMON_TIMEOUT_MS = 800; const std::size_t SEND_TIMEOUT_MS = 550; std::thread server_thread([&](){ std::size_t server_on_close_callback_count = 0; io::EventLoop loop; const auto start_time = std::chrono::high_resolution_clock::now(); auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); // Note: here we capture client by reference in Timer's callback. This should not // be done in production code because it is impossible to track lifetime of // server-size objects outside of the server callbacks. (new io::Timer(loop))->start(SEND_TIMEOUT_MS, [&](io::Timer& timer) { client.send_data("!"); timer.schedule_removal(); } ); }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); client.close(); }, COMMON_TIMEOUT_MS, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_close_callback_count; const auto end_time = std::chrono::high_resolution_clock::now(); EXPECT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(), 2 * SEND_TIMEOUT_MS); server->schedule_removal(); } ); ASSERT_FALSE(listen_error) << listen_error.string(); EXPECT_EQ(0, server_on_close_callback_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, server_on_close_callback_count); }); std::this_thread::sleep_for(std::chrono::milliseconds(500)); std::thread client_thread([&](){ std::size_t client_on_close_callback_count = 0; io::EventLoop loop; const auto start_time = std::chrono::high_resolution_clock::now(); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); (new io::Timer(loop))->start(SEND_TIMEOUT_MS, [&](io::Timer& timer) { client.send_data("!"); timer.schedule_removal(); } ); }, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_on_close_callback_count; const auto end_time = std::chrono::high_resolution_clock::now(); EXPECT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(), 2 * SEND_TIMEOUT_MS); client.schedule_removal(); }, COMMON_TIMEOUT_MS ); EXPECT_EQ(0, client_on_close_callback_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_close_callback_count); }); server_thread.join(); client_thread.join(); } TEST_F(DtlsClientServerTest, client_timeout_cause_server_peer_close) { io::EventLoop loop; const std::size_t SERVER_TIMEOUT_MS = 600; const std::size_t CLIENT_TIMEOUT_MS = 400; std::size_t client_on_close_callback_count = 0; std::size_t server_on_close_callback_count = 0; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); }, SERVER_TIMEOUT_MS, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); EXPECT_EQ(1, client_on_close_callback_count); EXPECT_EQ(0, server_on_close_callback_count); ++server_on_close_callback_count; server->schedule_removal(); } ); ASSERT_FALSE(listen_error) << listen_error.string(); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); }, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); EXPECT_EQ(0, client_on_close_callback_count); EXPECT_EQ(0, server_on_close_callback_count); ++client_on_close_callback_count; client.schedule_removal(); }, CLIENT_TIMEOUT_MS ); EXPECT_EQ(0, client_on_close_callback_count); EXPECT_EQ(0, server_on_close_callback_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_close_callback_count); EXPECT_EQ(1, server_on_close_callback_count); } TEST_F(DtlsClientServerTest, server_peer_timeout_cause_client_close) { io::EventLoop loop; const std::size_t SERVER_TIMEOUT_MS = 200; const std::size_t CLIENT_TIMEOUT_MS = 60000; std::size_t client_on_close_callback_count = 0; std::size_t server_on_close_callback_count = 0; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); }, SERVER_TIMEOUT_MS, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); EXPECT_EQ(0, client_on_close_callback_count); EXPECT_EQ(0, server_on_close_callback_count); ++server_on_close_callback_count; server->schedule_removal(); } ); ASSERT_FALSE(listen_error) << listen_error.string(); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); }, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); EXPECT_EQ(0, client_on_close_callback_count); EXPECT_EQ(1, server_on_close_callback_count); ++client_on_close_callback_count; client.schedule_removal(); }, CLIENT_TIMEOUT_MS ); EXPECT_EQ(0, client_on_close_callback_count); EXPECT_EQ(0, server_on_close_callback_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_close_callback_count); EXPECT_EQ(1, server_on_close_callback_count); } TEST_F(DtlsClientServerTest, server_schedule_removal_cause_client_close) { std::size_t server_on_connect_count = 0; std::size_t server_on_receive_count = 0; std::size_t server_on_close_count = 0; std::size_t client_on_connect_count = 0; std::size_t client_on_receive_count = 0; std::size_t client_on_close_count = 0; io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_connect_count; }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_receive_count; server->schedule_removal(); }, 100000, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_close_count; } ); ASSERT_FALSE(listen_error) << listen_error.string(); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); client.send_data("Hello!"); ++client_on_connect_count; }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_on_receive_count; }, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_on_close_count; client.schedule_removal(); }, 100000 ); EXPECT_EQ(0, server_on_connect_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); EXPECT_EQ(0, client_on_connect_count); EXPECT_EQ(0, client_on_receive_count); EXPECT_EQ(0, client_on_close_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, server_on_connect_count); EXPECT_EQ(1, server_on_receive_count); EXPECT_EQ(1, server_on_close_count); EXPECT_EQ(1, client_on_connect_count); EXPECT_EQ(0, client_on_receive_count); EXPECT_EQ(1, client_on_close_count); } TEST_F(DtlsClientServerTest, client_send_invalid_data_before_handshake) { std::size_t server_on_connect_count = 0; std::size_t server_on_receive_count = 0; std::size_t server_on_close_count = 0; std::size_t udp_on_receive_count = 0; io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_TRUE(error); ++server_on_connect_count; EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); server->schedule_removal(); }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_receive_count; }, 100000, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_close_count; } ); ASSERT_FALSE(listen_error) << listen_error.string(); auto client = new io::net::UdpClient(loop); client->set_destination({m_default_addr, m_default_port}, [&](io::net::UdpClient& client, const io::Error& error) { EXPECT_FALSE(error) << error; client.send_data("!!!"); }, [&](io::net::UdpClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++udp_on_receive_count; } ); (new io::Timer(loop))->start(100, [&](io::Timer& timer){ client->schedule_removal(); timer.schedule_removal(); } ); EXPECT_EQ(0, server_on_connect_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); EXPECT_EQ(0, udp_on_receive_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, server_on_connect_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); EXPECT_EQ(0, udp_on_receive_count); } const unsigned char DTLS_1_2_CLIENT_HELLO[] = { 0x16, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x01, 0x00, 0x00, 0xfb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe7, 0xfe, 0xfd, 0xfc, 0xf0, 0x71, 0xa9, 0x8f, 0x57, 0xd1, 0x32, 0x7a, 0xe1, 0x15, 0x2e, 0x3f, 0xa8, 0xe0, 0x73, 0xab, 0xa0, 0xf3, 0xd7, 0x02, 0xd2, 0x84, 0x36, 0x61, 0xbe, 0x78, 0xef, 0xe2, 0x03, 0x94, 0x7c, 0x00, 0x00, 0x00, 0x7c, 0xc0, 0x30, 0xc0, 0x2c, 0xc0, 0x14, 0x00, 0xa5, 0x00, 0xa3, 0x00, 0xa1, 0x00, 0x9f, 0x00, 0x39, 0x00, 0x38, 0x00, 0x37, 0x00, 0x36, 0x00, 0x88, 0x00, 0x87, 0x00, 0x86, 0x00, 0x85, 0xc0, 0x19, 0xc0, 0x32, 0xc0, 0x2e, 0xc0, 0x0f, 0xc0, 0x05, 0x00, 0x9d, 0x00, 0x35, 0x00, 0x84, 0xc0, 0x2f, 0xc0, 0x2b, 0xc0, 0x13, 0x00, 0xa4, 0x00, 0xa2, 0x00, 0xa0, 0x00, 0x9e, 0x00, 0x33, 0x00, 0x32, 0x00, 0x31, 0x00, 0x30, 0x00, 0x9a, 0x00, 0x99, 0x00, 0x98, 0x00, 0x97, 0x00, 0x45, 0x00, 0x44, 0x00, 0x43, 0x00, 0x42, 0xc0, 0x18, 0xc0, 0x31, 0xc0, 0x2d, 0xc0, 0x0e, 0xc0, 0x04, 0x00, 0x9c, 0x00, 0x2f, 0x00, 0x96, 0x00, 0x41, 0x00, 0x07, 0xc0, 0x12, 0x00, 0x16, 0x00, 0x13, 0x00, 0x10, 0x00, 0x0d, 0xc0, 0x17, 0xc0, 0x0d, 0xc0, 0x03, 0x00, 0x0a, 0x00, 0xff, 0x01, 0x00, 0x00, 0x55, 0x00, 0x0b, 0x00, 0x04, 0x03, 0x00, 0x01, 0x02, 0x00, 0x0a, 0x00, 0x1c, 0x00, 0x1a, 0x00, 0x17, 0x00, 0x19, 0x00, 0x1c, 0x00, 0x1b, 0x00, 0x18, 0x00, 0x1a, 0x00, 0x16, 0x00, 0x0e, 0x00, 0x0d, 0x00, 0x0b, 0x00, 0x0c, 0x00, 0x09, 0x00, 0x0a, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x20, 0x00, 0x1e, 0x06, 0x01, 0x06, 0x02, 0x06, 0x03, 0x05, 0x01, 0x05, 0x02, 0x05, 0x03, 0x04, 0x01, 0x04, 0x16, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x01, 0x00, 0x00, 0xfb, 0x00, 0x00, 0x00, 0x00, 0xe7, 0x00, 0x00, 0x14, 0x02, 0x04, 0x03, 0x03, 0x01, 0x03, 0x02, 0x03, 0x03, 0x02, 0x01, 0x02, 0x02, 0x02, 0x03, 0x00, 0x0f, 0x00, 0x01, 0x01 }; TEST_F(DtlsClientServerTest, client_send_invalid_data_during_handshake) { std::size_t server_on_connect_count = 0; std::size_t server_on_receive_count = 0; std::size_t server_on_close_count = 0; std::size_t udp_on_receive_count = 0; io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_TRUE(error); ++server_on_connect_count; EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); server->schedule_removal(); }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_receive_count; }, 100000, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_close_count; } ); ASSERT_FALSE(listen_error) << listen_error.string(); auto client = new io::net::UdpClient(loop); client->set_destination({m_default_addr, m_default_port}, [&](io::net::UdpClient& client, const io::Error& error) { EXPECT_FALSE(error) << error; std::shared_ptr<const char> buf_ptr(reinterpret_cast<const char*>(DTLS_1_2_CLIENT_HELLO), [](const char*){}); client.send_data(buf_ptr, sizeof(DTLS_1_2_CLIENT_HELLO)); }, [&](io::net::UdpClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++udp_on_receive_count; EXPECT_GE(data.size, 50); EXPECT_EQ(0x16, data.buf.get()[0]); // Type = handshake EXPECT_EQ(char(0xFE), data.buf.get()[1]); // Common prefix of DTLS version client.send_data("!!!"); (new io::Timer(loop))->start(100, [&](io::Timer& timer){ client.schedule_removal(); timer.schedule_removal(); } ); } ); EXPECT_EQ(0, server_on_connect_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); EXPECT_EQ(0, udp_on_receive_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, server_on_connect_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); EXPECT_EQ(1, udp_on_receive_count); } // TODO: currently incompatible with TLS 1.3 implementation TEST_F(DtlsClientServerTest, DISABLED_client_send_invalid_data_after_handshake) { // Note: in this test we make regular handshake and then bind UDP socket with SO_REUSEADDR // and send trash data. std::size_t server_on_connect_count = 0; std::size_t server_on_receive_count = 0; std::size_t server_on_close_count = 0; std::size_t client_on_connect_count = 0; std::size_t client_on_receive_count = 0; std::size_t client_on_close_count = 0; io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_connect_count; }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); ++server_on_receive_count; server->schedule_removal(); }, 100000, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_close_count; } ); ASSERT_FALSE(listen_error) << listen_error.string(); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_on_connect_count; /* // Just raw libuv code to send UDP data // TODO: looks like it could be rewritten with raw sockets ::sockaddr_in sock_addr{0}; sock_addr.sin_family = AF_INET; sock_addr.sin_port = io::host_to_network(client.bound_port()); uv_udp_t udp_handle; const io::Error init_error = uv_udp_init(reinterpret_cast<uv_loop_t*>(loop.raw_loop()), &udp_handle); const io::Error bind_error = uv_udp_bind(&udp_handle, reinterpret_cast<const ::sockaddr*>(&sock_addr), UV_UDP_REUSEADDR); if (bind_error) { FAIL() << "bind error: " << bind_error.string(); return; } uv_udp_send_t send_request; uv_buf_t uv_buf = uv_buf_init(&invalid_message, 1); ::sockaddr_in destination{0}; destination.sin_family = AF_INET; destination.sin_addr.s_addr = std::uint32_t(1) << 24 | std::uint32_t(0) << 16 | std::uint32_t(0) << 8 | std::uint32_t(127); destination.sin_port = io::host_to_network(m_default_port); int uv_status = uv_udp_send(&send_request, &udp_handle, &uv_buf, 1, reinterpret_cast<const struct sockaddr*>(&destination), nullptr); // add on_send, and close UDP handle there if (uv_status < 0) { FAIL() << "send error: " << io::Error(uv_status).string(); return; } */ auto socket_handle = ::socket(AF_INET, SOCK_DGRAM, 0); ASSERT_GT(socket_handle, 0); int result = 0; int yes = 1; #if defined(TARM_IO_PLATFORM_MACOSX) result = ::setsockopt(socket_handle, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(int)); #elif defined(TARM_IO_PLATFORM_WINDOWS) result = ::setsockopt(socket_handle, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&yes), sizeof(int)); #else result = ::setsockopt(socket_handle, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); #endif ASSERT_NE(-1, result); ::sockaddr_in source_addr{0}; source_addr.sin_family = AF_INET; source_addr.sin_port = io::host_to_network(client.bound_port()); result = ::bind(socket_handle, reinterpret_cast<sockaddr*>(&source_addr), sizeof(source_addr)); ASSERT_NE(-1, result); ::sockaddr_in dest_addr{0}; dest_addr.sin_family = AF_INET; dest_addr.sin_addr.s_addr = std::uint32_t(1) << 24 | // 127.0.0.1 std::uint32_t(0) << 16 | std::uint32_t(0) << 8 | std::uint32_t(127); dest_addr.sin_port = io::host_to_network(m_default_port); result = ::sendto(socket_handle, "!!!", 3, 0, reinterpret_cast<sockaddr*>(&dest_addr), sizeof(dest_addr)); ASSERT_NE(-1, result); ::close(socket_handle); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_on_receive_count; }, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_on_close_count; client.schedule_removal(); }, 100000 ); EXPECT_EQ(0, server_on_connect_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); EXPECT_EQ(0, client_on_connect_count); EXPECT_EQ(0, client_on_receive_count); EXPECT_EQ(0, client_on_close_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, server_on_connect_count); EXPECT_EQ(1, server_on_receive_count); EXPECT_EQ(1, server_on_close_count); EXPECT_EQ(1, client_on_connect_count); EXPECT_EQ(0, client_on_receive_count); EXPECT_EQ(1, client_on_close_count); } TEST_F(DtlsClientServerTest, client_send_data_to_server_after_connection_timeout_at_server) { std::size_t server_on_connect_count = 0; std::size_t server_on_receive_count = 0; std::size_t server_on_close_count = 0; std::size_t client_on_connect_count = 0; std::size_t client_on_receive_count = 0; std::size_t client_on_close_count = 0; io::EventLoop loop; auto server = new io::net::DtlsServer(loop, m_cert_path, m_key_path); auto listen_error = server->listen({m_default_addr, m_default_port}, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_connect_count; }, [&](io::net::DtlsConnectedClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::OPENSSL_ERROR, error.code()); ++server_on_receive_count; }, 200, [&](io::net::DtlsConnectedClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++server_on_close_count; } ); ASSERT_FALSE(listen_error) << listen_error.string(); auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_on_connect_count; (new io::Timer(loop))->start(400, [&](io::Timer& timer) { // TODO: currently this data will not be received because UDP peers at UDP server // have inactivity timeout which is hardcoded in DTLS server and filters incoming data. // Need to revise this/ client.send_data("!!!"); timer.schedule_removal(); } ); (new io::Timer(loop))->start(600, [&](io::Timer& timer) { client.schedule_removal(); server->schedule_removal(); timer.schedule_removal(); } ); }, [&](io::net::DtlsClient& client, const io::DataChunk& data, const io::Error& error) { EXPECT_FALSE(error) << error.string(); ++client_on_receive_count; }, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_FALSE(error) << error.string(); EXPECT_EQ(0, client_on_close_count); EXPECT_EQ(1, server_on_close_count); ++client_on_close_count; }, 100000 ); EXPECT_EQ(0, server_on_connect_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(0, server_on_close_count); EXPECT_EQ(0, client_on_connect_count); EXPECT_EQ(0, client_on_receive_count); EXPECT_EQ(0, client_on_close_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, server_on_connect_count); EXPECT_EQ(0, server_on_receive_count); EXPECT_EQ(1, server_on_close_count); EXPECT_EQ(1, client_on_connect_count); EXPECT_EQ(0, client_on_receive_count); EXPECT_EQ(1, client_on_close_count); } TEST_F(DtlsClientServerTest, client_send_data_to_server_after_connection_timeout_at_client) { // TODO: } // TODO: client timeout when no close callback provided, see test below TEST_F(DtlsClientServerTest, connect_to_not_existing_server) { io::EventLoop loop; std::size_t client_on_connect_count = 0; auto client = new io::net::DtlsClient(loop); client->connect({m_default_addr, m_default_port}, [&](io::net::DtlsClient& client, const io::Error& error) { EXPECT_TRUE(error); EXPECT_EQ(io::StatusCode::CONNECTION_REFUSED, error.code()); ++client_on_connect_count; client.schedule_removal(); } ); EXPECT_EQ(0, client_on_connect_count); ASSERT_EQ(io::StatusCode::OK, loop.run()); EXPECT_EQ(1, client_on_connect_count); } // TODO: key and certificate mismatch // TODO: send data to server after connection timeout // TODO: send data to client after connection timeout // TODO: schedulre client for removal and at the same time send data from server (client should not call receive callback)
37.944083
133
0.620177
[ "vector" ]
014fcf0be3224cada7764173525efc0c61194ec8
2,607
hpp
C++
sources/SceneGraph/Animation/spMorphTargetAnimation.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
14
2015-08-16T21:05:20.000Z
2019-08-21T17:22:01.000Z
sources/SceneGraph/Animation/spMorphTargetAnimation.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
null
null
null
sources/SceneGraph/Animation/spMorphTargetAnimation.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
3
2016-10-31T06:08:44.000Z
2019-08-02T16:12:33.000Z
/* * Morph target animation header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_MORPHTARGET_ANIMATION_H__ #define __SP_MORPHTARGET_ANIMATION_H__ #include "Base/spStandard.hpp" #include "SceneGraph/spSceneMesh.hpp" #include "SceneGraph/Animation/spMeshAnimation.hpp" #include "SceneGraph/Animation/spAnimationBaseStructures.hpp" #include <vector> namespace sp { namespace scene { /** Morph-Target animations interpolate each vertex of its mesh. This is a technique used by the games "Quake 1", "Quake 2" and "Quake III Arena". The 'SoftPixel Engine' supports this animation model innately for the MD2 and MD3 file formats. \ingroup group_animation */ class SP_EXPORT MorphTargetAnimation : public MeshAnimation { public: MorphTargetAnimation(); virtual ~MorphTargetAnimation(); /* === Functions === */ /** Adds a sequence of keyframes for the specified vertex. Because of performance efficiency you have to add all keyframes for each vertex at once. \param Surface: Specifies the MeshBuffer object to which the vertex belongs. \param Index: Specifies the vertex index. \param Keyframes: Specifies the container with all keyframe data (coordinate and normal). */ void addKeyframeSequence(video::MeshBuffer* Surface, u32 Index, const std::vector<SVertexKeyframe> &Keyframes); //! Remvoes all keyframes of the specifies vertex. void removeKeyframeSequence(video::MeshBuffer* Surface, u32 Index); void clearKeyframes(); virtual void setupManualAnimation(SceneNode* Node); /** Updates the morph target animation. If the animation is playing all keyframes will be performed. \param Object: This must be a Mesh scene node. Otherwise the function will do nothing. */ virtual void updateAnimation(SceneNode* Node); virtual u32 getKeyframeCount() const; virtual void interpolate(u32 IndexFrom, u32 IndexTo, f32 Interpolation); virtual void copy(const Animation* Other); private: /* === Members === */ std::list<SMorphTargetVertex> Vertices_; u32 MaxKeyframe_; bool isCulling_; }; } // /namespace scene } // /namespace sp #endif // ================================================================================
28.336957
142
0.64135
[ "mesh", "object", "vector", "model" ]
015fc0cfa07e538595e9441f5e6bfe8e74219e52
4,437
cc
C++
java/dynasm.cc
penberg/hornet
1cb54380d12eb35a0ef1fefe14aec11bf3b7b426
[ "BSD-2-Clause" ]
35
2015-01-17T12:14:30.000Z
2021-09-05T16:29:09.000Z
java/dynasm.cc
penberg/hornet
1cb54380d12eb35a0ef1fefe14aec11bf3b7b426
[ "BSD-2-Clause" ]
2
2015-05-22T16:51:24.000Z
2015-07-15T19:28:44.000Z
java/dynasm.cc
penberg/hornet
1cb54380d12eb35a0ef1fefe14aec11bf3b7b426
[ "BSD-2-Clause" ]
4
2015-09-29T05:54:27.000Z
2018-04-06T12:44:53.000Z
#include "hornet/java.hh" #include "hornet/translator.hh" #include "hornet/vm.hh" #include <sys/mman.h> #include <cassert> #include <classfile_constants.h> #include <jni.h> using namespace std; namespace hornet { static const int mmap_size = 4096; class dynasm_translator : public translator { public: dynasm_translator(method* method, dynasm_backend* backend); ~dynasm_translator(); template<typename T> T trampoline(); virtual void prologue() override; virtual void epilogue() override; virtual void begin(std::shared_ptr<basic_block> bblock) override; virtual void op_const (type t, int64_t value) override; virtual void op_load (type t, uint16_t idx) override; virtual void op_store (type t, uint16_t idx) override; virtual void op_arrayload(type t) override; virtual void op_arraystore(type t) override; virtual void op_convert(type from, type to) override; virtual void op_pop() override; virtual void op_pop2() override; virtual void op_dup() override; virtual void op_dup_x1() override; virtual void op_dup_x2() override; virtual void op_dup2() override; virtual void op_dup2_x1() override; virtual void op_dup2_x2() override; virtual void op_swap() override; virtual void op_unary(type t, unaryop op) override; virtual void op_binary(type t, binop op) override; virtual void op_iinc(uint8_t idx, jint value) override; virtual void op_lcmp() override; virtual void op_cmp(type t, cmpop op) override; virtual void op_if(type t, cmpop op, std::shared_ptr<basic_block> target) override; virtual void op_if_cmp(type t, cmpop op, std::shared_ptr<basic_block> bblock) override; virtual void op_goto(std::shared_ptr<basic_block> bblock) override; virtual void op_tableswitch(uint32_t high, uint32_t low, std::shared_ptr<basic_block> def, const std::vector<std::shared_ptr<basic_block>>& table) override; virtual void op_ret() override; virtual void op_ret_void() override; virtual void op_getstatic(field* field) override; virtual void op_putstatic(field* field) override; virtual void op_getfield(field* field) override; virtual void op_putfield(field* field) override; virtual void op_invokevirtual(method* target) override; virtual void op_invokespecial(method* target) override; virtual void op_invokestatic(method* target) override; virtual void op_invokeinterface(method* target) override; virtual void op_new(klass* klass) override; virtual void op_newarray(uint8_t atype) override; virtual void op_anewarray(klass* klass) override; virtual void op_multianewarray(klass* klass, uint8_t dimensions) override; virtual void op_arraylength() override; virtual void op_athrow() override; virtual void op_checkcast(klass* klass) override; virtual void op_instanceof(klass* klass) override; virtual void op_monitorenter() override; virtual void op_monitorexit() override; private: dynasm_backend* ctx; }; #define Dst ctx #define Dst_DECL dynasm_backend *Dst #define Dst_REF (ctx->D) #include <dasm_proto.h> #include <dasm_x86.h> #include "dynasm_x64.h" dynasm_translator::dynasm_translator(method* method, dynasm_backend* backend) : translator(method) , ctx(backend) { } dynasm_translator::~dynasm_translator() { } template<typename T> T dynasm_translator::trampoline() { size_t size; if (dasm_link(ctx, &size) != DASM_S_OK) { assert(0); } if (ctx->_offset + size >= mmap_size) { assert(0); } // // XXX: not thread safe // unsigned char* code = static_cast<unsigned char*>(ctx->_code) + ctx->_offset; ctx->_offset += size; dasm_encode(ctx, code); return reinterpret_cast<T>(code); } dynasm_backend::dynasm_backend() : _offset(0) { dasm_init(this, DASM_MAXSECTION); dasm_setupglobal(this, nullptr, 0); dasm_setup(this, actions); _code = mmap(NULL, mmap_size, PROT_WRITE | PROT_EXEC, MAP_ANON | MAP_PRIVATE, -1, 0); if (_code == MAP_FAILED) { assert(0); } } dynasm_backend::~dynasm_backend() { munmap(_code, mmap_size); dasm_free(this); } value_t dynasm_backend::execute(method* method, frame& frame) { dynasm_translator translator(method, this); translator.translate(); auto fp = translator.trampoline<value_t (*)()>(); return fp(); } }
28.811688
160
0.709714
[ "vector" ]
01626e58c254c53b5ca34b47e79c8d7890285feb
1,248
cc
C++
dataframe/edm4hepRDF.cc
fdplacido/EDM4hep
ad89a9077feaf222ee5249b626d7d74b3dc33a13
[ "Apache-2.0" ]
5
2019-10-29T10:13:25.000Z
2020-02-24T13:12:20.000Z
dataframe/edm4hepRDF.cc
fdplacido/EDM4hep
ad89a9077feaf222ee5249b626d7d74b3dc33a13
[ "Apache-2.0" ]
82
2020-03-03T12:08:24.000Z
2022-03-25T16:36:51.000Z
dataframe/edm4hepRDF.cc
fdplacido/EDM4hep
ad89a9077feaf222ee5249b626d7d74b3dc33a13
[ "Apache-2.0" ]
9
2020-03-20T06:14:48.000Z
2022-03-25T14:22:38.000Z
#include "edm4hepRDF.h" #include "Math/Vector4D.h" namespace edm4hep { std::vector<float> pt (std::vector<MCParticleData> const& in){ std::vector<float> result; for (size_t i = 0; i < in.size(); ++i) { result.push_back(std::sqrt(in[i].momentum.x * in[i].momentum.x + in[i].momentum.y * in[i].momentum.y)); } return result; } std::vector<float> eta(std::vector<MCParticleData> const& in){ std::vector<float> result; ROOT::Math::PxPyPzMVector lv; for (size_t i = 0; i < in.size(); ++i) { lv.SetCoordinates(in[i].momentum.x, in[i].momentum.y, in[i].momentum.z, in[i].mass); result.push_back(lv.Eta()); } return result; } std::vector<float> cos_theta(std::vector<MCParticleData> const& in){ std::vector<float> result; ROOT::Math::PxPyPzMVector lv; for (size_t i = 0; i < in.size(); ++i) { lv.SetCoordinates(in[i].momentum.x, in[i].momentum.y, in[i].momentum.z, in[i].mass); result.push_back(cos(lv.Theta())); } return result; } std::vector<double> r (std::vector<SimTrackerHitData> const& in) { std::vector<double> result; for (size_t i = 0; i < in.size(); ++i) { result.push_back(std::sqrt(in[i].position.x*in[i].position.x + in[i].position.y*in[i].position.y)); } return result; } }
29.023256
107
0.643429
[ "vector" ]
6c632aae1186d0d60db41d7bbf1c733c88c7930c
729
cpp
C++
ABC/ABC089/B.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
1
2021-06-01T17:13:44.000Z
2021-06-01T17:13:44.000Z
ABC/ABC089/B.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
null
null
null
ABC/ABC089/B.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
null
null
null
//#include <cstdio> //#include <cmath> //#include <iostream> //#include <sstream> //#include <string> //#include <vector> //#include <set> //#include <queue> //#include <algorithm> // //#ifdef _DEBUG //#define DMP(x) cerr << #x << ": " << x << "\n" //#else //#define DMP(x) ((void)0) //#endif // //const int MOD = 1000000007, INF = 1111111111; //using namespace std; //using lint = long long; // //int main() { // // cin.tie(nullptr); // ios::sync_with_stdio(false); // // int N; // cin >> N; // // char tmp; // set<char> s; // for (int i = 0; i < N; i++) { // cin >> tmp; // s.emplace(tmp); // } // for (auto &e : s) cerr << e << endl; // if (s.size() == 3) cout << "Three\n"; // else cout << "Four\n"; // // // return 0; //}
17.357143
48
0.532236
[ "vector" ]
6c6390d2463d46c9a6f6b11ac52445279b68079a
9,311
cpp
C++
Assignment 3/bestfirstsearch.cpp
utkarsh1097/COL362-Assignments
b01b79e3d7e6aa3c53759015a3387a43fe821a11
[ "MIT" ]
null
null
null
Assignment 3/bestfirstsearch.cpp
utkarsh1097/COL362-Assignments
b01b79e3d7e6aa3c53759015a3387a43fe821a11
[ "MIT" ]
null
null
null
Assignment 3/bestfirstsearch.cpp
utkarsh1097/COL362-Assignments
b01b79e3d7e6aa3c53759015a3387a43fe821a11
[ "MIT" ]
null
null
null
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<queue> #include<algorithm> using namespace std; double **datapoints, **mbr_min, **mbr_max; //Stores the datapoints, all the min mbr, all the max mbr int **indexes; //Store indexes of all datapoints int sort_dim, counter; //Dimension on which sort has to be done int comp_d; bool comparator(int a, int b) { if(datapoints[a][sort_dim] != datapoints[b][sort_dim]) return datapoints[a][sort_dim] < datapoints[b][sort_dim]; else { int k = (sort_dim+1)%comp_d; while(true) { if(datapoints[a][k] != datapoints[b][k]) return datapoints[a][k] < datapoints[b][k]; else k = (k+1)%comp_d; } } } class Node { private: double *point, *mbr_min, *mbr_max; Node *left, *right; public: Node() { left = NULL; right = NULL; } Node(double *in_point, double *in_mbr_min, double *in_mbr_max) { left = NULL; right = NULL; point = in_point; mbr_max = in_mbr_max; mbr_min = in_mbr_min; } void assignL(Node* child) { left = child; } void assignR(Node* child) { right = child; } Node *getLChild() { return left; } Node *getRChild() { return right; } double *getPoint() { return point; } double *getMinMBR() { return mbr_min; } double *getMaxMBR() { return mbr_max; } }; Node *buildTree(int level, int dim, int L, int R, int mbr_min_idx, int mbr_max_idx) { if(R < L) //Leaf node condition return NULL; int split_on_dim = level%dim; //Dimension to split on. First index of "indexes" int mid = (L+R)/2; //median. if even nos choose lower one, else middle one is chosen. second index of "indexes" int point_idx = indexes[split_on_dim][mid]; //Stores the index of current point for(int d = 0; d < dim; ++d) { if(dim != split_on_dim) { //What we do here is that we will sort the index[d] array in such a way that the sorting and ordering of the left child and right child in all dimensions is maintained always int temp[R-L+1]; //will help in "sorting" the vector of indexes so that at each level we get the correct lists sorted on each dimension for(int i = L; i<=R; ++i) temp[i-L] = (indexes[d][i]); int i = L, j = mid+1, k = L; indexes[d][mid] = point_idx; //for the sake of conserving this value in sorted lists of other dimensions while(i < mid && j <= R) { if(temp[k-L] != point_idx) { if(datapoints[temp[k-L]][split_on_dim] <= datapoints[point_idx][split_on_dim]) { indexes[d][i] = temp[k-L]; ++i; } else { indexes[d][j] = temp[k-L]; ++j; } } ++k; } while(i < mid) { if(temp[k-L] != point_idx) { indexes[d][i] = temp[k-L]; ++i; } ++k; } while(j <= R) { if(temp[k-L] != point_idx) { indexes[d][j] = temp[k-L]; ++j; } ++k; } } } Node *curnode = new Node(datapoints[point_idx], mbr_min[mbr_min_idx], mbr_max[mbr_max_idx]); ++counter; // double new_mbr_min[dim], new_mbr_max[dim]; for(int d = 0; d < dim; d++) { mbr_min[counter][d] = mbr_min[mbr_min_idx][d]; mbr_max[counter][d] = mbr_max[mbr_max_idx][d]; } mbr_min[counter][split_on_dim] = datapoints[point_idx][split_on_dim]; mbr_max[counter][split_on_dim] = datapoints[point_idx][split_on_dim]; int new_mbr_min_idx = counter, new_mbr_max_idx = counter; //The commented code below is to obtain the KD-Tree with in-order traversal /*for(int i = 0; i < dim; ++i) cout<<datapoints[point_idx][i]<<" "; cout<<endl;*/ curnode->assignL(buildTree(level+1, dim, L, mid-1, mbr_min_idx, new_mbr_max_idx)); curnode->assignR(buildTree(level+1, dim, mid+1, R, new_mbr_min_idx, mbr_max_idx)); return curnode; } double distance(int d, double *p1, double *p2) { double ans = 0.0; for(int i = 0; i < d; ++i) ans = ans + (p1[i]-p2[i])*(p1[i]-p2[i]); return ans; } bool lexi_compare(int d, double *p1, double *p2) //return true if p1 lexicographically smaller than p2 { for(int i = 0; i < d; ++i) { if(p1[i] != p2[i]) return p1[i] < p2[i]; } } double mbr_distance(int d, double *mbr_min, double *mbr_max, double query_point[]) { double ans = 0.0; for(int i = 0; i < d; ++i) { if(query_point[i] < mbr_min[i]) ans = ans+ (mbr_min[i]-query_point[i])*(mbr_min[i]-query_point[i]); else if(query_point[i] > mbr_max[i]) ans = ans+ (query_point[i]-mbr_max[i])*(query_point[i]-mbr_max[i]); } return ans; } void bestFirstSearch(int dim, double query_point[], priority_queue<pair<double, Node *>> &candidates, priority_queue<pair<double, Node *>> &answer) { // TODO: Implement best first search and find the times for 20NN queries. This will complete this file's part. while(true) { counter++; if(candidates.size() == 0) return; pair<double, Node *> P = candidates.top(), Q; candidates.pop(); if(answer.size() >= 20) { Q = answer.top(); if(Q.first < -P.first) return; } Node *curnode = P.second; double *curpoint = curnode->getPoint(); double cur_distance = distance(dim, curpoint, query_point); if(answer.size() >= 20) { if(cur_distance < Q.first) { answer.pop(); answer.push(make_pair(cur_distance, curnode)); } else if(cur_distance == Q.first) { if(lexi_compare(dim, curpoint, Q.second->getPoint())) { answer.pop(); answer.push(make_pair(cur_distance, curnode)); } } } else { answer.push(make_pair(cur_distance, curnode)); } Q = answer.top(); Node *LChild = curnode->getLChild(), *RChild = curnode->getRChild(); double lchild_distance, rchild_distance; if(LChild != NULL) { lchild_distance = mbr_distance(dim, LChild->getMinMBR(), LChild->getMaxMBR(), query_point); if(answer.size() >= 20) { if(lchild_distance <= Q.first) candidates.push(make_pair(-lchild_distance, LChild)); } else { candidates.push(make_pair(-lchild_distance, LChild)); } } if(RChild != NULL) { rchild_distance = mbr_distance(dim, RChild->getMinMBR(), RChild->getMaxMBR(), query_point); if(answer.size() >= 20) { if(rchild_distance <= Q.first) candidates.push(make_pair(-rchild_distance, RChild)); } else { candidates.push(make_pair(-rchild_distance, RChild)); } } } } int main() { system("mkdir bestfirstsearch_20NN"); freopen("bestfirstsearch_time.txt", "w", stdout); fclose(stdout); int d[] = {2, 3, 5, 10, 15, 20}; for(int r = 0; r <= 5; r++) { string filename = "dataset/dataset_"+to_string(d[r])+".txt"; freopen(filename.c_str(), "r", stdin); int N, D; double data; cin>>D>>N; comp_d = D; //First, take in the tuples datapoints = new double* [N]; mbr_min = new double* [N+1]; //Should be N+1, but just testing mbr_max = new double* [N+1]; ////Should be N+1, but just testing indexes = new int* [D]; for(int i = 0; i < N; ++i) { datapoints[i] = new double [D]; mbr_min[i] = new double [D]; mbr_max[i] = new double [D]; for(int j = 0; j < D; ++j) { cin>>data; datapoints[i][j] = data; } } mbr_min[N] = new double [D]; mbr_max[N] = new double [D]; fclose(stdin); //Now we will have to sort the tuples. Sorting is maintained by instead sorting an integer array of indexes. The comparator function looks into the datapoints instead. //Sorting needs to be maintained wrt each dimension. for(int i = 0; i < D; ++i) { indexes[i] = new int [N]; for(int j = 0; j < N; ++j) indexes[i][j] = j; sort_dim = i; sort(indexes[i], indexes[i]+N, comparator); } for(int i = 0; i < D; i++) { mbr_min[0][i] = 0.0; mbr_max[0][i] = 1.0; } counter = 0; Node *head = buildTree(0, D, 0, N-1, 0, 0); //Build the KD Tree // cout<<0<<endl; //KD-Tree construction completed double average_time = 0.0; clock_t begin = clock(); filename = "queryset/queryset_"+to_string(D)+".txt"; freopen(filename.c_str(), "r", stdin); string pathname = "bestfirstsearch_20NN/"+to_string(D); string makedir = "mkdir "+pathname; system(makedir.c_str()); for(int i = 0; i < 100; ++i) { priority_queue<pair<double, Node *>> candidates, answer; //Candidates is min heap, answer is max heap candidates.push(make_pair(-0.0, head)); //Initially the root MBR is present double query_point[D]; for(int i = 0; i < D; ++i) { cin>>query_point[i]; } //Now start finding kNN bestFirstSearch(D, query_point, candidates, answer); filename = pathname+"/"+to_string(i+1)+".txt"; freopen(filename.c_str(), "w", stdout); double *ans[20]; int k = 0; while(!answer.empty()) { ans[k] = answer.top().second->getPoint(); ++k; answer.pop(); } for(int i = k-1; i>=0; --i) { for(int j = 0; j < D; ++j) cout<<ans[i][j]<<" "; cout<<endl; } fclose(stdout); } fclose(stdin); clock_t end = clock(); filename = pathname+"/"+"average_time.txt"; freopen(filename.c_str(), "w", stdout); average_time = double(end-begin)/CLOCKS_PER_SEC; average_time = average_time/100; cout<<"Average time to find 20NN using best first search for dimension "<<D<<" is "<<average_time<<endl; fclose(stdout); freopen("bestfirstsearch_time.txt", "a", stdout); cout<<average_time<<endl; fclose(stdout); } return 0; }
23.752551
177
0.617442
[ "vector" ]
6c6593fa4cec4d435d33f3dced0b61ae8e4ca233
4,705
cpp
C++
src/gfx/file/scene_file.cpp
johannes-braun/graphics_utilities
191772a3ff1c14eea74b9b5614b6226cf1f8abb7
[ "MIT" ]
null
null
null
src/gfx/file/scene_file.cpp
johannes-braun/graphics_utilities
191772a3ff1c14eea74b9b5614b6226cf1f8abb7
[ "MIT" ]
null
null
null
src/gfx/file/scene_file.cpp
johannes-braun/graphics_utilities
191772a3ff1c14eea74b9b5614b6226cf1f8abb7
[ "MIT" ]
null
null
null
#include "file.hpp" #include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include <assimp/scene.h> #include <assimp/vector3.h> #include <gfx/log.hpp> #include <glm/glm.hpp> namespace gfx { void handle_node(scene_file& file, aiNode* node, const aiScene* scene, const glm::mat4& transform) noexcept { const glm::mat4 node_trafo = transform * transpose(reinterpret_cast<glm::mat4&>(node->mTransformation)); for (uint32_t i = 0; i < node->mNumMeshes; ++i) { file.mesh.geometries.at(node->mMeshes[i]).transformation = static_cast<gfx::transform>(node_trafo); } for (uint32_t i = 0; i < node->mNumChildren; ++i) { handle_node(file, node->mChildren[i], scene, node_trafo); } } scene_file::scene_file(const files::path& path) : file(path) { if (!exists(file::path)) { elog << "Scene \"" << path << "\" could not be loaded."; return; } Assimp::Importer importer; const aiScene* scene = importer.ReadFile( file::path.string(), aiProcess_GenSmoothNormals | aiProcess_JoinIdenticalVertices | aiProcess_ImproveCacheLocality | aiProcess_LimitBoneWeights | aiProcess_RemoveRedundantMaterials | aiProcess_Triangulate | aiProcess_GenUVCoords | aiProcess_SortByPType | aiProcess_FindDegenerates | aiProcess_FindInvalidData); materials.resize(scene->mNumMaterials); #pragma omp parallel for schedule(dynamic) for (int i = 0; i <static_cast<int>(scene->mNumMaterials); ++i) { const auto ai_material = scene->mMaterials[i]; aiString name; [[maybe_unused]] aiReturn r = ai_material->Get(AI_MATKEY_NAME, name); material& current_material = materials[i]; current_material.name = std::string(name.data, name.length); ai_material->Get(AI_MATKEY_COLOR_DIFFUSE, reinterpret_cast<aiColor4D&>(current_material.color_diffuse)); ai_material->Get(AI_MATKEY_COLOR_EMISSIVE, reinterpret_cast<aiColor4D&>(current_material.color_emissive)); ai_material->Get(AI_MATKEY_COLOR_REFLECTIVE, reinterpret_cast<aiColor4D&>(current_material.color_reflective)); ai_material->Get(AI_MATKEY_COLOR_SPECULAR, reinterpret_cast<aiColor4D&>(current_material.color_specular)); ai_material->Get(AI_MATKEY_COLOR_TRANSPARENT, reinterpret_cast<aiColor4D&>(current_material.color_transparent)); const auto load_if = [&](auto& into, auto... matkey) { aiString p; ai_material->Get(matkey..., p); std::filesystem::path texpath = file::path.parent_path() / p.C_Str(); if (p.length != 0 && !std::filesystem::is_directory(texpath) && std::filesystem::exists(texpath)) { ilog << "Loading texture from " << texpath; into = image_file(texpath, bits::b8, 4); } }; load_if(current_material.texture_diffuse, AI_MATKEY_TEXTURE_DIFFUSE(0)); load_if(current_material.texture_bump, AI_MATKEY_TEXTURE_HEIGHT(0)); } const auto to_vec3 = [](const aiVector3D& vec) { return glm::vec3(vec.x, vec.y, vec.z); }; for (int m = 0; m < static_cast<int>(scene->mNumMeshes); ++m) { const auto ai_mesh = scene->mMeshes[m]; mesh3d current_mesh; current_mesh.indices.resize(ai_mesh->mNumFaces * 3); #pragma omp parallel for schedule(static) for (auto i = 0; i < static_cast<int>(ai_mesh->mNumFaces); ++i) { if (ai_mesh->mFaces[0].mNumIndices != 3) continue; current_mesh.indices[3 * i] = ai_mesh->mFaces[i].mIndices[0]; current_mesh.indices[3 * i + 1] = ai_mesh->mFaces[i].mIndices[1]; current_mesh.indices[3 * i + 2] = ai_mesh->mFaces[i].mIndices[2]; } current_mesh.vertices.resize(ai_mesh->mNumVertices); #pragma omp parallel for schedule(static) for (auto i = 0; i < static_cast<int>(ai_mesh->mNumVertices); ++i) { current_mesh.vertices[i] = vertex3d(to_vec3(ai_mesh->mVertices[i]), ai_mesh->HasTextureCoords(0) ? glm::vec2(to_vec3(ai_mesh->mTextureCoords[0][i])) : glm::vec2(0), to_vec3(ai_mesh->mNormals[i])); } auto& geo = current_mesh.geometries.emplace_back(); geo.index_count = static_cast<u32>(current_mesh.indices.size()); geo.vertex_count = static_cast<u32>(current_mesh.vertices.size()); mesh += current_mesh; mesh_material_indices[&mesh.geometries.back()] = ai_mesh->mMaterialIndex; } handle_node(*this, scene->mRootNode, scene, glm::mat4(1.f)); } } // namespace gfx
46.127451
138
0.643146
[ "mesh", "transform" ]
6c6dfea6a3d08352aa4cd045a0fbd52670e29c04
7,469
cc
C++
linker/linker.cc
rpjohnst/dejavu-llvm
568dfa38f226a8994d0bfc07db2cdb466db10529
[ "MIT" ]
6
2017-07-13T09:01:38.000Z
2021-11-03T06:50:02.000Z
linker/linker.cc
rpjohnst/dejavu-llvm
568dfa38f226a8994d0bfc07db2cdb466db10529
[ "MIT" ]
9
2018-02-08T23:19:47.000Z
2018-02-12T19:09:01.000Z
linker/linker.cc
rpjohnst/dejavu-llvm
568dfa38f226a8994d0bfc07db2cdb466db10529
[ "MIT" ]
1
2020-05-17T17:34:03.000Z
2020-05-17T17:34:03.000Z
#include <dejavu/linker/linker.h> #include <dejavu/linker/game.h> #include <dejavu/compiler/lexer.h> #include <dejavu/compiler/parser.h> #include <dejavu/compiler/codegen.h> #include <dejavu/system/buffer.h> #include <llvm/PassManager.h> #include <llvm/Analysis/Passes.h> #include <llvm/IR/Verifier.h> #include <llvm/Transforms/Scalar.h> #include <llvm/Transforms/IPO.h> #include <llvm/Transforms/IPO/PassManagerBuilder.h> #include <llvm/Linker/Linker.h> #include <llvm/Support/MemoryBuffer.h> #include <llvm/Bitcode/ReaderWriter.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Target/TargetMachine.h> #include <llvm/IR/DataLayout.h> #include <llvm/Support/ToolOutputFile.h> #include <llvm/Support/FileSystem.h> #include <sstream> #include <algorithm> #include <memory> using namespace llvm; static Module *load_module(const char *filename, LLVMContext &context) { std::unique_ptr<MemoryBuffer> file = std::move(MemoryBuffer::getFile(filename).get()); return getLazyBitcodeModule(std::move(file), context).get(); } linker::linker( const char *output, game &g, error_stream &e, const std::string &triple, LLVMContext &context ) : context(context), runtime(load_module("runtime.bc", context)), output(output), source(g), errors(e), compiler(*runtime, errors) { verifyModule(*runtime); } bool linker::build(const char *target, bool debug) { errors.progress(20, "compiling libraries"); build_libraries(); errors.progress(30, "compiling scripts"); build_scripts(); errors.progress(40, "compiling objects"); build_objects(); if (errors.count() > 0) return false; Module &game = compiler.get_module(); { SmallString<80> str; raw_svector_ostream error(str); if (verifyModule(game, &error)) { game.dump(); errors.error(error.str()); return false; } } if (!debug) { PassManager pm; PassManagerBuilder pmb; pmb.populateModulePassManager(pm); pm.run(game); } { std::error_code error; std::ostringstream f; f << output << "/objects.bc"; tool_output_file out(f.str(), error, sys::fs::F_None); if (error) { errors.error(error.message()); return false; } WriteBitcodeToFile(&game, out.os()); out.keep(); } errors.progress(60, "linking runtime"); link(target, debug); return errors.count() == 0; } static void diagnostic_handler(const DiagnosticInfo &DI) { fprintf(stderr, "AUGHERASER\n"); } bool linker::link(const char *target, bool debug) { std::ostringstream f; f << output << "/objects.bc"; std::unique_ptr<Module> objects(load_module(f.str().c_str(), context)); std::unique_ptr<Module> game = std::make_unique<Module>("game", context); Linker L(game.get(), &diagnostic_handler); if (L.linkInModule(objects.get()) || L.linkInModule(runtime.get())) errors.error("failed to link with runtime"); if (!debug) { PassManager pm; PassManagerBuilder pmb; pmb.OptLevel = 3; pmb.populateLTOPassManager(pm); pm.run(*game); } std::error_code error; tool_output_file out(target, error, sys::fs::F_None); if (error) { errors.error(error.message()); return false; } WriteBitcodeToFile(game.get(), out.os()); out.keep(); return true; } void linker::build_libraries() { for (unsigned int i = 0; i < source.nactions; i++) { if (source.actions[i].exec != action_type::exec_code) continue; std::ostringstream name; name << "action_lib"; if (source.actions[i].parent > -1) name << source.actions[i].parent; name << "_" << source.actions[i].id; size_t nargs = source.actions[i].nargs; if (source.actions[i].relative) nargs++; add_function( strlen(source.actions[i].code), source.actions[i].code, name.str().c_str(), nargs, false ); } } void linker::build_scripts() { // first pass so the code generator knows which functions are scripts for (unsigned int i = 0; i < source.nscripts; i++) { compiler.register_script(std::string(source.scripts[i].name)); } for (unsigned int i = 0; i < source.nscripts; i++) { add_function( strlen(source.scripts[i].code), source.scripts[i].code, source.scripts[i].name, 0, true ); } } std::ostream &operator <<(std::ostream &out, const argument &arg); void linker::build_objects() { for (unsigned int i = 0; i < source.nobjects; i++) { object &obj = source.objects[i]; // todo: output object properties for (unsigned int e = 0; e < obj.nevents; e++) { event &evt = obj.events[e]; // todo: output event data // todo: move this into compiler std::ostringstream code; for (unsigned int a = 0; a < evt.nactions; a++) { action &act = evt.actions[a]; // todo: don't do this by unparsing and reparsing switch (act.type->kind) { case action_type::act_begin: code << "{\n"; break; case action_type::act_end: code << "}\n"; break; case action_type::act_else: code << "else\n"; break; case action_type::act_exit: code << "exit\n"; break; case action_type::act_repeat: code << "repeat (" << act.args[0].val << ")\n"; break; case action_type::act_variable: code << act.args[0].val << (act.relative ? " += " : " = ") << act.args[1].val << "\n"; break; case action_type::act_code: { std::ostringstream s; s << obj.name << "_" << evt.main_id << "_" << evt.sub_id << "_" << a; add_function(strlen(act.args[0].val), act.args[0].val, s.str(), 0, false); code << s.str() << "()\n"; break; } case action_type::act_normal: { if (act.type->exec == action_type::exec_none) break; if (act.target != action::self) code << "with (" << act.target << ")"; if (act.type->question) code << "if ("; if (act.inv) code << '!'; if (act.type->exec == action_type::exec_code) { code << "action_lib"; if (act.type->parent > -1) code << act.type->parent; code << "_" << act.type->id; } else code << act.type->code; code << '('; unsigned int n = 0; for (; n < act.nargs; n++) { if (n != 0) code << ", "; code << act.args[n]; } if (act.type->relative) { code << ", " << act.relative; } code << ')'; if (act.type->question) code << ')'; code << '\n'; break; } default: /* do nothing */; } } std::ostringstream s; s << obj.name << "_" << evt.main_id << "_" << evt.sub_id; std::string c = code.str(); add_function(c.size(), c.c_str(), s.str(), 0, false); } } } std::ostream &operator <<(std::ostream &out, const argument &arg) { switch (arg.kind) { case argument::arg_expr: return out << arg.val; case argument::arg_both: if (arg.val[0] == '"' || arg.val[0] == '\'') return out << arg.val; // fall through case argument::arg_string: { std::string val(arg.val); while (val.find('"') != std::string::npos) { val.replace(val.find('"'), 1, "\"+'\"'+\""); } return out << '"' << val << '"'; } case argument::arg_bool: return out << (arg.val[0] == '0'); case argument::arg_menu: return out << arg.val; case argument::arg_color: return out << '$' << arg.val; default: return out << arg.resource; } } void linker::add_function( size_t length, const char *data, const std::string &name, int args, bool var ) { buffer code(length, data); token_stream tokens(code); arena allocator; parser parser(tokens, allocator, errors); errors.set_context(name); node *program = parser.getprogram(); if (errors.count() > 0) return; compiler.add_function(program, name.c_str(), args, var); }
25.404762
87
0.63623
[ "object" ]
6c700262a3fd9c48a998b926da0d4afae16bb21e
1,756
cpp
C++
3rd_4th_5th_sems/PP lab/Programming-paradigms-lab/Assignment 4/Question 2/src/clerk.cpp
iamshnoo/IIEST_labs
9f2cb85035ff2049e4c3438cc45d1e8c96938022
[ "BSD-3-Clause" ]
null
null
null
3rd_4th_5th_sems/PP lab/Programming-paradigms-lab/Assignment 4/Question 2/src/clerk.cpp
iamshnoo/IIEST_labs
9f2cb85035ff2049e4c3438cc45d1e8c96938022
[ "BSD-3-Clause" ]
null
null
null
3rd_4th_5th_sems/PP lab/Programming-paradigms-lab/Assignment 4/Question 2/src/clerk.cpp
iamshnoo/IIEST_labs
9f2cb85035ff2049e4c3438cc45d1e8c96938022
[ "BSD-3-Clause" ]
null
null
null
//clerk.cpp #include "clerk.hpp" // header in local directory #include <iostream> // header in standard library using namespace cleric; // Default constructor Clerk::Clerk(/* no args */) : Person() { position = "ASDFG"; salary = 9999; } // Parameterized constructor Clerk::Clerk(std::string t_name,int t_age,std::string t_gender, std::string position_val,int salary_val) : Person(t_name,t_age,t_gender) { position = position_val; salary = salary_val; } // Copy constructor Clerk::Clerk(const Clerk& old_clerk) : Person(old_clerk) { position = old_clerk.position; salary = old_clerk.salary; } // Assignment operator Clerk& Clerk::operator=(const Clerk& other_clerk) { if ( this != &other_clerk ) { //upcast the reference to the object *this of Student class to type (Person&) static_cast<Person&>(*this) = other_clerk; //uses Assignment opeator of Base class. position = other_clerk.position; salary = other_clerk.salary; } return *this; } // Read data (use it in main.cpp) void Clerk::read(/* no args */) { std::string t_position; int t_salary; Person::read(); std::cout<< "Workload : "; std::cin >> std::ws; // consume any white-space characters getline(std::cin, t_position); std::cout<< "Salary : "; std::cin >> t_salary; position = t_position; salary = t_salary; } // Display data void Clerk::display(/* no args */) { Person::display(); std::cout << "Workload : " << position << std::endl; std::cout<< "Salary : " << salary << std::endl; } // Destructor Clerk::~Clerk(/* no args */) { /* no explicit functionality*/ }
23.105263
93
0.607631
[ "object" ]
6c723d7a87e3bb03d9453cd5572830c39b0bb847
701
cpp
C++
Other Concepts/Preprocessor_Solution.cpp
aydinsimsek/HackerRank-solutions-cpp
acc567c4c169694e4086012e9acc6682884382e7
[ "MIT" ]
null
null
null
Other Concepts/Preprocessor_Solution.cpp
aydinsimsek/HackerRank-solutions-cpp
acc567c4c169694e4086012e9acc6682884382e7
[ "MIT" ]
null
null
null
Other Concepts/Preprocessor_Solution.cpp
aydinsimsek/HackerRank-solutions-cpp
acc567c4c169694e4086012e9acc6682884382e7
[ "MIT" ]
null
null
null
#define FUNCTION(name, op) #define minimum(a, b) if(b < a) a = b #define maximum(a, b) if(b > a) a = b #define foreach(a, b) for(int b = 0; b < a.size(); b++) #define io(a) cin >> a #define INF 100000000 #define toStr(a) #a #include <iostream> #include <vector> using namespace std; #if !defined toStr || !defined io || !defined FUNCTION || !defined INF #error Missing preprocessor definitions #endif FUNCTION(minimum, <) FUNCTION(maximum, >) int main(){ int n; cin >> n; vector<int> v(n); foreach(v, i) { io(v)[i]; } int mn = INF; int mx = -INF; foreach(v, i) { minimum(mn, v[i]); maximum(mx, v[i]); } int ans = mx - mn; cout << toStr(Result =) <<' '<< ans; return 0; }
18.945946
70
0.599144
[ "vector" ]
6c76349868d1ac99c1a7d243ce797de8250da592
1,000
cpp
C++
platforms/leetcode/0319_first_day_where_you_have_been_in_all_the_rooms.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
2
2020-09-17T09:04:00.000Z
2020-11-20T19:43:18.000Z
platforms/leetcode/0319_first_day_where_you_have_been_in_all_the_rooms.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/leetcode/0319_first_day_where_you_have_been_in_all_the_rooms.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
#include "../../template.hpp" int sol(const vector<int>& nums) { int n = nums.size(); int mod = 1e9 + 7; vector<vector<int64_t>> dp(2, vector<int64_t>(n + 1)); // dp[0][i] - the first odd times, dp[1][i] - even times dp[0][1] = 0; dp[1][1] = 1; for (int i = 2; i <= n; ++i) { dp[0][i] = (dp[1][i - 1] + 1) % mod; dp[1][i] = (2 * dp[0][i] + 1 - dp[0][nums[i - 1] + 1] + mod) % mod; } return dp[0][n]; } const int fastio_ = ([](){std::ios_base::sync_with_stdio(0); std::cin.tie(0);return 0;})(); int main() { TimeMeasure _; cout << sol({0,0}) << endl; // 2 cout << sol({0,0,2}) << endl; // 6 cout << sol({0,1,2,0}) << endl; // 6 cout << sol({0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,33,33,34,34,35,35,36,36,37,37,38,38,39,39,40,40,41,41,42,42,43,43,44,44,45,45,46,46,47,47,48}) << endl; // 86417750 }
43.478261
308
0.519
[ "vector" ]
6c7f2ac83905ec82ce4a0cfd0dac68ac9e9ecf12
16,936
cpp
C++
moos-ivp/ivp/src/lib_logutils/LogUtils.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
null
null
null
moos-ivp/ivp/src/lib_logutils/LogUtils.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
null
null
null
moos-ivp/ivp/src/lib_logutils/LogUtils.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
null
null
null
/*****************************************************************/ /* NAME: Michael Benjamin */ /* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */ /* FILE: LogUtils.cpp */ /* DATE: August 7th, 2008 */ /* */ /* This file is part of MOOS-IvP */ /* */ /* MOOS-IvP 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. */ /* */ /* MOOS-IvP 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 MOOS-IvP. If not, see */ /* <http://www.gnu.org/licenses/>. */ /*****************************************************************/ #include <iostream> #include <cstdlib> #include <cstdio> #include "MBUtils.h" #include "LogUtils.h" #include <cstdio> #define MAX_LINE_LENGTH 500000 using namespace std; //-------------------------------------------------------- // Procedure: getTimeStamp // Notes: Syntax: "TIMESTAMP VAR SOURCE DATA" string getTimeStamp(const string& line) { unsigned int i, len = line.length(); bool done = false; string str; for(i=0; ((i<len) && !done); i++) { if((line[i] == ' ') || (line[i] == '\t')) done = true; else str.push_back(line[i]); } return(str); } //-------------------------------------------------------- // Procedure: getVarName // Notes: Syntax: "TIMESTAMP VAR SOURCE DATA" // States: 0 1 2 3 4 5 string getVarName(const string& line) { unsigned int i, len = line.length(); bool done = false; int state = 0; string str; for(i=0; ((i<len) && !done); i++) { if((line[i] == ' ') || (line[i] == '\t')) { if(state == 0) state = 1; else if(state == 2) done = true; } else { if(state == 1) { str.push_back(line[i]); state = 2; } else if(state == 2) str.push_back(line[i]); } } return(str); } //-------------------------------------------------------- // Procedure: getSourceName // Notes: Syntax: "TIMESTAMP VAR SOURCE DATA" // States: 0 1 2 3 4 5 string getSourceName(const string& line) { unsigned int i, len = line.length(); bool done = false; int state = 0; string str; for(i=0; ((i<len) && !done); i++) { if((line[i] == ' ') || (line[i] == '\t')) { if(state == 0) state = 1; else if(state == 2) state = 3; else if(state == 4) done = true; } else { if(state == 1) state = 2; else if(state == 3) { str.push_back(line[i]); state = 4; } else if(state == 4) str.push_back(line[i]); } } return(str); } //-------------------------------------------------------- // Procedure: getSourceNameNoAux string getSourceNameNoAux(const string& line) { string src = getSourceName(line); string src_no_aux = biteString(src, ':'); return(src_no_aux); } //-------------------------------------------------------- // Procedure: getDataEntry // Notes: Syntax: "TIMESTAMP VAR SOURCE DATA" // States: 0 1 2 3 4 5 6 string getDataEntry(const string& line) { unsigned int i, len = line.length(); int state = 0; string str; for(i=0; (i<len); i++) { if((line[i] == ' ') || (line[i] == '\t')) { if(state == 0) state = 1; else if(state == 2) state = 3; else if(state == 4) state = 5; else if(state == 6) str.push_back(line[i]); } else { if(state == 1) state = 2; else if(state == 3) state = 4; else if(state == 5) { str.push_back(line[i]); state = 6; } else if(state == 6) str.push_back(line[i]); } } return(str); } //-------------------------------------------------------- // Procedure: stripInsigDigits // Notes: void stripInsigDigits(string& line) { bool seen_zero = false; bool done = false; int endix = line.length() - 1; while(!done) { if(line.at(endix) == '0') { seen_zero = true; // Check to make sure this zero isn't just a solitary zero, in which // case we want to leave it there. if((endix > 0)&&(line.at(endix-1)!=' ') && (line.at(endix-1)!='\t')) line[endix] = '\0'; else done = true; } else if(line.at(endix) == '.') { if(seen_zero == true) line[endix] = '\0'; done = true; } else done = true; endix--; } } //-------------------------------------------------------- // Procedure: getIndexByTime() // Purpose: Given a time, determine the highest index that has a // time less than or equal to the given time. // 2 5 9 13 14 19 23 28 31 35 43 57 // ^ ^ // 25 56 unsigned int getIndexByTime(const std::vector<double>& vtime, double gtime) { unsigned int vsize = vtime.size(); // Handle special cases if(vsize == 0) return(0); if(gtime <= vtime[0]) return(0); if(gtime >= vtime[vsize-1]) return(vsize-1); int jump = vsize / 2; int index = vsize / 2; bool done = false; while(!done) { //cout << "[" << index << "," << jump << "]" << flush; if(jump > 1) jump = jump / 2; if(vtime[index] <= gtime) { if(vtime[index+1] > gtime) done = true; else index += jump; } else index -= jump; } return(index); } //-------------------------------------------------------- // Procedure: shiftTimeStamp void shiftTimeStamp(string& line, double logstart) { string timestamp = getTimeStamp(line); if(!isNumber(timestamp)) return; double dtime = atof(timestamp.c_str()); if((dtime+1000) > logstart) dtime -= logstart; string stime = doubleToString(dtime, 3); line = findReplace(line, timestamp, stime); } //-------------------------------------------------------- // Procedure: getLogStart // Notes: Syntax "%% LOGSTART TIMESTAMP" double getLogStart(const string& line) { bool done = false; int state = 0; int buffix = 0; char buff[MAX_LINE_LENGTH]; unsigned int i, len = line.length(); for(i=0; ((i<len) && !done); i++) { if((line[i] == ' ') || (line[i] == '\t')) { if(state == 0) state = 1; else if(state == 2) state = 3; else if(state == 4) { buff[buffix] = '\0'; done = true; } } else { if(state == 1) state = 2; else if(state == 3) state = 4; if(state == 4) { buff[buffix] = line[i]; buffix++; } } } return(atof(buff)); } //------------------------------------------------------------- // Procedure: getLogStartFromFile double getLogStartFromFile(const string& filestr) { FILE *f = fopen(filestr.c_str(), "r"); if(!f) return(0); for(int j=0; j<5; j++) { string line = getNextRawLine(f); if(strContains(line, "LOGSTART")) { fclose(f); return(getLogStart(line)); } } fclose(f); return(0); } //-------------------------------------------------------- // Procedure: addVectorKey void addVectorKey(vector<string>& v_keys, vector<bool>& v_pmatch, string key) { bool pmatch = false; int len = key.length(); if(key.at(len-1) == '*') { pmatch = true; key.erase(len-1, 1); } unsigned int prior_ix = 0; bool prior = false; for(unsigned int i=0; i<v_keys.size(); i++) { if(key == v_keys[i]) { prior = true; prior_ix = i; } } if(!prior) { v_keys.push_back(key); v_pmatch.push_back(pmatch); } if(prior && pmatch && !v_pmatch[prior_ix]) v_pmatch[prior_ix] = true; } //-------------------------------------------------------- // Procedure: getNextRawLine string getNextRawLine(FILE *fileptr) { if(!fileptr) { cout << "failed getNextLine() - null file pointer" << endl; return("err"); } bool EOL = false; int buffix = 0; int myint = '\0'; char buff[MAX_LINE_LENGTH]; while((!EOL) && (buffix < MAX_LINE_LENGTH)) { myint = fgetc(fileptr); unsigned char mychar = myint; switch(myint) { case EOF: return("eof"); case '\n': buff[buffix] = '\0'; // attach terminating NULL EOL = true; break; default: buff[buffix] = mychar; buffix++; } } string str = buff; return(str); } //-------------------------------------------------------- // Procedure: getNextRawALogEntry ALogEntry getNextRawALogEntry(FILE *fileptr, bool allstrings) { ALogEntry entry; if(!fileptr) { cout << "failed getNextRawALogEntry() - null file pointer" << endl; entry.setStatus("invalid"); return(entry); } bool EOLine = false; bool EOFile = false; int buffix = 0; int lineix = 0; int myint = '\0'; char buff[MAX_LINE_LENGTH]; string time, var, rawsrc, val; // Simple state machine: // 0: time // 1: between time and variable // 2: variable // 3: between variable and source // 4: source // 5: between source and value // 6: value int state = 0; while((!EOLine) && (!EOFile) && (lineix < MAX_LINE_LENGTH)) { myint = fgetc(fileptr); unsigned char mychar = myint; switch(myint) { case EOF: EOFile = true; break; case ' ': case '\t': if(state==0) { buff[buffix] = '\0'; time = buff; buffix = 0; state=1; } else if(state==2) { buff[buffix] = '\0'; var = buff; buffix = 0; state=3; } else if(state==4) { buff[buffix] = '\0'; rawsrc = buff; buffix = 0; state=5; } break; case '\n': buff[buffix] = '\0'; // attach terminating NULL val = buff; EOLine = true; break; default: if(state==1) state=2; else if(state==3) state=4; else if(state==5) state=6; buff[buffix] = mychar; buffix++; } lineix++; } //cout << "t:" << time << " v:" << var << " s:" << src << " v:" << val << endl; string src = biteString(rawsrc,':'); string srcaux = rawsrc; // Check for lines that may be carriage return continuation of previous line's // data field as in DB_VARSUMMARY if((time != "") && (time.at(0) != '%')) { if(!isNumber(time.substr(0,1))) { entry.setStatus("invalid"); return(entry); } } if((time!="")&&(var!="")&&(src!="")&&(val!="") && isNumber(time)) { if(allstrings || !isNumber(val)) entry.set(atof(time.c_str()), var, src, srcaux, val); else entry.set(atof(time.c_str()), var, src, srcaux, atof(val.c_str())); } else { if(EOFile) entry.setStatus("eof"); else entry.setStatus("invalid"); } return(entry); } //-------------------------------------------------------- // Procedure: getSecsfromTimeOfDay // Notes: Date String of form "11:50:04 AM" double getEpochSecsFromTimeOfDay(string date_str) { string time = stripBlankEnds(biteString(date_str, ' ')); string am_pm = tolower(stripBlankEnds(date_str)); string hstr = biteString(time, ':'); string mstr = biteString(time, ':'); string sstr = time; double hours = atof(hstr.c_str()); double minutes = atof(mstr.c_str()); double seconds = atof(sstr.c_str()); if(am_pm == "pm") hours += 12; double total_seconds = seconds + (60*minutes) + (3600*hours); return(total_seconds); } //-------------------------------------------------------- // Procedure: getSecsfromTimeOfDay double getEpochSecsFromTimeOfDay(double hrs, double mins, double secs) { double total_seconds = secs + (60*mins) + (3600*hrs); return(total_seconds); } //-------------------------------------------------------- // Procedure: getEpochSecsfromDayOfYear // Notes: Date String of form "7/15/2009" // Returns the number of seconds before the start of the // given date - since January 01 1972. double getEpochSecsFromDayOfYear(string date_str, int format) { date_str = stripBlankEnds(date_str); double d_month = 0; double d_day = 0; double d_year = 0; if(format == 0) { string s_month = biteString(date_str, '/'); string s_day = biteString(date_str, '/'); string s_year = date_str; d_month = atof(s_month.c_str()); d_day = atof(s_day.c_str()); d_year = atof(s_year.c_str()); } double total_seconds = getEpochSecsFromDayOfYear(d_day, d_month, d_year); return(total_seconds); } //-------------------------------------------------------- // Procedure: getEpochSecsfromDayOfYear // Returns the number of seconds before the start of the // given date - since January 01 1970. double getEpochSecsFromDayOfYear(double d_day, double d_month, double d_year) { double years_elapsed = d_year - 1970; if(years_elapsed < 0) return(0); double total_seconds = years_elapsed * 365 * (3600 * 24); double days_elapsed = d_day-1; if(d_month > 1) days_elapsed += 31; if(d_month > 2) days_elapsed += 28; if(d_month > 3) days_elapsed += 31; if(d_month > 4) days_elapsed += 30; if(d_month > 5) days_elapsed += 31; if(d_month > 6) days_elapsed += 30; if(d_month > 7) days_elapsed += 31; if(d_month > 8) days_elapsed += 31; if(d_month > 9) days_elapsed += 30; if(d_month > 10) days_elapsed += 31; if(d_month > 11) days_elapsed += 30; total_seconds += 86400 * days_elapsed; // handle leap days if((d_year >= 1972) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 1976) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 1980) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 1984) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 1988) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 1992) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 1996) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2000) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2004) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2008) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2012) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2016) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2020) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2024) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2028) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2032) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2036) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2040) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2044) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2048) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2052) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2056) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2060) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2064) && (d_month >= 3)) total_seconds += 86400; if((d_year >= 2068) && (d_month >= 3)) total_seconds += 86400; #if 0 // handle leap seconds NOT COUNTED IN UNIX EPOCH TIME if((d_year >= 1972) && (d_month >= 7)) total_seconds++; if(d_year >= 1973) total_seconds++; if(d_year >= 1974) total_seconds++; if(d_year >= 1975) total_seconds++; if(d_year >= 1976) total_seconds++; if(d_year >= 1977) total_seconds++; if(d_year >= 1978) total_seconds++; if(d_year >= 1979) total_seconds++; if(d_year >= 1980) total_seconds++; if((d_year >= 1981) && (d_month >= 7)) total_seconds++; if((d_year >= 1982) && (d_month >= 7)) total_seconds++; if((d_year >= 1983) && (d_month >= 7)) total_seconds++; if((d_year >= 1985) && (d_month >= 7)) total_seconds++; if(d_year >= 1988) total_seconds++; if(d_year >= 1990) total_seconds++; if(d_year >= 1991) total_seconds++; if((d_year >= 1992) && (d_month >= 7)) total_seconds++; if((d_year >= 1993) && (d_month >= 7)) total_seconds++; if((d_year >= 1994) && (d_month >= 7)) total_seconds++; if(d_year >= 1996) total_seconds++; if((d_year >= 1997) && (d_month >= 7)) total_seconds++; if(d_year >= 1999) total_seconds++; if(d_year >= 2006) total_seconds++; if(d_year >= 2009) total_seconds++; #endif return(total_seconds); }
25.506024
81
0.523441
[ "vector" ]
6c8ceea0d95b3d8938643096775d652687af5cd1
96,419
cc
C++
stapl_release/benchmarks/composition/sweeps.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/benchmarks/composition/sweeps.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/benchmarks/composition/sweeps.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #include <stapl/containers/array/static_array.hpp> #include <stapl/containers/graph/dynamic_graph.hpp> #include <stapl/containers/graph/views/graph_view.hpp> #include <stapl/containers/graph/algorithms/hierarchical_view.hpp> #include <stapl/containers/graph/partitioners/graph_partitioner_utils.hpp> #include <stapl/containers/graph/algorithms/graph_io.hpp> #include <stapl/domains/interval.hpp> #include <stapl/utility/do_once.hpp> #include <stapl/runtime.hpp> #include <stapl/paragraph/factory_wf.hpp> #include <functional> //////////////////////////////////////////////////////////////////// /// @file sweeps.cc /// /// Parallel implementation of a sweep of a 3D spatial domain. The spatial /// domain is represented using a stapl::graph. There are eight sweeps, one /// beginning at each corner of the spatial domain. After the cell in the /// corner is processed the adjacent cells in each dimension are processed, and /// after they are processed the next set of adjacent cells may be processed. /// The resulting flow of execution across the graph is referred to as as /// wave front. Each sweep is implemented as a PARAGRAPH, which allows the /// individual tasks to be processed as soon as its adjacent predecessors have /// been processed. /// /// Each sweep represents the sweep of a collection of directions whose /// dot product with the sweep direction is positive. The implementation /// creates ten random directions for each octant that will be swept. /// /// The benchmark uses a @ref hierarchical_graph_view to create a multi-level /// coarsening of the cells, which are referred to as cellsets. The sweep /// itself is defined recursively using nested parallelism as a sweep of sweeps, /// with the work function at each level processing a cellset by creating a /// nested PARAGRAPH to sweep the cellsets contained within it. /// /// When the lowest level of the hierarchy is reached the sweep of a single cell /// is the application of a work function that averages the results from the /// preceding cells with the value stored in the cell. The result of the work /// function is a vector of values, one for each of the three outgoing faces. /// The value of a face is the weighted product of the average computed with the /// directions whose normals have a positive dot product with the cell face /// normal. /// /// This is benchmark structure mimics the core computation of the PDT /// application. See http://parasol.tamu.edu/asci for an explanation of the /// full application. ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @brief Represents a unit of the discretized spatial domain. /// /// The cell is stored as the property of the vertices of the graph /// representing the entire spatial domain. ////////////////////////////////////////////////////////////////////// struct cell { private: double m_value; public: cell() : m_value(0.) {} cell(double const& value) : m_value(value) {} double value() const { return m_value; } void value(double const& val) { m_value = val; } void define_type(stapl::typer& t) const { t.member(m_value); } }; namespace stapl { ////////////////////////////////////////////////////////////////////// /// @brief specialization of @ref proxy for the cell struct. ////////////////////////////////////////////////////////////////////// template <typename Accessor> class proxy<cell, Accessor> : public Accessor { friend class proxy_core_access; typedef cell target_t; public: explicit proxy(Accessor const& acc) : Accessor(acc) {} operator target_t() const { return Accessor::read(); } double value() const { return Accessor::const_invoke(&target_t::value); } void value(double const& v) { Accessor::invoke(&target_t::value, v); } }; } ////////////////////////////////////////////////////////////////////// /// @brief Three-dimensional vector implementation /// /// This class is used to represent sweep directions and cell face normals. ////////////////////////////////////////////////////////////////////// struct normal { double m_x; double m_y; double m_z; normal() : m_x(0.), m_y(0.), m_z(0.) {} normal(double x, double y, double z) : m_x(x), m_y(y), m_z(z) {} void define_type(stapl::typer& t) { t.member(m_x); t.member(m_y); t.member(m_z); } }; std::ostream& operator<<(std::ostream& str, normal const& n) { str << "(" << n.m_x << ", " << n.m_y << ", " << n.m_z << ")"; return str; } bool operator==(normal const& x, normal const& y) { double epsilon(0.000001); return (x.m_x - y.m_x < epsilon) && (x.m_x - y.m_x > -epsilon) && (x.m_y - y.m_y < epsilon) && (x.m_y - y.m_y > -epsilon) && (x.m_z - y.m_z < epsilon) && (x.m_z - y.m_z > -epsilon); } ////////////////////////////////////////////////////////////////////// /// @brief Compute the dot product of two normals ////////////////////////////////////////////////////////////////////// double operator*(normal const& x, normal const& y) { return x.m_x*y.m_x + x.m_y*y.m_y + x.m_z*y.m_z; } ////////////////////////////////////////////////////////////////////// /// @brief Captures the input arguments for the benchmark and provides easy /// access for all methods that need information about the spatial domain. ////////////////////////////////////////////////////////////////////// struct problem_input { private: /// Number of cells in the x-dimension. unsigned int m_nx; /// Number of cells in the y-dimension. unsigned int m_ny; /// Number of cells in the z-dimension. unsigned int m_nz; /// Aggregation factor for each dimension that determines the cellset size. unsigned int m_agg; /// The number of levels of nesting to be exercised. unsigned int m_level; /// The number of locations in the x-dimension. unsigned int m_px; /// The number of locations in the y-dimension. unsigned int m_py; /// The total number of locations. unsigned int m_nlocs; /// The id of the location. unsigned int m_loc_id; /// The x-y coordinates of the location in the location space. std::pair<unsigned int, unsigned int> m_loc_coords; public: problem_input() : m_nx(0), m_ny(0), m_nz(0), m_agg(0), m_px(0), m_py(0), m_nlocs(0), m_loc_id(0), m_loc_coords(0,0) {} problem_input(const unsigned int nx, const unsigned int ny, const unsigned int nz, const unsigned int agg, const unsigned int level, const unsigned int px, const unsigned int py) : m_nx(nx), m_ny(ny), m_nz(nz), m_agg(agg), m_level(level), m_px(px), m_py(py), m_nlocs(stapl::get_num_locations()), m_loc_id(stapl::get_location_id()), m_loc_coords(0,0) { stapl_assert(m_px*m_py == m_nlocs, "The product of the last two arguments must be the number of locations."); stapl_assert(m_nx/m_px >= m_agg, "Num cells on location must be greater than the aggregation factor."); stapl_assert(m_ny/m_py >= m_agg, "Num cells on location must be greater than the aggregation factor."); stapl_assert(m_nz >= m_agg, "Num cells on location must be greater than the aggregation factor."); m_loc_coords.first = m_loc_id / m_py; m_loc_coords.second = m_loc_id % m_py; } unsigned int nx() const { return m_nx; } unsigned int ny() const { return m_ny; } unsigned int nz() const { return m_nz; } unsigned int agg() const { return m_agg; } unsigned int level() const { return m_level; } unsigned int px() const { return m_px; } unsigned int py() const { return m_py; } unsigned int pz() const { return 1; } unsigned int get_num_locations() const { return m_nlocs; } unsigned int get_location_id() const { return m_loc_id; } unsigned int location_x_coord() const { return m_loc_coords.first; } unsigned int location_y_coord() const { return m_loc_coords.second; } std::pair<unsigned int, unsigned int> location_coords() const { return m_loc_coords; } }; ////////////////////////////////////////////////////////////////////// /// @brief Specifies the supervertex id and which cells/cellsets of the graph /// view at the lower level of the hierarchy will be grouped into a /// supervertex at the level of the @ref hierarchical_graph_view that is being /// constructed. /// /// The partitioner assumes the spatial domain is a regular three-dimension /// brick mesh. ////////////////////////////////////////////////////////////////////// class regular_grid_partitioner { public: typedef stapl::domset1D<size_t> domain_type; private: typedef stapl::static_array<size_t> desc_cont_type; typedef stapl::static_array<domain_type> dom_cont_type; problem_input m_input; public: typedef stapl::array_view<desc_cont_type> descriptor_view_type; typedef stapl::array_view<dom_cont_type> view_type; regular_grid_partitioner(problem_input const& input) : m_input(input) {} ////////////////////////////////////////////////////////////////////// /// @brief Group vertices into supervertices. /// @param graph_view View of the graph at the lower level of the hierarchy. /// @param level Level of the hierarchy being created. /// @return pair of stapl::array containers, the elements of the first are /// the domains of the supervertices to be created, and the elements of /// the second are the ids of the supervertices. ////////////////////////////////////////////////////////////////////// template <typename GraphView> std::pair<view_type, descriptor_view_type> operator()(GraphView const& graph_view, std::size_t level) const { // number of vertices in graph at lower level is original size / 2^level-2 // because level 1 doesn't reduce number of vertices. size_t two_lm2 = 1 << (level-2); size_t ax = m_input.agg(); size_t ay = m_input.agg(); size_t az = m_input.agg(); if (level == 1) { two_lm2 = 1; ax = ay = az = 1; } size_t nx = m_input.nx() / two_lm2; size_t ny = m_input.ny() / two_lm2; size_t nz = m_input.nz() / two_lm2; // Convenient constants size_t yz_plane_size = ny * nz; size_t z_col_size = nz; size_t total_num_cellsets = (nx/ax) * (ny/ay) * (nz/az); //size_t loc_id = m_input.get_location_id(); //Declare the containers and views desc_cont_type* cellset_ids_cont = new desc_cont_type(total_num_cellsets); dom_cont_type* cellset_doms_cont = new dom_cont_type(total_num_cellsets); // Compute the first cell id on this location. size_t start_cell_id = yz_plane_size * (nx/m_input.px()) * m_input.location_x_coord() + z_col_size * (ny/m_input.py()) * m_input.location_y_coord(); size_t ncsx = nx / ax; size_t ncsy = ny / ay; size_t ncsz = nz / az; size_t yz_cs_plane_size = ncsy * ncsz; // Compute which stacks of cellsets we'll be computing. size_t start_id = yz_cs_plane_size*(ncsx/m_input.px())*m_input.location_x_coord() + ncsz * (ncsy/m_input.py()) * m_input.location_y_coord(); size_t cellset_id = start_id; for (size_t csx = 0; csx != ncsx/m_input.px(); ++csx) { for (size_t csy = 0; csy != ncsy/m_input.py(); ++csy) { for (size_t csz = 0; csz != ncsz/m_input.pz(); ++csz) { size_t cs_start_cell_id = start_cell_id; cs_start_cell_id += csz*az + csy*ay*z_col_size + csx*ax*yz_plane_size; domain_type v; std::vector<size_t> dbg_info; for (size_t x = 0; x != ax; ++x) { for (size_t y = 0; y != ay; ++y) { for (size_t z = 0; z != az; ++z) { v += cs_start_cell_id + z + y*z_col_size + x*yz_plane_size; dbg_info.push_back( cs_start_cell_id + z + y*z_col_size + x*yz_plane_size); } } } cellset_id = start_id + csz + csy*ncsz/m_input.pz() + csx*yz_cs_plane_size; cellset_ids_cont->operator[](cellset_id) = cellset_id; cellset_doms_cont->operator[](cellset_id) = v; // std::ostringstream info("Location "); // info << loc_id << " Cellset " << cellset_id << "("; // for (std::vector<size_t>::iterator i = dbg_info.begin(); // i != dbg_info.end(); ++i) // info << *i << " "; // info << ")\n"; // printf("%s",info.str().c_str()); } } } // FIXME: I think a rmi_synchronize may be all we need here. stapl::rmi_fence(); return std::make_pair(view_type(cellset_doms_cont), descriptor_view_type(cellset_ids_cont)); } }; ////////////////////////////////////////////////////////////////////// /// @brief Add edges between the supervertices at the level of the hierarchical /// graph view that is being created. /// /// Assumes the spatial domain is a regular three-dimension brick mesh. Results /// in an undirected graph. ////////////////////////////////////////////////////////////////////// class cellset_edge_functor { problem_input m_input; public: typedef normal value_type; cellset_edge_functor(problem_input const& input) : m_input(input) {} template <typename Grid> void operator()(Grid* g, std::size_t level) const { // dimensions of the grid at this level are n[x|y|z]/2^(level-1) // level-1 is divisor because level 1 contains a cellset for every cell. size_t two_l = 1 << (level-1); size_t nx = m_input.nx() / two_l; size_t ny = m_input.ny() / two_l; size_t nz = m_input.nz() / two_l; // dimensions of local portion of the grid size_t lx = nx / m_input.px(); size_t ly = ny / m_input.py(); size_t lz = nz / m_input.pz(); size_t px = m_input.px(); size_t py = m_input.py(); size_t xi = m_input.location_x_coord(); size_t yi = m_input.location_y_coord(); size_t z_col_size = nz; size_t yz_plane_size = ny * z_col_size; // std::stringstream dbg; // dbg << "Location " << m_input.get_location_id() << "\n"; size_t start_cellset_id = xi * lx * yz_plane_size + yi * ly * z_col_size; for (size_t i = 0; i != lx; ++i) { for (size_t j = 0; j != ly; ++j) { for (size_t k = 0; k != lz; ++k) { size_t cellset_id = start_cellset_id + k + j*lz + i*yz_plane_size; // dbg << "Cellset " << cellset_id << ": "; if ((k != 0) && (k != z_col_size-1)) { g->add_edge_async(cellset_id, cellset_id-1, normal(0.,0.,-1.)); g->add_edge_async(cellset_id, cellset_id+1, normal(0.,0.,1.)); // dbg << cellset_id-1 << normal(0,0,-1) << " "; // dbg << cellset_id+1 << normal(0,0,1) << " "; } else { if (z_col_size != 1) { // No self edges in the cellset graph. if (k == 0) { g->add_edge_async(cellset_id, cellset_id+1, normal(0.,0.,1.)); // dbg << cellset_id+1 << normal(0,0,1) << " "; } else { g->add_edge_async(cellset_id, cellset_id-1, normal(0.,0.,-1.)); // dbg << cellset_id-1 << normal(0,0,-1) << " "; } } } if ((yi != 0) && (yi != py-1)) { g->add_edge_async(cellset_id, cellset_id-z_col_size, normal(0.,-1.,0.)); g->add_edge_async(cellset_id, cellset_id+z_col_size, normal(0.,1.,0.)); // dbg << cellset_id-z_col_size << normal(0,-1,0) << " "; // dbg << cellset_id+z_col_size << normal(0,1,0) << " "; } else { if (py != 1) { // No self edges in the cellset graph. if (yi == 0) { if (j != 0) { g->add_edge_async(cellset_id, cellset_id-z_col_size, normal(0.,-1.,0.)); g->add_edge_async(cellset_id, cellset_id+z_col_size, normal(0.,1.,0.)); // dbg << cellset_id-z_col_size << normal(0,-1,0) << " "; // dbg << cellset_id+z_col_size << normal(0,1,0) << " "; } else { g->add_edge_async(cellset_id, cellset_id+z_col_size, normal(0.,1.,0.)); // dbg << cellset_id+z_col_size << normal(0,1,0) << " "; } } else { if (j != ly-1) { g->add_edge_async(cellset_id, cellset_id-z_col_size, normal(0.,-1.,0.)); g->add_edge_async(cellset_id, cellset_id+z_col_size, normal(0.,1.,0.)); // dbg << cellset_id-z_col_size << normal(0,-1,0) << " "; // dbg << cellset_id+z_col_size << normal(0,1,0) << " "; } else { g->add_edge_async(cellset_id, cellset_id-z_col_size, normal(0.,-1.,0.)); // dbg << cellset_id-z_col_size << normal(0,-1,0) << " "; } } } } if ((xi != 0) && (xi != px-1)) { g->add_edge_async(cellset_id, cellset_id-yz_plane_size, normal(-1.,0.,0.)); g->add_edge_async(cellset_id, cellset_id+yz_plane_size, normal(1.,0.,0.)); // dbg << cellset_id-yz_plane_size << normal(-1,0,0) << " "; // dbg << cellset_id+yz_plane_size << normal(1,0,0) << " "; } else { if (px != 1) { // No self edges in the cellset graph. if (xi == 0) { if (i != 0) { g->add_edge_async(cellset_id, cellset_id-yz_plane_size, normal(-1.,0.,0.)); g->add_edge_async(cellset_id, cellset_id+yz_plane_size, normal(1.,0.,0.)); // dbg << cellset_id-yz_plane_size << normal(-1,0,0) << " "; // dbg << cellset_id+yz_plane_size << normal(1,0,0) << " "; } else { g->add_edge_async(cellset_id, cellset_id+yz_plane_size, normal(1.,0.,0.)); // dbg << cellset_id+yz_plane_size << normal(1,0,0) << " "; } } else { if (i != lx-1) { g->add_edge_async(cellset_id, cellset_id-yz_plane_size, normal(-1.,0.,0.)); g->add_edge_async(cellset_id, cellset_id+yz_plane_size, normal(1.,0.,0.)); // dbg << cellset_id-yz_plane_size << normal(-1,0,0) << " "; // dbg << cellset_id+yz_plane_size << normal(1,0,0) << " "; } else { g->add_edge_async(cellset_id, cellset_id-yz_plane_size, normal(-1.,0.,0.)); // dbg << cellset_id-yz_plane_size << normal(-1,0,0) << " "; } } } } // dbg << "\n"; } } } stapl::rmi_fence(); // if (level < 3) // printf("%s",dbg.str().c_str()); } }; ////////////////////////////////////////////////////////////////////// /// @brief Represents the discretized spatial domain. The vertex /// property is a cell and the edge property is the cell face normal. ////////////////////////////////////////////////////////////////////// struct spatial_grid : public stapl::dynamic_graph<stapl::DIRECTED, stapl::MULTIEDGES, cell, normal> {}; typedef spatial_grid grid_type; typedef stapl::graph_view<grid_type> grid_view_type; ////////////////////////////////////////////////////////////////////// /// @brief Construct the discretized spatial domain /// @param grid Empty graph that will be populated. /// @param input Information on the size of grid to be created. ////////////////////////////////////////////////////////////////////// int create_grid(grid_type& grid, problem_input const& input) { unsigned int ax = input.nx()/input.px(); unsigned int ay = input.ny()/input.py(); unsigned int local_yz_plane_size = ay*input.nz(); unsigned int yz_plane_size = input.ny()*input.nz(); unsigned int start_cell_id = input.nz()*input.ny()*ax * input.location_x_coord() + input.nz()*ay * input.location_y_coord(); unsigned int cell_id = start_cell_id; double init_value(0.); for (unsigned int x = ax*input.location_x_coord(); x != ax*(input.location_x_coord()+1); ++x) { for (unsigned int y = ay*input.location_y_coord(); y != ay*(input.location_y_coord()+1); ++y) { for (unsigned int z = 0; z != input.nz(); ++z) { if (cell_id == 0) { double nz_val = 1000000000000000000.; grid.add_vertex(cell_id, cell(nz_val)); } else grid.add_vertex(cell_id, cell(init_value)); ++cell_id; } } cell_id = cell_id - local_yz_plane_size + yz_plane_size; } // Fence required before adding edges. // The graph doesn't buffer add_edge calls. stapl::rmi_fence(); cell_id = start_cell_id; for (unsigned int x = ax*input.location_x_coord(); x != ax*(input.location_x_coord()+1); ++x) { for (unsigned int y = ay*input.location_y_coord(); y != ay*(input.location_y_coord()+1); ++y) { for (unsigned int z = 0; z != input.nz(); ++z) { if ((z != 0) && (z != input.nz()-1)) { grid.add_edge_async(cell_id, cell_id-1, normal(0.,0.,-1.)); grid.add_edge_async(cell_id, cell_id+1, normal(0.,0.,1.)); } else { if (z == 0) { grid.add_edge_async(cell_id, cell_id, normal()); // Z-neg boundary grid.add_edge_async(cell_id, cell_id+1, normal(0.,0.,1.)); // Z-pos } else { grid.add_edge_async(cell_id, cell_id-1, normal(0.,0.,-1.)); // Z-neg grid.add_edge_async(cell_id, cell_id, normal()); // Z-pos boundary } } if ((y != 0) && (y != input.ny()-1)) { grid.add_edge_async(cell_id, cell_id-input.nz(), normal(0.,-1.,0.)); grid.add_edge_async(cell_id, cell_id+input.nz(), normal(0.,1.,0.)); } else { if (y == 0) { grid.add_edge_async(cell_id, cell_id, normal()); grid.add_edge_async(cell_id, cell_id+input.nz(), normal(0.,1.,0.)); } else { grid.add_edge_async(cell_id, cell_id-input.nz(), normal(0.,-1.,0.)); grid.add_edge_async(cell_id, cell_id, normal()); } } if ((x != 0) && (x != input.nx()-1)) { grid.add_edge_async(cell_id, cell_id-yz_plane_size, normal(-1.,0.,0.)); grid.add_edge_async(cell_id, cell_id+yz_plane_size, normal(1.,0.,0.)); } else { if (x == 0) { grid.add_edge_async(cell_id, cell_id, normal()); grid.add_edge_async(cell_id, cell_id+yz_plane_size, normal(1.,0.,0.)); } else { grid.add_edge_async(cell_id, cell_id-yz_plane_size, normal(-1.,0.,0.)); grid.add_edge_async(cell_id, cell_id, normal()); } } ++cell_id; } } cell_id = cell_id - local_yz_plane_size + yz_plane_size; } stapl::rmi_fence(); // stapl::write_graph(grid, std::cout); return 0; } ////////////////////////////////////////////////////////////////////// /// @brief Determine to which of the eight octants the provided normal belongs. ////////////////////////////////////////////////////////////////////// unsigned int octant(normal const& n) { unsigned int octant = 0; if (n.m_x < 0) octant += 4; if (n.m_y < 0) octant += 2; if (n.m_z < 0) ++octant; return octant; } ////////////////////////////////////////////////////////////////////// /// @brief Create a vector of random normals that represent directions. /// @return vector of directions that are uniformly distributed across octants. ////////////////////////////////////////////////////////////////////// struct create_directions { typedef std::vector<normal> result_type; unsigned int m_num_dirs; create_directions(unsigned int num_dirs) : m_num_dirs(num_dirs) {} result_type operator()(void) const { result_type directions(m_num_dirs); srand48((unsigned int)(drand48()*1000000000)); const double pi = 3.14159265358979323846; unsigned int angles_per_octant = m_num_dirs >> 3; std::vector<unsigned int> octant_counts(8, 0); unsigned int total_dir_count = 0; while (total_dir_count != m_num_dirs) { // Method for random points on unit sphere taken from // http://mathworld.wolfram.com/SpherePointPicking.html double theta = 2*pi*drand48(); // theta = 2*pi*u double phi = std::acos(2*drand48()-1); // phi = acos(2*(v-1)) normal dir(std::cos(phi)*std::sin(theta), std::sin(phi)*std::sin(theta), std::cos(theta)); unsigned int oct = octant(dir); if (octant_counts[oct] != angles_per_octant) { ++total_dir_count; // Storing sorted by octant to eliminate explicit angle aggregation. directions[oct*angles_per_octant + octant_counts[oct]] = dir; octant_counts[oct] += 1; } } return directions; } }; template <typename IncomingPsi> struct filter_sweep_result; template <typename IncomingPsi> inline bool operator==(filter_sweep_result<IncomingPsi> const&, filter_sweep_result<IncomingPsi> const&); ////////////////////////////////////////////////////////////////////// /// @brief The value transmitted across the face of a cell when it is processed /// in the sweep. ////////////////////////////////////////////////////////////////////// class cell_face_value { /// Id of the cell that was processed. unsigned int m_source_id; /// Id of the cell that will receive the value. unsigned int m_id; /// Normal of the face of the processed cell. normal m_normal; /// Value being transmitted across the face. double m_value; public: cell_face_value() : m_source_id(std::numeric_limits<unsigned int>::max()), m_id(std::numeric_limits<unsigned int>::max()), m_normal(), m_value(0.) {} cell_face_value(const unsigned int source, const unsigned int id, normal norm, double const& value) : m_source_id(source), m_id(id), m_normal(norm), m_value(value) {} void define_type(stapl::typer& t) { t.member(m_source_id); t.member(m_id); t.member(m_normal); t.member(m_value); } unsigned int id() const { return m_id; } unsigned int source_id() const { return m_source_id; } normal get_normal() const { return m_normal; } double const& value() const { return m_value; } void value(double const& v) { m_value = v; } }; ////////////////////////////////////////////////////////////////////// /// @brief The value transmitted across the face of a cellset when it is /// processed by the sweep. /// /// The cellset face is an aggregation of the faces of the components it /// contains. For example, at the lowest level the cellset face is a cell face. /// For each level up in the hierarchical graph view the cellset face is an /// aggregation of cellset faces from the lower level. ////////////////////////////////////////////////////////////////////// template <typename ComponentFace> class cellset_face_value { /// Id of the cellset processed by the sweep. unsigned int m_source_id; /// Id of the cellset that will receive the value. unsigned int m_id; /// Normal of the face of the cellset processed by the sweep. normal m_normal; /// Collection of the faces of the components that make up this cellset face. std::vector<ComponentFace> m_surface_values; public: typedef std::vector<ComponentFace> subface_set_type; cellset_face_value() : m_source_id(std::numeric_limits<unsigned int>::max()), m_id(std::numeric_limits<unsigned int>::max()), m_normal(), m_surface_values() {} cellset_face_value(const unsigned int src_id, const unsigned int id, normal const& norm) : m_source_id(src_id), m_id(id), m_normal(norm), m_surface_values() {} cellset_face_value(const unsigned int src_id, const unsigned int id, normal const& norm, std::vector<ComponentFace> const& surface_values) : m_source_id(src_id), m_id(id), m_normal(norm), m_surface_values(surface_values) {} cellset_face_value(ComponentFace const& face) : m_source_id(face.source_id()), m_id(face.id()), m_normal(face.get_normal()), m_surface_values(1, face) {} unsigned int source_id() const { return m_source_id; } unsigned int id() const { return m_id; } normal get_normal() const { return m_normal; } std::vector<ComponentFace> const& value() const { return m_surface_values; } void push_back(ComponentFace const& fv) { m_surface_values.push_back(fv); } void define_type(stapl::typer& t) { t.member(m_source_id); t.member(m_id); t.member(m_normal); t.member(m_surface_values); } }; namespace stapl { ////////////////////////////////////////////////////////////////////// /// @brief Specialization of @ref proxy for @ref cell_face_value. ////////////////////////////////////////////////////////////////////// template <typename Accessor> class proxy<cell_face_value, Accessor> : public Accessor { friend class proxy_core_access; typedef cell_face_value target_t; public: explicit proxy(Accessor const& acc) : Accessor(acc) {} operator target_t() const { return Accessor::read(); } unsigned int id() const { return Accessor::const_invoke(&target_t::id); } double value() const { return Accessor::const_invoke(&target_t::value); } }; ////////////////////////////////////////////////////////////////////// /// @brief Specialization of @ref proxy for @ref cellset_face_value. ////////////////////////////////////////////////////////////////////// template <typename ComponentFace, typename Accessor> class proxy<cellset_face_value<ComponentFace>, Accessor> : public Accessor { friend class proxy_core_access; typedef cellset_face_value<ComponentFace> target_t; public: typedef typename target_t::subface_set_type subface_set_type; explicit proxy(Accessor const& acc) : Accessor(acc) {} operator target_t() const { return Accessor::read(); } unsigned int source_id() const { return Accessor::const_invoke(&target_t::source_id); } unsigned int id() const { return Accessor::const_invoke(&target_t::id); } normal get_normal() const { return Accessor::const_invoke(&target_t::get_normal); } std::vector<ComponentFace> const& value() const { return Accessor::const_invoke(&target_t::value); } }; } ////////////////////////////////////////////////////////////////////// /// @brief Work function used to filter the result of a sweep task to select /// one of the cellset faces. /// /// There is a filter functor for every consumer of a cellset task, because /// each cellset that the next wave front of tasks will process only need one /// face from the cellsets on which it depends. This reduces the amount of data /// transmitted between locations significantly. /// /// @todo Re-enable filtering now that multiple filters from a given location /// and filters for local consumer tasks are supported. ////////////////////////////////////////////////////////////////////// template <typename IncomingPsi> struct filter_sweep_result { protected: normal m_normal; friend bool operator==<>(filter_sweep_result<IncomingPsi> const&, filter_sweep_result<IncomingPsi> const&); public: typedef IncomingPsi result_type; filter_sweep_result(normal const& n) : m_normal(n) {} void define_type(stapl::typer& t) { t.member(m_normal); } result_type operator()(std::vector<result_type> const& sweep_result) const { typename result_type::const_iterator res = sweep_result.begin(); for (; res != sweep_result.end(); ++res) { if ((*res).normal() * m_normal > 0) return *res; } printf("ERROR: result for cellset not found.\n"); return sweep_result[0]; } result_type operator()(result_type const& result) const { if (result.get_normal() * m_normal < 0) printf("ERROR: result for cellset not found.\n"); return result; } }; template <typename IncomingPsi> inline bool operator==(filter_sweep_result<IncomingPsi> const& lhs, filter_sweep_result<IncomingPsi> const& rhs) { return lhs.m_normal == rhs.m_normal; } ////////////////////////////////////////////////////////////////////// /// @brief Metafunction to compute the type of a cellset face at a given level /// of the nested sweep. ////////////////////////////////////////////////////////////////////// template <int Level> struct cellset_face_type { typedef cellset_face_value<typename cellset_face_type<Level-1>::type> type; typedef std::vector<type> result_type; }; ////////////////////////////////////////////////////////////////////// /// @brief Specialization of the metafunction to compute the type of a cellset /// face of the most nested sweep. ////////////////////////////////////////////////////////////////////// template <> struct cellset_face_type<0> { typedef cellset_face_value<cell_face_value> type; typedef std::vector<type> result_type; }; ////////////////////////////////////////////////////////////////////// /// @brief Id and successor cellset information of the cellset on which a /// nested sweep has been invoked. /// /// This is needed to properly construct the resulting cellset faces of the /// nested sweep. ////////////////////////////////////////////////////////////////////// struct parent_cellset_info { /// @brief Id of the cellset that is being processed by the nested sweep. /// Equivalent to source_id in @ref cell_face_value and /// @ref cellset_face_value. unsigned int parent_id; /// Id of the successor of the processed cellset along the x-axis. std::pair<unsigned int, normal> x_succ; /// Id of the successor of the processed cellset along the y-axis. std::pair<unsigned int, normal> y_succ; /// Id of the successor of the processed cellset along the z-axis. std::pair<unsigned int, normal> z_succ; parent_cellset_info(unsigned int id) : parent_id(id) {} void define_type(stapl::typer& t) { t.member(parent_id); t.member(x_succ); t.member(y_succ); t.member(z_succ); } }; ////////////////////////////////////////////////////////////////////// /// @brief Populate the PARAGRAPH of a sweep with tasks. ////////////////////////////////////////////////////////////////////// template <typename SweepMethod> class sweep_factory : public factory_wf { ////////////////////////////////////////////////////////////////////// /// @brief Information about the set of cellsets to be swept. ////////////////////////////////////////////////////////////////////// struct cellsets_info { std::vector<std::size_t> m_descriptors; std::size_t m_max_descriptor; std::vector<std::size_t> m_x_surface; std::vector<std::size_t> m_y_surface; std::vector<std::size_t> m_z_surface; ////////////////////////////////////////////////////////////////////// /// @brief Extracts the cellset information from the set of graph vertices /// provided. /// @param begin Iterator to the first cellset. /// @param end Iterator one past the last cellset to be processed. /// @param ncellsets Number of cellsets to be swept. Provided to allow /// vectors to reserve the necessary space. ////////////////////////////////////////////////////////////////////// template <typename VertexIterator> cellsets_info(VertexIterator begin, VertexIterator end, std::size_t ncellsets) : m_max_descriptor(0) { m_descriptors.reserve(ncellsets); for (VertexIterator i = begin; i != end; ++i) { std::size_t descriptor = (*i).descriptor(); m_descriptors.push_back(descriptor); m_max_descriptor = m_max_descriptor < descriptor ? descriptor : m_max_descriptor; } // sorting gives me the cellsets in z-y-x order. std::sort(m_descriptors.begin(), m_descriptors.end()); } std::vector<std::size_t> const& descriptors() const { return m_descriptors; } std::size_t max() const { return m_max_descriptor; } ////////////////////////////////////////////////////////////////////// /// @brief Check if the specified cellset will be processed by the current /// sweep. Used to identify which neighboring cellsets are on the /// boundary of the higher level cellset. ////////////////////////////////////////////////////////////////////// // check if the cellset will be processed by the current sweep. bool is_sibling(std::size_t desc) const { return std::binary_search(m_descriptors.begin(), m_descriptors.end(), desc); } }; ////////////////////////////////////////////////////////////////////// /// @brief Functor used to build predecessor list for a cellset. ////////////////////////////////////////////////////////////////////// struct categorize_edge { double epsilon; normal sweep_direction; /// Cellset that will be processed by the task being constructed. cellsets_info const& m_cs_info; /// Ids of the cellsets whose values this cellset will receive. std::vector<unsigned int> predecessors; /// @brief Ids of the cellsets that are processed by the same nested sweep /// that this cellset is processed by. std::vector<unsigned int> sibling_preds; /// The number of cellsets that will receive this cellset's result. std::size_t num_sibling_succs; /// @brief The number of cellsets that will receive this cellset's result, /// and will be processed by another nested sweep. std::size_t num_boundary_succs; /// @brief The number of faces this cellset has on the boundary of the /// higher level cellset. std::size_t boundary_faces; categorize_edge(normal const& dir, cellsets_info const& cs_info) : epsilon(0.000001), sweep_direction(dir), m_cs_info(cs_info), num_sibling_succs(0), num_boundary_succs(0), boundary_faces(0) {} categorize_edge const& operator=(categorize_edge const& other) { epsilon = other.epsilon; sweep_direction = other.sweep_direction; // m_cs_info is skipped as it is a reference both objects share. predecessors = other.predecessors; sibling_preds = other.sibling_preds; num_sibling_succs = other.num_sibling_succs; num_boundary_succs = other.num_boundary_succs; boundary_faces = other.boundary_faces; return *this; } ////////////////////////////////////////////////////////////////////// /// @brief Increment boundary faces depending on the normal. /// /// This determines the cellset boundary faces to which this cellset /// contributes. ////////////////////////////////////////////////////////////////////// void update_boundary_face(normal const& n) { if (n.m_x < -epsilon || n.m_x > epsilon) boundary_faces += 4; else if (n.m_y < -epsilon || n.m_y > epsilon) boundary_faces += 2; else if (n.m_z < -epsilon || n.m_z > epsilon) boundary_faces += 1; } template <typename EdgeIterator> void operator()(EdgeIterator& ei) { // Given an edge we want to know: // 1. predecessor or successor // 2. For predecessors // a. boundary input required? // b. who are sibling predecessors? // 3. For successors // a. boundary output? // 1. which boundary face? normal property = ei.property(); double product = property * sweep_direction; if (product > epsilon) { // target vertex is a successor. if (m_cs_info.is_sibling(ei.target())) ++num_sibling_succs; else { ++num_boundary_succs; update_boundary_face(property); } } else if (product < 0-epsilon) { // target vertex is a predecessor. if (m_cs_info.is_sibling(ei.target())) sibling_preds.push_back(ei.target()); else predecessors.push_back(ei.target()); } // otherwise the target is independent of this vertex } ////////////////////////////////////////////////////////////////////// /// @brief Reset predecessor and successor information to allow the struct /// to be reused. ////////////////////////////////////////////////////////////////////// void reset() { predecessors.clear(); sibling_preds.clear(); num_sibling_succs = 0; num_boundary_succs = 0; boundary_faces = 0; } }; /// Type information of the higher level cellset. typedef cellset_face_type<SweepMethod::level+1> type_comp; public: typedef stapl::null_coarsener coarsener_type; typedef typename type_comp::result_type result_type; private: SweepMethod m_sweep_wf; normal m_sweep_direction; /// Information about the cellset that we are sweeping. parent_cellset_info m_parent_cellset; /// @todo I'd rather the inputs to the cellset come in to the function /// operator as views, but for now this is what we do. result_type m_inc_faces; typedef stapl::result_of::localize_object< typename SweepMethod::result_type::value_type > localized_object_type; public: sweep_factory(SweepMethod const& sweep_wf, normal const& sweep_direction, parent_cellset_info const& parent_cellset, result_type const& inc_faces) : m_sweep_wf(sweep_wf), m_sweep_direction(sweep_direction), m_parent_cellset(parent_cellset), m_inc_faces(inc_faces) {} coarsener_type get_coarsener() const { return coarsener_type(); } ////////////////////////////////////////////////////////////////////// /// @brief Work function to collect the cellset faces of the tasks on each /// location performing the nested sweep. ////////////////////////////////////////////////////////////////////// template <typename Result> struct build_cellset_face_wf { typedef Result result_type; result_type m_result; build_cellset_face_wf(unsigned int const& source_id, std::pair<unsigned int, normal> const& succ_info) : m_result(source_id, succ_info.first, succ_info.second) {} template <typename AggregatedFaces> result_type operator()(AggregatedFaces& faces) { normal norm = m_result.get_normal(); std::size_t num_faces = faces.size(); for (std::size_t i = 0; i != num_faces; ++i) { const typename AggregatedFaces::reference face_vec = faces[i]; // each face is a vector of component faces. Search for correct normal. typename AggregatedFaces::reference::const_iterator face_it = face_vec.begin(); typename AggregatedFaces::reference::const_iterator face_end = face_vec.end(); for (; face_it != face_end; ++face_it) { if (norm * (*face_it).get_normal() > 0) m_result.push_back(*face_it); } } return m_result; } result_type operator()(void) { return m_result; } void define_type(stapl::typer& t) { t.member(m_result); } }; ////////////////////////////////////////////////////////////////////// /// @brief Work function to combine the cellset faces from each location /// into a single aggregation. ////////////////////////////////////////////////////////////////////// template <typename Result> struct merge_cellset_face_wf { typedef Result result_type; result_type m_result; merge_cellset_face_wf(unsigned int const& source_id, std::pair<unsigned int, normal> const& succ_info) : m_result(source_id, succ_info.first, succ_info.second) {} template <typename AggregatedFaces> result_type operator()(AggregatedFaces& faces) { // face_type is a cellset_face_value. std::size_t num_faces = faces.size(); for (std::size_t i = 0; i != num_faces; ++i) { const typename AggregatedFaces::reference face_vec = faces[i]; typedef typename AggregatedFaces::reference::subface_set_type::const_iterator face_it; face_it fit = face_vec.value().begin(); face_it fend = face_vec.value().end(); for (; fit != fend; ++fit) { m_result.push_back(*fit); } } return m_result; } void define_type(stapl::typer& t) { t.member(m_result); } }; ////////////////////////////////////////////////////////////////////// /// @brief Work function to combine the cellset face results into a single /// value that is the result of the sweep on the higher level cellset. ////////////////////////////////////////////////////////////////////// template <typename Result> struct build_cellset_result { typedef Result result_type; template <typename Face0, typename Face1, typename Face2> result_type operator()(Face0 const& f0, Face1 const& f1, Face2 const& f2) { result_type res; res.push_back(f0); res.push_back(f1); res.push_back(f2); return res; } }; template <typename T> struct identity_filter { typedef T result_type; template <typename Ref> T operator()(Ref r) const { return r; } bool operator==(identity_filter const&) const { return true; } }; template <typename Result> struct identity_wf { typedef Result result_type; template <typename Ref> result_type operator()(Ref val) { return val; } }; ////////////////////////////////////////////////////////////////////// /// @brief Build the set of inputs for a cellset that come in from the /// boundary of the higher level cellset. ////////////////////////////////////////////////////////////////////// std::vector<localized_object_type> extract_task_inputs(std::size_t csid) { std::vector<localized_object_type> cs_inputs; cs_inputs.reserve(3); // for each face in m_inc_faces typename result_type::iterator face_it = m_inc_faces.begin(); typename result_type::iterator face_end = m_inc_faces.end(); for (; face_it != face_end; ++face_it) { typedef typename result_type::value_type::subface_set_type subface_set_t; subface_set_t const& subfaces = (*face_it).value(); // for each subface in face.value() typename subface_set_t::const_iterator subface_it = subfaces.begin(); typename subface_set_t::const_iterator subface_end = subfaces.end(); for (; subface_it != subface_end; ++subface_it) { if ((*subface_it).id() == csid) cs_inputs.push_back(localize_object(cs_in_type(*subface_it))); } } return cs_inputs; } template <typename TaskGraphView, typename GridView> void operator()(TaskGraphView const& tgv, GridView& grid_view) { typedef typename SweepMethod::result_type task_result; typedef typename SweepMethod::result_type::value_type filter_result; typedef typename GridView::vertex_descriptor vertex_descriptor; typedef typename GridView::vertex_iterator vertex_iterator; std::size_t loc_id = stapl::get_location_id(); std::size_t nlocs = stapl::get_num_locations(); std::size_t ncellsets = grid_view.size(); vertex_iterator gvi(grid_view.begin()), gvi_end(grid_view.end()); cellsets_info cs_info(gvi, gvi_end, ncellsets); categorize_edge edge_cat(m_sweep_direction, cs_info); // Naively splitting the task creation. Would like to spatially divide // the cellset according to organization of locations in the gang. This // requires constructing spatial layout of cellset from the grid_view. std::vector<std::size_t> const& descriptors = cs_info.descriptors(); std::size_t ndescriptors = ncellsets / nlocs; // The number of tasks generated by the factory is // ncellsets + 3 faces + 1 aggregator + nlocs-1 broadcasts. // tasks generated std::size_t task_id = 0; std::size_t num_succs; std::vector<std::size_t>::const_iterator descriptor = descriptors.begin() + ndescriptors*loc_id; std::vector<std::size_t>::const_iterator descriptor_end = descriptor + ndescriptors; for (; gvi != gvi_end; ++gvi) { vertex_descriptor cellset_id = (*gvi).descriptor(); //FIXME: I'd rather iterate descriptor and call grid_view.find_vertex(), //but that doesn't compile as the graph container iterator returned by //the find_vertex implementation isn't convertible to vertex_iterator. if (!std::binary_search(descriptor, descriptor_end, cellset_id)) continue; if ((cellset_id == 8) || (cellset_id == 6) || (cellset_id == 5)) cellset_id = cellset_id; // task_id == cellset_id because predecessor info is specified in terms // of cellset ids by edge categorization. task_id = cellset_id; //every task in the sweep is consumed by three tasks. num_succs = 3; edge_cat.reset(); edge_cat = std::for_each((*gvi).begin(), (*gvi).end(), edge_cat); switch (edge_cat.boundary_faces) { case 1: cs_info.m_z_surface.push_back(cellset_id); break; case 2: cs_info.m_y_surface.push_back(cellset_id); break; case 3: cs_info.m_z_surface.push_back(cellset_id); cs_info.m_y_surface.push_back(cellset_id); break; case 4: cs_info.m_x_surface.push_back(cellset_id); break; case 5: cs_info.m_z_surface.push_back(cellset_id); cs_info.m_x_surface.push_back(cellset_id); break; case 6: cs_info.m_y_surface.push_back(cellset_id); cs_info.m_x_surface.push_back(cellset_id); break; case 7: cs_info.m_z_surface.push_back(cellset_id); cs_info.m_y_surface.push_back(cellset_id); cs_info.m_x_surface.push_back(cellset_id); } typedef std::vector<localized_object_type> task_inputs_t; task_inputs_t task_inputs; if (edge_cat.predecessors.size()) { // There are boundary inputs to collect for this cellset. task_inputs = extract_task_inputs(cellset_id); } // Note: num_succs = sweep consumers + surface consumers stapl_assert(task_inputs.size() <= 3, "Too many boundary inputs."); switch (task_inputs.size() + edge_cat.sibling_preds.size()) { case 0: tgv.add_task(task_id, m_sweep_wf, num_succs, std::make_pair(&grid_view, cellset_id)); break; case 1: if (task_inputs.size()) tgv.add_task(task_id, m_sweep_wf, num_succs, std::make_pair(&grid_view, cellset_id), task_inputs[0]); else tgv.add_task(task_id, m_sweep_wf, num_succs, std::make_pair(&grid_view, cellset_id), stapl::consume<task_result>(tgv, edge_cat.sibling_preds[0])); break; case 2: switch (task_inputs.size()) { case 0: tgv.add_task( task_id, m_sweep_wf, num_succs, std::make_pair(&grid_view, cellset_id), stapl::consume<task_result>(tgv, edge_cat.sibling_preds[0]), stapl::consume<task_result>(tgv, edge_cat.sibling_preds[1]) ); break; case 1: tgv.add_task( task_id, m_sweep_wf, num_succs, std::make_pair(&grid_view, cellset_id), task_inputs[0], stapl::consume<task_result>(tgv, edge_cat.sibling_preds[0]) ); break; case 2: tgv.add_task(task_id, m_sweep_wf, num_succs, std::make_pair(&grid_view, cellset_id), task_inputs[0], task_inputs[1]); } break; case 3: switch (task_inputs.size()) { case 0: tgv.add_task( task_id, m_sweep_wf, num_succs, std::make_pair(&grid_view, cellset_id), stapl::consume<task_result>(tgv, edge_cat.sibling_preds[0]), stapl::consume<task_result>(tgv, edge_cat.sibling_preds[1]), stapl::consume<task_result>(tgv, edge_cat.sibling_preds[2]) ); break; case 1: tgv.add_task( task_id, m_sweep_wf, num_succs, std::make_pair(&grid_view, cellset_id), task_inputs[0], stapl::consume<task_result>(tgv, edge_cat.sibling_preds[0]), stapl::consume<task_result>(tgv, edge_cat.sibling_preds[1]) ); break; case 2: tgv.add_task( task_id, m_sweep_wf, num_succs, std::make_pair(&grid_view, cellset_id), task_inputs[0], task_inputs[1], stapl::consume<task_result>(tgv, edge_cat.sibling_preds[0]) ); break; case 3: tgv.add_task(task_id, m_sweep_wf, num_succs, std::make_pair(&grid_view, cellset_id), task_inputs[0], task_inputs[1], task_inputs[2]); } break; default: printf("too many boundary inputs (%zu).\n",task_inputs.size()); } } // used in aggregated consume for the boundary tasks. identity_filter<task_result> id_filt; // Each location builds its component of the cellset faces. task_id = cs_info.m_max_descriptor + 3*loc_id + 1; num_succs = 1; tgv.add_task(task_id, build_cellset_face_wf<typename type_comp::type>( m_parent_cellset.parent_id, m_parent_cellset.z_succ), num_succs, stapl::consume<task_result>(tgv, cs_info.m_z_surface, id_filt)); ++task_id; num_succs = 1; tgv.add_task(task_id, build_cellset_face_wf<typename type_comp::type>( m_parent_cellset.parent_id, m_parent_cellset.y_succ), num_succs, stapl::consume<task_result>(tgv, cs_info.m_y_surface, id_filt)); ++task_id; num_succs = 1; tgv.add_task(task_id, build_cellset_face_wf<typename type_comp::type>( m_parent_cellset.parent_id, m_parent_cellset.x_succ), num_succs, stapl::consume<task_result>(tgv, cs_info.m_x_surface, id_filt)); // Location 0 collects components of each face and merges them. if (loc_id == 0) { identity_filter<typename type_comp::type> id_filt2; std::vector<std::size_t> preds(nlocs); std::size_t pred_id = cs_info.m_max_descriptor + 1; for (std::size_t pred_cnt = 0; pred_cnt != nlocs; ++pred_cnt, pred_id+=3) preds[pred_cnt] = pred_id; task_id = cs_info.m_max_descriptor + 3*nlocs + 1; num_succs = 1; tgv.add_task(task_id, merge_cellset_face_wf<typename type_comp::type>( m_parent_cellset.parent_id, m_parent_cellset.z_succ), num_succs, stapl::consume<typename type_comp::type>(tgv, preds, id_filt2)); ++task_id; num_succs = 1; pred_id = cs_info.m_max_descriptor + 2; for (std::size_t pred_cnt = 0; pred_cnt != nlocs; ++pred_cnt, pred_id+=3) preds[pred_cnt] = pred_id; tgv.add_task(task_id, merge_cellset_face_wf<typename type_comp::type>( m_parent_cellset.parent_id, m_parent_cellset.y_succ), num_succs, stapl::consume<typename type_comp::type>(tgv, preds, id_filt2)); ++task_id; num_succs = 1; pred_id = cs_info.m_max_descriptor + 3; for (std::size_t pred_cnt = 0; pred_cnt != nlocs; ++pred_cnt, pred_id+=3) preds[pred_cnt] = pred_id; tgv.add_task(task_id, merge_cellset_face_wf<typename type_comp::type>( m_parent_cellset.parent_id, m_parent_cellset.x_succ), num_succs, stapl::consume<typename type_comp::type>(tgv, preds, id_filt2)); ++task_id; num_succs = nlocs; tgv.add_task(task_id, build_cellset_result<result_type>(), num_succs, stapl::consume<typename type_comp::type>(tgv, task_id-3), stapl::consume<typename type_comp::type>(tgv, task_id-2), stapl::consume<typename type_comp::type>(tgv, task_id-1)); tgv.set_result(task_id); } else { std::size_t res_producer = cs_info.m_max_descriptor + 3*nlocs + 4; task_id = res_producer + loc_id; num_succs = 1; tgv.add_task(task_id, identity_wf<result_type>(), num_succs, stapl::consume<result_type>(tgv, res_producer)); tgv.set_result(task_id); } return; } bool finished() const { return true; } void define_type(stapl::typer& t) { t.member(m_sweep_wf); t.member(m_sweep_direction); } }; // Customized termination detection can be re-enabled when the other aspects of // nested parallelism have been resolved. // namespace stapl // { // namespace detail // { // template<typename SweepMethod> // struct // terminator_initializer<sweep_factory<SweepMethod> > // { // typedef counter_based_terminator terminator_t; // // template <typename Result, typename SVS> // terminator_t* // operator()(Result const& result, task_graph&, SVS&) const // { // terminator_t* t_ptr = new terminator_t(1); // // find_accessor<Result>()(result).request_notify( // std::bind(&counter_based_terminator::receive_notify, t_ptr) // ); // // return t_ptr; // } // }; // } // } ////////////////////////////////////////////////////////////////////// /// @brief Work function used in the lowest level sweep to process a single /// cell. ////////////////////////////////////////////////////////////////////// class cell_wf { typedef std::vector<cell_face_value> inc_cell_faces; typedef inc_cell_faces::iterator cell_input_iterator; normal m_sweep_direction; // FIXME - ARMI doesn't know how to pack refs like this. // Pass by value for now. // // std::vector<normal> const& m_directions; // /// The full set of directions. const std::vector<normal> m_directions; /// The octant we are sweeping. unsigned int m_sweep_octant; /// The set of incoming values for the cell. inc_cell_faces m_cell_inputs; public: cell_wf(normal const& sweep_direction, std::vector<normal> const& directions, unsigned int octant) : m_sweep_direction(sweep_direction), m_directions(directions), m_sweep_octant(octant) {} void define_type(stapl::typer& t) { t.member(m_sweep_direction); t.member(m_directions); t.member(m_sweep_octant); t.member(m_cell_inputs); } typedef std::vector<cell_face_value> result_type; ////////////////////////////////////////////////////////////////////// /// @brief Performs the core computation of processing a cell. /// /// This operator is also used for the first cell in a sweep as it has no /// incoming face values. ////////////////////////////////////////////////////////////////////// template <typename CellRef> result_type operator()(CellRef cell) { inc_cell_faces::iterator input_it = m_cell_inputs.begin(); double x_in(0.), y_in(0.), z_in(0.), epsilon(0.000001); typename CellRef::adj_edge_iterator edge = cell.begin(); typename CellRef::adj_edge_iterator edges_end = cell.end(); for (; edge != edges_end; ++edge) { // Edge normals are outfacing. A negative product is an incoming value. normal face_norm = (*edge).property(); if (face_norm * m_sweep_direction < -epsilon) { inc_cell_faces::iterator val_it = m_cell_inputs.begin(); for (; val_it != m_cell_inputs.end(); ++val_it) if (val_it->source_id() == (*edge).target()) break; stapl_assert(val_it != m_cell_inputs.end(), "Didn't find cell face input"); if ((face_norm.m_x > epsilon) || (face_norm.m_x < -epsilon)) x_in = val_it->value(); else if ((face_norm.m_y > epsilon) || (face_norm.m_y < -epsilon)) y_in = val_it->value(); else z_in = val_it->value(); } } // Take the value coming in on the face and multiply it by product of // the face normal and each direction in the octant. // Add that to the cell value. double x_contrib(0.), y_contrib(0.), z_contrib(0.); int angle = m_sweep_octant*10; int angle_end = (m_sweep_octant+1)*10; for (; angle != angle_end; ++angle) { x_contrib += x_in * m_directions[angle].m_x; y_contrib += y_in * m_directions[angle].m_y; z_contrib += z_in * m_directions[angle].m_z; } // Normalize x_contrib /= 10.0; y_contrib /= 10.0; z_contrib /= 10.0; double value = cell.property().value(); value += x_contrib + y_contrib + z_contrib; cell.property().value(value); // Adjust the value for each outgoing face. x_contrib = 0.; y_contrib = 0.; z_contrib = 0.; angle = m_sweep_octant*10; for (; angle != angle_end; ++angle) { x_contrib += value * m_directions[angle].m_x; y_contrib += value * m_directions[angle].m_y; z_contrib += value * m_directions[angle].m_z; } // Normalize x_contrib /= 10.0; y_contrib /= 10.0; z_contrib /= 10.0; result_type result; edge = cell.begin(); for (; edge != edges_end; ++edge) { // Edge normals are outfacing. A positive product is an outgoing value. normal face_norm = (*edge).property(); if (face_norm * m_directions[m_sweep_octant*10] > epsilon) { cell_face_value fv((*edge).source(), (*edge).target(), (*edge).property(), 0.0); if ((face_norm.m_x > epsilon) || (face_norm.m_x < -epsilon)) { fv.value(x_contrib); } else if ((face_norm.m_y > epsilon) || (face_norm.m_y < -epsilon)) { fv.value(y_contrib); } else { fv.value(z_contrib); } result.push_back(fv); } } return result; } template <typename CellRef, typename CellInc> result_type operator()(CellRef cell, const CellInc inc_face_val0) { m_cell_inputs.push_back(inc_face_val0); return (*this)(cell); } template <typename CellRef, typename CellInc0, typename CellInc1> result_type operator()(CellRef cell, const CellInc0 inc_face_val0, const CellInc1 inc_face_val1) { m_cell_inputs.push_back(inc_face_val0); m_cell_inputs.push_back(inc_face_val1); return (*this)(cell); } template <typename CellRef, typename CellInc0, typename CellInc1, typename CellInc2> result_type operator()(CellRef cell, const CellInc0 inc_face_val0, const CellInc1 inc_face_val1, const CellInc2 inc_face_val2) { m_cell_inputs.push_back(inc_face_val0); m_cell_inputs.push_back(inc_face_val1); m_cell_inputs.push_back(inc_face_val2); return (*this)(cell); } }; template <int Level, typename Result> struct make_sweep_paragraph; ////////////////////////////////////////////////////////////////////// /// @brief Work function to process a cellset. /// /// The cellset is processed by executing a nested sweep PARAGRAPH on the /// cellsets that make up this cellset. ////////////////////////////////////////////////////////////////////// template <int Level, typename ComponentFace> class cellset_wf { normal m_sweep_direction; std::vector<normal> const m_directions; unsigned int m_sweep_octant; // The octant we are sweeping. public: static const int level = Level; cellset_wf(normal const& sweep_direction, std::vector<normal> const& directions, unsigned int octant) : m_sweep_direction(sweep_direction), m_directions(directions), m_sweep_octant(octant) {} void define_type(stapl::typer& t) { t.member(m_sweep_direction); t.member(m_directions); t.member(m_sweep_octant); } typedef typename cellset_face_type<Level>::result_type result_type; template <typename CellSetRef> parent_cellset_info construct_this_info(CellSetRef cellset) { double epsilon(0.000001); parent_cellset_info this_info(cellset.descriptor()); // There are no edges on problem boundary, so we need defaults. std::pair<unsigned int, normal> default_succ(99, normal(0.,0.,0.)); default_succ.second.m_x = m_sweep_direction.m_x; this_info.x_succ = default_succ; default_succ.second.m_x = 0.; default_succ.second.m_y = m_sweep_direction.m_y; this_info.y_succ = default_succ; default_succ.second.m_y = 0.; default_succ.second.m_z = m_sweep_direction.m_y; this_info.z_succ = default_succ; // Iterate through neighboring cellsets. typename CellSetRef::adj_edge_iterator edge = cellset.begin(); typename CellSetRef::adj_edge_iterator edge_end = cellset.end(); for (; edge != edge_end; ++edge) { normal face_norm = (*edge).property(); if (m_sweep_direction * face_norm > 0) { if ((face_norm.m_x > epsilon) || (face_norm.m_x < -epsilon)) this_info.x_succ = std::make_pair(((*edge).target()), face_norm); else if ((face_norm.m_y > epsilon) || (face_norm.m_y < -epsilon)) this_info.y_succ = std::make_pair(((*edge).target()), face_norm); else this_info.z_succ = std::make_pair(((*edge).target()), face_norm); } } return this_info; } template <typename CellSetRef> result_type operator()(CellSetRef cellset) { std::stringstream out; std::size_t cellset_id = cellset.descriptor(); // Get the inner graph view and its domain. typedef typename CellSetRef::property_type comp_graph_type; comp_graph_type p = cellset.property(); out << "Loc " << stapl::get_location_id() << " cellset_wf<" << Level << ">" << cellset_id << " has size == " << p.size() << " "; // Sweep the cells. parent_cellset_info this_cellset = construct_this_info(cellset); return make_sweep_paragraph<Level, result_type>(out, this_cellset) (m_sweep_direction, m_directions, m_sweep_octant, p); } template <typename CellSetRef, typename CellSetInc> result_type operator()(CellSetRef cellset, const CellSetInc inc_face_values) { std::stringstream out; std::size_t cellset_id = cellset.descriptor(); // Get the inner graph view and its domain. typedef typename CellSetRef::property_type comp_graph_type; comp_graph_type p = cellset.property(); out << "Loc " << stapl::get_location_id() << " cellset_wf<" << Level << ">" << cellset_id << " has size == " << p.size() << " "; // Sweep the cells. parent_cellset_info this_cellset = construct_this_info(cellset); return make_sweep_paragraph<Level, result_type>(out, this_cellset, inc_face_values) (m_sweep_direction, m_directions, m_sweep_octant, p); } template <typename CellSetRef, typename CellSetInc0, typename CellSetInc1> result_type operator()(CellSetRef cellset, const CellSetInc0 inc_face_vals0, const CellSetInc1 inc_face_vals1) { std::stringstream out; std::size_t cellset_id = cellset.descriptor(); // Get the inner graph view and its domain. typedef typename CellSetRef::property_type comp_graph_type; comp_graph_type p = cellset.property(); out << "Loc " << stapl::get_location_id() << " cellset_wf<" << Level << ">" << cellset_id << " has size == " << p.size() << " "; // Sweep the cells. parent_cellset_info this_cellset = construct_this_info(cellset); return make_sweep_paragraph<Level, result_type>(out, this_cellset, inc_face_vals0, inc_face_vals1) (m_sweep_direction, m_directions, m_sweep_octant, p); } template <typename CellSetRef, typename CellSetInc0, typename CellSetInc1, typename CellSetInc2> result_type operator()(CellSetRef cellset, const CellSetInc0 inc_face_vals0, const CellSetInc1 inc_face_vals1, const CellSetInc2 inc_face_vals2) { std::stringstream out; std::size_t cellset_id = cellset.descriptor(); // Get the inner graph view and its domain. typedef typename CellSetRef::property_type comp_graph_type; comp_graph_type p = cellset.property(); out << "Loc " << stapl::get_location_id() << " cellset_wf<" << Level << ">" << cellset_id << " has size == " << p.size() << " "; // Sweep the cells. parent_cellset_info this_cellset = construct_this_info(cellset); return make_sweep_paragraph<Level, result_type>(out, this_cellset, inc_face_vals0, inc_face_vals1, inc_face_vals2) (m_sweep_direction, m_directions, m_sweep_octant, p); } }; ////////////////////////////////////////////////////////////////////// /// @brief Helper struct used to create the nested PARAGRAPH needed to /// process a cellset. ////////////////////////////////////////////////////////////////////// template <int Level, typename Result> struct make_sweep_paragraph { std::stringstream& m_out; parent_cellset_info const& m_parent_cellset; Result m_inc_faces; typedef stapl::result_of::localize_object< typename Result::value_type > inc_face_t; make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs) : m_out(out), m_parent_cellset(pcs), m_inc_faces() {} // These constructors are called on tasks that consume from other tasks. make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, Result const& inc_face) : m_out(out), m_parent_cellset(pcs), m_inc_faces() { for (typename Result::const_iterator f = inc_face.begin(); f != inc_face.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, Result const& inc_face0, Result const& inc_face1) : m_out(out), m_parent_cellset(pcs), m_inc_faces() { m_inc_faces.reserve(2); for (typename Result::const_iterator f = inc_face0.begin(); f != inc_face0.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } for (typename Result::const_iterator f = inc_face1.begin(); f != inc_face1.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, Result const& inc_face0, Result const& inc_face1, Result const& inc_face2) : m_out(out), m_parent_cellset(pcs), m_inc_faces() { m_inc_faces.reserve(3); for (typename Result::const_iterator f = inc_face0.begin(); f != inc_face0.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } for (typename Result::const_iterator f = inc_face1.begin(); f != inc_face1.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } for (typename Result::const_iterator f = inc_face2.begin(); f != inc_face2.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } // Constructors for a single boundary input. make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face0) : m_out(out), m_parent_cellset(pcs), m_inc_faces() { m_inc_faces.reserve(1); if ((*inc_face0).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face0); } make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face0, Result const& inc_face1) : m_out(out), m_parent_cellset(pcs), m_inc_faces() { m_inc_faces.reserve(2); if ((*inc_face0).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face0); for (typename Result::const_iterator f = inc_face1.begin(); f != inc_face1.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face0, Result const& inc_face1, Result const& inc_face2) : m_out(out), m_parent_cellset(pcs), m_inc_faces() { m_inc_faces.reserve(3); if ((*inc_face0).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face0); for (typename Result::const_iterator f = inc_face1.begin(); f != inc_face1.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } for (typename Result::const_iterator f = inc_face2.begin(); f != inc_face2.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } // Constructors for two boundary inputs. make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face0, inc_face_t const& inc_face1) : m_out(out), m_parent_cellset(pcs), m_inc_faces() { m_inc_faces.reserve(2); if ((*inc_face0).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face0); if ((*inc_face1).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face1); } make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face0, inc_face_t const& inc_face1, Result const& inc_face2) : m_out(out), m_parent_cellset(pcs), m_inc_faces() { m_inc_faces.reserve(3); if ((*inc_face0).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face0); if ((*inc_face1).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face1); for (typename Result::const_iterator f = inc_face2.begin(); f != inc_face2.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } // Constructors for strictly boundary input. make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face0, inc_face_t const& inc_face1, inc_face_t const& inc_face2) : m_out(out), m_parent_cellset(pcs), m_inc_faces() { m_inc_faces.reserve(3); if ((*inc_face0).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face0); if ((*inc_face1).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face1); if ((*inc_face2).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face2); } template <typename CellsetView> Result operator()(normal const& sweep_direction, std::vector<normal> const& directions, unsigned int octant, CellsetView& cellset_view) { /* m_out << "nested cellset paragraph on ("; typename CellsetView::vertex_iterator it, it_end; it = cellset_view.begin(); it_end = cellset_view.end(); for (; it != it_end; ++it) m_out << (*it).descriptor() << " "; m_out << ")\n"; printf("%s",m_out.str().c_str()); */ // pull the correct face out of each result typedef cellset_wf<Level-1, typename cellset_face_type<Level-1>::type> cellset_wf_type; return stapl::make_paragraph( sweep_factory<cellset_wf_type>( cellset_wf_type(sweep_direction, directions, octant), sweep_direction, m_parent_cellset, m_inc_faces), /*nested==*/true, cellset_view)(); } }; ////////////////////////////////////////////////////////////////////// /// @brief Specialization for the most nested sweep that invokes cell_wf on /// the cell to be processed. ////////////////////////////////////////////////////////////////////// template <typename Result> struct make_sweep_paragraph<0, Result> { std::stringstream& m_out; parent_cellset_info const& m_parent_cellset; Result m_inc_faces; typedef stapl::result_of::localize_object< typename SweepMethod::result_type::value_type > inc_face_t; make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs) : m_out(out), m_parent_cellset(pcs), m_inc_faces() {} // Called by tasks consuming from other tasks in the sweep. make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, Result const& inc_face) : m_out(out), m_parent_cellset(pcs) { for (typename Result::const_iterator f = inc_face.begin(); f != inc_face.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, Result const& inc_face0, Result const& inc_face1) : m_out(out), m_parent_cellset(pcs) { for (typename Result::const_iterator f = inc_face0.begin(); f != inc_face0.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } for (typename Result::const_iterator f = inc_face1.begin(); f != inc_face1.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, Result const& inc_face0, Result const& inc_face1, Result const& inc_face2) : m_out(out), m_parent_cellset(pcs) { for (typename Result::const_iterator f = inc_face0.begin(); f != inc_face0.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } for (typename Result::const_iterator f = inc_face1.begin(); f != inc_face1.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } for (typename Result::const_iterator f = inc_face2.begin(); f != inc_face2.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } // Constructors for tasks with a single boundary input. make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face) : m_out(out), m_parent_cellset(pcs) { m_inc_faces.reserve(1); if ((*inc_face).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face); } make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face0, Result const& inc_face1) : m_out(out), m_parent_cellset(pcs) { if ((*inc_face0).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face0); for (typename Result::const_iterator f = inc_face1.begin(); f != inc_face1.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face0, Result const& inc_face1, Result const& inc_face2) : m_out(out), m_parent_cellset(pcs) { if ((*inc_face0).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face0); for (typename Result::const_iterator f = inc_face1.begin(); f != inc_face1.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } for (typename Result::const_iterator f = inc_face2.begin(); f != inc_face2.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } // Constructors for tasks with two boundary inputs. make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face0, inc_face_t const& inc_face1) : m_out(out), m_parent_cellset(pcs) { m_inc_faces.reserve(2); if ((*inc_face0).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face0); if ((*inc_face1).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face1); } make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face0, inc_face_t const& inc_face1, Result const& inc_face2) : m_out(out), m_parent_cellset(pcs) { if ((*inc_face0).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face0); if ((*inc_face1).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face1); for (typename Result::const_iterator f = inc_face2.begin(); f != inc_face2.end(); ++f) { if ((*f).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*f); } } // Constructor for task with all three faces on boundary. make_sweep_paragraph(std::stringstream& out, parent_cellset_info const& pcs, inc_face_t const& inc_face0, inc_face_t const& inc_face1, inc_face_t const& inc_face2) : m_out(out), m_parent_cellset(pcs) { m_inc_faces.reserve(3); if ((*inc_face0).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face0); if ((*inc_face1).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face1); if ((*inc_face2).id() == m_parent_cellset.parent_id) m_inc_faces.push_back(*inc_face2); } Result promote_return(std::vector<cell_face_value> const& cell_result) { // When cellset is multi-cell this becomes scan to extract faces for // x/y/z succ in m_parent_cellset. Result cs_result; cs_result.reserve(cell_result.size()); for (std::vector<cell_face_value>::const_iterator f = cell_result.begin(); f != cell_result.end(); ++f) cs_result.push_back(cellset_face_value<cell_face_value>(*f)); return cs_result; } template <typename CellsetView> Result operator()(normal const& sweep_direction, std::vector<normal> const& directions, unsigned int octant, CellsetView& cellset_view) { // m_out << "nested CELL paragraph\n"; // printf("%s",m_out.str().c_str()); // Sweep the cell. switch (m_inc_faces.size()) { case 0: return promote_return( cell_wf(sweep_direction, directions, octant) (*cellset_view.begin())); break; case 1: return promote_return( cell_wf(sweep_direction, directions, octant) (*cellset_view.begin(), m_inc_faces[0].value()[0])); break; case 2: return promote_return( cell_wf(sweep_direction, directions, octant) (*cellset_view.begin(), m_inc_faces[0].value()[0], m_inc_faces[1].value()[0])); break; case 3: return promote_return( cell_wf(sweep_direction, directions, octant) (*cellset_view.begin(), m_inc_faces[0].value()[0], m_inc_faces[1].value()[0], m_inc_faces[2].value()[0])); break; default: printf("Too many incoming faces in make_paragraph<1>::operator()\n"); return Result(); // kill compiler warning. } } }; ////////////////////////////////////////////////////////////////////// /// @brief Invokes the sweeps of the spatial domain for each octant. ////////////////////////////////////////////////////////////////////// template <int N, typename CellsetView> void sweep(CellsetView& cs_view, std::vector<normal> const& directions) { // Let's start from the inside and work our way out. // The first loop to compose is over the set of directions we sweep. typedef cellset_wf<N, typename cellset_face_type<N>::type> cellset_wf_type; typedef typename sweep_factory<cellset_wf_type>::result_type result_type; typedef stapl::proxy<result_type, stapl::edge_accessor<stapl::detail::result_view<result_type> > > sweep_result_ref_type; typedef stapl::paragraph<stapl::default_scheduler, sweep_factory<cellset_wf_type>, CellsetView> sweep_tg_type; std::vector<std::pair<sweep_result_ref_type*, sweep_tg_type *> > sweep_tgs; sweep_tgs.reserve(8); for (unsigned int octant = 0; octant != 8; ++octant) { // Construct PARAGRAPH for the sweep of this octant. parent_cellset_info sweep_info(0); sweep_info.z_succ = std::make_pair((unsigned int)1, normal(0,0,1)); sweep_info.y_succ = std::make_pair((unsigned int)2, normal(0,1,0)); sweep_info.z_succ = std::make_pair((unsigned int)4, normal(1,0,0)); sweep_tgs.push_back(std::make_pair( (sweep_result_ref_type*)0, new sweep_tg_type( sweep_factory<cellset_wf_type>( cellset_wf_type(directions[octant*10], directions, octant), directions[octant*10], sweep_info, result_type()), cs_view))); } // The loop is split because prefix scan in graph view coarsening causes the // executor to hang. typename std::vector< std::pair<sweep_result_ref_type*, sweep_tg_type *> >::iterator sweep_it = sweep_tgs.begin(); for (; sweep_it != sweep_tgs.end(); ++sweep_it) { // Start sweep using the non-blocking function operator to allow // sweeps to proceed concurrently. sweep_it->first = new sweep_result_ref_type(sweep_it->second->operator()(0)); } // causes all sweep PARAGRAPHS to be processed. stapl::get_executor()(stapl::execute_all); // NOTE - paragraph executor does this itself when not in persistent mode. // // sweep_it = sweep_tgs.begin(); // for (; sweep_it != sweep_tgs.end(); ++sweep_it) // delete sweep_it->second; } stapl::exit_code stapl_main(int argc, char* argv[]) { problem_input input; if (argc == 8) { input = problem_input(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atoi(argv[6]), atoi(argv[7])); } else { fprintf(stderr,"./sweeps nx ny nz agg level px py (4 4 4 2 1 2 2)\n"); return EXIT_FAILURE; } // Build some random directions, 10 per octant. create_directions dir_creator(80); std::vector<normal> directions = stapl::do_once(dir_creator); // Build Grid and Grid View grid_type grid; create_grid(grid, input); grid_view_type grid_view(grid); // Output of the benchmark is buffered in a stream. std::stringstream out; unsigned int last_cell = input.nx() * input.ny() * input.nz() - 1; out << "cell 0 and " << last_cell << " value before sweep: (" << grid_view[0].property().value() << ", " << grid_view[last_cell].property().value() << ")\n"; // Build Cellset View. typedef stapl::hierarchical_view_type< grid_view_type, regular_grid_partitioner, normal >::type l0_cs_view_type; typedef stapl::hierarchical_view_type< l0_cs_view_type, regular_grid_partitioner, normal >::type l1_cs_view_type; typedef stapl::hierarchical_view_type< l1_cs_view_type, regular_grid_partitioner, normal >::type l2_cs_view_type; typedef stapl::hierarchical_view_type< l2_cs_view_type, regular_grid_partitioner, normal >::type l3_cs_view_type; typedef stapl::hierarchical_view_type< l3_cs_view_type, regular_grid_partitioner, normal >::type l4_cs_view_type; typedef stapl::hierarchical_view_type< l4_cs_view_type, regular_grid_partitioner, normal >::type l5_cs_view_type; // Cellsets in this view each contain a single cell. l0_cs_view_type l0_cs_view = stapl::create_level(grid_view, regular_grid_partitioner(input), cellset_edge_functor(input)); // Cellsets in these views each contain multiple lower level cellsets. l1_cs_view_type* l1_cs_view(0); l2_cs_view_type* l2_cs_view(0); l3_cs_view_type* l3_cs_view(0); l4_cs_view_type* l4_cs_view(0); l5_cs_view_type* l5_cs_view(0); // Construct views, sweep, and cleanup for the desired level of nesting. switch (input.level()) { case 1: l1_cs_view = new l1_cs_view_type( stapl::create_level(l0_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); sweep<1>(*l1_cs_view, directions); delete l1_cs_view; break; case 2: l1_cs_view = new l1_cs_view_type( stapl::create_level(l0_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); l2_cs_view = new l2_cs_view_type( stapl::create_level(*l1_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); sweep<2>(*l2_cs_view, directions); delete l1_cs_view; delete l2_cs_view; break; case 3: l1_cs_view = new l1_cs_view_type( stapl::create_level(l0_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); l2_cs_view = new l2_cs_view_type( stapl::create_level(*l1_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); l3_cs_view = new l3_cs_view_type( stapl::create_level(*l2_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); sweep<3>(*l3_cs_view, directions); delete l1_cs_view; delete l2_cs_view; delete l3_cs_view; break; case 4: l1_cs_view = new l1_cs_view_type( stapl::create_level(l0_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); l2_cs_view = new l2_cs_view_type( stapl::create_level(*l1_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); l3_cs_view = new l3_cs_view_type( stapl::create_level(*l2_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); l4_cs_view = new l4_cs_view_type( stapl::create_level(*l3_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); sweep<4>(*l4_cs_view, directions); delete l1_cs_view; delete l2_cs_view; delete l3_cs_view; delete l4_cs_view; break; case 5: l1_cs_view = new l1_cs_view_type( stapl::create_level(l0_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); l2_cs_view = new l2_cs_view_type( stapl::create_level(*l1_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); l3_cs_view = new l3_cs_view_type( stapl::create_level(*l2_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); l4_cs_view = new l4_cs_view_type( stapl::create_level(*l3_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); l5_cs_view = new l5_cs_view_type( stapl::create_level(*l4_cs_view, regular_grid_partitioner(input), cellset_edge_functor(input))); sweep<5>(*l5_cs_view, directions); delete l1_cs_view; delete l2_cs_view; delete l3_cs_view; delete l4_cs_view; delete l5_cs_view; } out << "cell 0 and " << last_cell << " value after sweep: (" << grid_view[0].property().value() << ", " << grid_view[last_cell].property().value() << ")\n"; if (stapl::get_location_id() == 0) printf("%s",out.str().c_str()); return EXIT_SUCCESS; }
34.484621
80
0.578278
[ "mesh", "vector", "3d" ]
6c8e8716f4a5e45cc0ff96c5eb76af6741b51e76
2,809
cpp
C++
CGALWrapper/Geometry/Box2_EEK.cpp
unitycoder/CGALDotNet
90682724a55aec2818847500047d4785aa7e1d67
[ "MIT" ]
null
null
null
CGALWrapper/Geometry/Box2_EEK.cpp
unitycoder/CGALDotNet
90682724a55aec2818847500047d4785aa7e1d67
[ "MIT" ]
null
null
null
CGALWrapper/Geometry/Box2_EEK.cpp
unitycoder/CGALDotNet
90682724a55aec2818847500047d4785aa7e1d67
[ "MIT" ]
null
null
null
#include "Box2_EEK.h" #include <CGAL/Iso_rectangle_2.h> #include <CGAL/Aff_transformation_2.h> #include <CGAL/Cartesian_converter.h> typedef CGAL::Iso_rectangle_2<EEK> Box2; typedef CGAL::Aff_transformation_2<EEK> Transformation2; void* Box2_EEK_Create(const Point2d& min, const Point2d& max) { auto _min = min.ToCGAL<EEK>(); auto _max = max.ToCGAL<EEK>(); return new Box2(_min, _max); } void Box2_EEK_Release(void* ptr) { auto obj = static_cast<Box2*>(ptr); if (obj != nullptr) { delete obj; obj = nullptr; } } Box2* CastToBox2(void* ptr) { return static_cast<Box2*>(ptr); } Box2* NewBox2() { return new Box2(); } Point2d Box2_EEK_GetMin(void* ptr) { auto rec = CastToBox2(ptr); return Point2d::FromCGAL<EEK>(rec->min()); } void Box2_EEK_SetMin(void* ptr, const Point2d& point) { auto rec = CastToBox2(ptr); (*rec) = Box2(point.ToCGAL<EEK>(), rec->max()); } Point2d Box2_EEK_GetMax(void* ptr) { auto rec = CastToBox2(ptr); return Point2d::FromCGAL<EEK>(rec->max()); } void Box2_EEK_SetMax(void* ptr, const Point2d& point) { auto rec = CastToBox2(ptr); (*rec) = Box2(rec->min(), point.ToCGAL<EEK>()); } double Box2_EEK_Area(void* ptr) { auto rec = CastToBox2(ptr); return CGAL::to_double(rec->area()); } CGAL::Bounded_side Box2_EEK_BoundedSide(void* ptr, const Point2d& point) { auto rec = CastToBox2(ptr); auto p = point.ToCGAL<EEK>(); return rec->bounded_side(p); } BOOL Box2_EEK_ContainsPoint(void* ptr, const Point2d& point, BOOL inculdeBoundary) { auto rec = CastToBox2(ptr); auto side = rec->bounded_side(point.ToCGAL<EEK>()); if (inculdeBoundary && side == CGAL::Bounded_side::ON_BOUNDARY) return true; return side == CGAL::Bounded_side::ON_BOUNDED_SIDE; } BOOL Box2_EEK_IsDegenerate(void* ptr) { auto rec = CastToBox2(ptr); return rec->is_degenerate(); } void Box2_EEK_Transform(void* ptr, const Point2d& translation, double rotation, double scale) { auto rec = CastToBox2(ptr); Transformation2 T(CGAL::TRANSLATION, translation.ToVector<EEK>()); Transformation2 R(CGAL::ROTATION, sin(rotation), cos(rotation)); Transformation2 S(CGAL::SCALING, scale); (*rec) = rec->transform(T * R * S); } void* Box2_EEK_Copy(void* ptr) { auto rec = CastToBox2(ptr); auto nrec = NewBox2(); (*nrec) = *rec; return nrec; } template<class K2> static void* Convert(Box2* rec) { CGAL::Cartesian_converter<EEK, K2> convert; auto min = convert(rec->min()); auto max = convert(rec->max()); return new CGAL::Iso_rectangle_2<K2>(min, max); } void* Box2_EEK_Convert(void* ptr, CGAL_KERNEL k) { auto rec = CastToBox2(ptr); switch (k) { case CGAL_KERNEL::EXACT_PREDICATES_INEXACT_CONSTRUCTION: return Convert<EIK>(rec); case CGAL_KERNEL::EXACT_PREDICATES_EXACT_CONSTRUCTION: return Convert<EEK>(rec); default: return Convert<EEK>(rec); } }
20.064286
93
0.707725
[ "transform" ]
6c97639bc039f8515f05b6e2f23cecbf238e64d6
5,582
cpp
C++
rapp_hazard_detection/src/door_check.cpp
DEVX1/NAOrapp-Pythonlib
d07d7fe304556cad24e7e138df4e41376eacb6a7
[ "Apache-2.0" ]
null
null
null
rapp_hazard_detection/src/door_check.cpp
DEVX1/NAOrapp-Pythonlib
d07d7fe304556cad24e7e138df4e41376eacb6a7
[ "Apache-2.0" ]
null
null
null
rapp_hazard_detection/src/door_check.cpp
DEVX1/NAOrapp-Pythonlib
d07d7fe304556cad24e7e138df4e41376eacb6a7
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** Copyright 2015 RAPP 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. Authors: Maciej Stefańczyk contact: m.stefanczyk@elka.pw.edu.pl ******************************************************************************/ #include <hazard_detection/door_check.hpp> #include <hazard_detection/Line.hpp> int DoorCheck::process( const std::string & fname, DoorCheckParams params ) { cv::Mat img = cv::imread(fname, CV_LOAD_IMAGE_GRAYSCALE); // check, whether image is properly loaded if (img.empty()) return -1; // adaptive thresholding - results similar to edge detection cv::Mat img_thr; cv::adaptiveThreshold(img, img_thr, 255, params.thr_method, cv::THRESH_BINARY_INV, params.thr_block, params.thr_c); int prop_width = img.size().width; int prop_height = img.size().height; // detect line segments std::vector<cv::Vec4i> tmp_lines; cv::HoughLinesP( img_thr, tmp_lines, 1, CV_PI/180, params.hough_thr, params.hough_len, params.hough_gap); std::vector<Line> lines; for( size_t i = 0; i < tmp_lines.size(); i++ ) { lines.push_back(Line(cv::Point(tmp_lines[i][0], tmp_lines[i][1]), cv::Point(tmp_lines[i][2], tmp_lines[i][3]))); } // estimate door angle Line line; std::vector<Line> lines_v, lines_h; for (int i = 0; i < lines.size(); ++i) { line = lines[i]; line.draw(img, cv::Scalar(255,255,255)); if (abs(line.getAngle()) < M_PI/6) { lines_h.push_back(line); line.draw(img, cv::Scalar(128)); } else if (abs(line.getAngle()) > 2*M_PI/6) { lines_v.push_back(line); } else { // skip line } } std::vector<cv::Point2f> points_v, points_h; /*for (int i = 0; i < 20; ++i) { std::random_shuffle(lines_v.begin(), lines_v.end()); }*/ // center line - vertical door frame Line * cl = NULL; // score of center line float cl_score = 0; for (int i = 0; i < lines_v.size(); ++i) { Line * tmp = &lines_v[i]; // angle score - 1 for perfectly vertical line float angle_score = fabs(tmp->getAngle()) / (M_PI/2); // position score - 1 for centered line float mean_x = (tmp->getP1().x + tmp->getP2().x) / 2; float cx = 0.5 * prop_width; float position_score = 1.0 - fabs(cx - mean_x) / cx; // length score - 1 for line at least half of image height float length_score = 2 * tmp->length() / prop_height; if (length_score > 1) length_score = 1; float tmp_score = angle_score * position_score * length_score; if (tmp_score > cl_score) { cl = tmp; cl_score = tmp_score; } } if (cl) cl->draw(img, cv::Scalar(0, 0, 0)); // left line - left floor/wall crossing Line * ll = NULL; // score of left line float ll_score = 0; for (int i = 0; i < lines_h.size(); ++i) { Line * tmp = &lines_h[i]; // angle score - 1 for perfectly horizontal line float angle_score = (M_PI/2 - fabs(tmp->getAngle())) / (M_PI/2); // position score - 1 for line centered on the left part float mean_x = (tmp->getP1().x + tmp->getP2().x) / 2; float cx = 0.25 * prop_width; float position_score = 1.0 - fabs(cx - mean_x) / cx; // ignore lines laying on the right side if (mean_x > 0.5 * prop_width) position_score = 0; // length score - 1 for line at least half of image width float length_score = 2 * tmp->length() / prop_width; if (length_score > 1) length_score = 1; float tmp_score = angle_score * position_score * length_score; if (tmp_score > ll_score) { ll = tmp; ll_score = tmp_score; } } if (ll) ll->draw(img, cv::Scalar(0)); // right line - right floor/wall crossing Line * rl = NULL; // score of right line float rl_score = 0; for (int i = 0; i < lines_h.size(); ++i) { Line * tmp = &lines_h[i]; // angle score - 1 for perfectly horizontal line float angle_score = (M_PI/2 - fabs(tmp->getAngle())) / (M_PI/2); // position score - 1 for line centered on the left part float mean_x = (tmp->getP1().x + tmp->getP2().x) / 2; float cx = 0.75 * prop_width; float position_score = 1.0 - fabs(cx - mean_x) / cx; // ignore lines laying on the left side if (mean_x < 0.5 * prop_width) position_score = 0; // length score - 1 for line at least half of image width float length_score = 2 * tmp->length() / prop_width; if (length_score > 1) length_score = 1; float tmp_score = angle_score * position_score * length_score; if (tmp_score > rl_score) { rl = tmp; rl_score = tmp_score; } } if (rl) rl->draw(img, cv::Scalar(0)); float angle = 0; if (ll && rl) { angle = fabs(ll->getAngle() - rl->getAngle()) * 180 / 3.1415; } else { angle = 90; } if (params.debug) cv::imwrite("/tmp/door_out.png", img); return angle; }
30.172973
118
0.59029
[ "vector" ]
6c9e28c43000bdcfe45f95f169c542fffcf9a7f7
634
cc
C++
examples/gtk/gtk.cc
dmikushin/libjingle
b9754327f3e4361cea9d27683a3b5817afb99819
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
examples/gtk/gtk.cc
dmikushin/libjingle
b9754327f3e4361cea9d27683a3b5817afb99819
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
examples/gtk/gtk.cc
dmikushin/libjingle
b9754327f3e4361cea9d27683a3b5817afb99819
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
#include "media/devices/gtkvideorenderer.h" #include <vector> int main(int argc, char* argv[]) { cricket::GtkVideoRenderer renderer; const int width = 300; const int height = 200; std::vector<uint8> pixels(width * height * 4); while (1) { for (int j = 0; j < height; j++) for (int i = 0; i < width; i++) { pixels[4 * (j * width + i)] = rand() % 255; pixels[4 * (j * width + i) + 1] = rand() % 255; pixels[4 * (j * width + i) + 2] = rand() % 255; pixels[4 * (j * width + i) + 3] = rand() % 255; } renderer.RenderFrame(width, height, reinterpret_cast<uint8*>(&pixels[0])); } return 0; }
21.133333
76
0.561514
[ "vector" ]
6c9e3ae1e9c8b7e5d14b64f49a6677862cc770b2
615
cpp
C++
Easy/136_singleNumber/136_singleNumber/main.cpp
yangbingjie/Leetcode
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
[ "MIT" ]
1
2020-10-08T06:15:37.000Z
2020-10-08T06:15:37.000Z
Easy/136_singleNumber/136_singleNumber/main.cpp
yangbingjie/Leetcode
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
[ "MIT" ]
null
null
null
Easy/136_singleNumber/136_singleNumber/main.cpp
yangbingjie/Leetcode
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
[ "MIT" ]
null
null
null
// // main.cpp // 136_singleNumber // // Created by Bella Yang on 2019/9/23. // Copyright © 2019 Bella Yang. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { public: int singleNumber(vector<int>& nums) { int result = 0; for(int i = 0; i < nums.size(); ++i){ result ^= nums[i]; } return result; } }; int main(int argc, const char * argv[]) { Solution s; const int LEN = 5; int array[LEN] = {4, 4, 3, 1}; vector<int> nums(array, array + LEN); cout << s.singleNumber(nums); return 0; }
20.5
53
0.56748
[ "vector" ]
6ca0116c322bd0380ac331163817471906d1292d
14,473
hpp
C++
Includes/Core/Matrix/MatrixCSR.hpp
ADMTec/CubbyFlow
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
[ "MIT" ]
216
2017-01-25T04:34:30.000Z
2021-07-15T12:36:06.000Z
Includes/Core/Matrix/MatrixCSR.hpp
ADMTec/CubbyFlow
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
[ "MIT" ]
323
2017-01-26T13:53:13.000Z
2021-07-14T16:03:38.000Z
Includes/Core/Matrix/MatrixCSR.hpp
ADMTec/CubbyFlow
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
[ "MIT" ]
33
2017-01-25T05:05:49.000Z
2021-06-17T17:30:56.000Z
// This code is based on Jet framework. // Copyright (c) 2018 Doyub Kim // CubbyFlow is voxel-based fluid simulation engine for computer games. // Copyright (c) 2020 CubbyFlow Team // Core Part: Chris Ohk, Junwoo Hwang, Jihong Sin, Seungwoo Yoo // AI Part: Dongheon Cho, Minseo Kim // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef CUBBYFLOW_MATRIX_CSR_HPP #define CUBBYFLOW_MATRIX_CSR_HPP #include <Core/Matrix/Matrix.hpp> namespace CubbyFlow { template <typename T> class MatrixCSR; //! //! \brief Matrix expression for CSR matrix-matrix multiplication. //! //! This matrix expression represents a CSR matrix-matrix operation that //! takes one CSR input matrix expression and one (probably dense) matrix //! expression. //! //! \tparam T Element value type. //! \tparam ME Matrix expression. //! template <typename T, typename ME> class MatrixCSRMatrixMul : public MatrixExpression<T, MATRIX_SIZE_DYNAMIC, MATRIX_SIZE_DYNAMIC, MatrixCSRMatrixMul<T, ME>> { public: MatrixCSRMatrixMul(const MatrixCSR<T>& m1, const ME& m2); //! Number of rows. [[nodiscard]] size_t GetRows() const; //! Number of columns. [[nodiscard]] size_t GetCols() const; //! Returns matrix element at (i, j). T operator()(size_t i, size_t j) const; private: const MatrixCSR<T>& m_m1; const ME& m_m2; const T* const m_nnz; const size_t* const m_rp; const size_t* const m_ci; }; //! //! \brief Compressed Sparse Row (CSR) matrix class. //! //! This class defines Compressed Sparse Row (CSR) matrix using arrays of //! non-zero elements, row pointers, and column indices. //! //! \see http://www.netlib.org/utk/people/JackDongarra/etemplates/node373.html //! //! \tparam T Type of the element. //! template <typename T> class MatrixCSR final : public MatrixExpression<T, MATRIX_SIZE_DYNAMIC, MATRIX_SIZE_DYNAMIC, MatrixCSR<T>> { public: static_assert( std::is_floating_point<T>::value, "MatrixCSR only can be instantiated with floating point types"); struct Element { size_t i; size_t j; T value; Element(); Element(size_t i, size_t j, const T& value); }; using NonZeroContainerType = std::vector<T>; using NonZeroIterator = typename NonZeroContainerType::iterator; using ConstNonZeroIterator = typename NonZeroContainerType::const_iterator; using IndexContainerType = std::vector<size_t>; using IndexIterator = IndexContainerType::iterator; using ConstIndexIterator = IndexContainerType::const_iterator; //! Constructs an empty matrix. MatrixCSR(); //! //! \brief Compresses given initializer list \p lst into a sparse matrix. //! //! This constructor will build a matrix with given initializer list \p lst //! such as //! //! \code{.cpp} //! MatrixCSR<float> mat = { //! {1.f, 0.f, 0.f, 3.f}, //! {0.f, 3.f, 5.f, 1.f}, //! {4.f, 0.f, 1.f, 5.f} //! }; //! \endcode //! //! Note the initializer has 4x3 structure which will create 4x3 matrix. //! During the process, zero elements (less than \p epsilon) will not be //! stored. //! //! \param lst Initializer list that should be copy to the new matrix. //! MatrixCSR(const std::initializer_list<std::initializer_list<T>>& lst, T epsilon = std::numeric_limits<T>::epsilon()); //! //! \brief Compresses input (dense) matrix expression into a sparse matrix. //! //! This function sets this sparse matrix with dense input matrix. //! During the process, zero elements (less than \p epsilon) will not be //! stored. //! template <size_t R, size_t C, typename E> MatrixCSR(const MatrixExpression<T, R, C, E>& other, T epsilon = std::numeric_limits<T>::epsilon()); //! Default destructor. ~MatrixCSR() = default; //! Copy constructor. MatrixCSR(const MatrixCSR& other); //! Move constructor. MatrixCSR(MatrixCSR&& other) noexcept; //! Copies to this matrix. MatrixCSR& operator=(const MatrixCSR& other); //! Moves to this matrix. MatrixCSR& operator=(MatrixCSR&& other) noexcept; //! Clears the matrix and make it zero-dimensional. void Clear(); //! Sets whole matrix with input scalar. void Set(const T& s); //! Copy from given sparse matrix. void Set(const MatrixCSR& other); //! Reserves memory space of this matrix. void Reserve(size_t rows, size_t cols, size_t numNonZeros); //! //! \brief Compresses given initializer list \p lst into a sparse matrix. //! //! This function will fill the matrix with given initializer list \p lst //! such as //! //! \code{.cpp} //! MatrixCSR<float> mat; //! mat.compress({ //! {1.f, 0.f, 0.f, 3.f}, //! {0.f, 3.f, 5.f, 1.f}, //! {4.f, 0.f, 1.f, 5.f} //! }); //! \endcode //! //! Note the initializer has 4x3 structure which will resize to 4x3 matrix. //! During the process, zero elements (less than \p epsilon) will not be //! stored. //! //! \param lst Initializer list that should be copy to the new matrix. //! void Compress(const std::initializer_list<std::initializer_list<T>>& lst, T epsilon = std::numeric_limits<T>::epsilon()); //! //! \brief Compresses input (dense) matrix expression into a sparse matrix. //! //! This function sets this sparse matrix with dense input matrix. //! During the process, zero elements (less than \p epsilon) will not be //! stored. //! template <size_t R, size_t C, typename E> void Compress(const MatrixExpression<T, R, C, E>& other, T epsilon = std::numeric_limits<T>::epsilon()); //! Adds non-zero element to (i, j). void AddElement(size_t i, size_t j, const T& value); //! Adds non-zero element. void AddElement(const Element& element); //! //! Adds a row to the sparse matrix. //! //! \param nonZeros - Array of non-zero elements for the row. //! \param columnIndices - Array of column indices for the row. //! void AddRow(const NonZeroContainerType& nonZeros, const IndexContainerType& columnIndices); //! Sets non-zero element to (i, j). void SetElement(size_t i, size_t j, const T& value); //! Sets non-zero element. void SetElement(const Element& element); [[nodiscard]] bool IsEqual(const MatrixCSR& other) const; //! Returns true if this matrix is similar to the input matrix within the //! given tolerance. [[nodiscard]] bool IsSimilar( const MatrixCSR& other, double tol = std::numeric_limits<double>::epsilon()) const; //! Returns true if this matrix is a square matrix. [[nodiscard]] bool IsSquare() const; //! Returns the size of this matrix. [[nodiscard]] Vector2UZ Size() const; //! Returns number of rows of this matrix. [[nodiscard]] size_t GetRows() const; //! Returns number of columns of this matrix. [[nodiscard]] size_t GetCols() const; //! Returns the number of non-zero elements. [[nodiscard]] size_t NumberOfNonZeros() const; //! Returns i-th non-zero element. [[nodiscard]] const T& NonZero(size_t i) const; //! Returns i-th non-zero element. [[nodiscard]] T& NonZero(size_t i); //! Returns i-th row pointer. [[nodiscard]] const size_t& RowPointer(size_t i) const; //! Returns i-th column index. [[nodiscard]] const size_t& ColumnIndex(size_t i) const; //! Returns pointer of the non-zero elements data. [[nodiscard]] T* NonZeroData(); //! Returns constant pointer of the non-zero elements data. [[nodiscard]] const T* NonZeroData() const; //! Returns constant pointer of the row pointers data. [[nodiscard]] const size_t* RowPointersData() const; //! Returns constant pointer of the column indices data. [[nodiscard]] const size_t* ColumnIndicesData() const; //! Returns the begin iterator of the non-zero elements. [[nodiscard]] NonZeroIterator NonZeroBegin(); //! Returns the begin const iterator of the non-zero elements. [[nodiscard]] ConstNonZeroIterator NonZeroBegin() const; //! Returns the end iterator of the non-zero elements. [[nodiscard]] NonZeroIterator NonZeroEnd(); //! Returns the end const iterator of the non-zero elements. [[nodiscard]] ConstNonZeroIterator NonZeroEnd() const; //! Returns the begin iterator of the row pointers. [[nodiscard]] IndexIterator RowPointersBegin(); //! Returns the begin const iterator of the row pointers. [[nodiscard]] ConstIndexIterator RowPointersBegin() const; //! Returns the end iterator of the row pointers. [[nodiscard]] IndexIterator RowPointersEnd(); //! Returns the end const iterator of the row pointers. [[nodiscard]] ConstIndexIterator RowPointersEnd() const; //! Returns the begin iterator of the column indices. [[nodiscard]] IndexIterator ColumnIndicesBegin(); //! Returns the begin const iterator of the column indices. [[nodiscard]] ConstIndexIterator ColumnIndicesBegin() const; //! Returns the end iterator of the column indices. [[nodiscard]] IndexIterator ColumnIndicesEnd(); //! Returns the end const iterator of the column indices. [[nodiscard]] ConstIndexIterator ColumnIndicesEnd() const; //! Returns this matrix + input scalar. [[nodiscard]] MatrixCSR Add(const T& s) const; //! Returns this matrix + input matrix (element-wise). [[nodiscard]] MatrixCSR Add(const MatrixCSR& m) const; //! Returns this matrix - input scalar. [[nodiscard]] MatrixCSR Sub(const T& s) const; //! Returns this matrix - input matrix (element-wise). [[nodiscard]] MatrixCSR Sub(const MatrixCSR& m) const; //! Returns this matrix * input scalar. [[nodiscard]] MatrixCSR Mul(const T& s) const; //! Returns this matrix * input matrix. template <size_t R, size_t C, typename ME> [[nodiscard]] MatrixCSRMatrixMul<T, ME> Mul( const MatrixExpression<T, R, C, ME>& m) const; //! Returns this matrix / input scalar. [[nodiscard]] MatrixCSR Div(const T& s) const; //! Returns input scalar + this matrix. [[nodiscard]] MatrixCSR RAdd(const T& s) const; //! Returns input matrix + this matrix (element-wise). [[nodiscard]] MatrixCSR RAdd(const MatrixCSR& m) const; //! Returns input scalar - this matrix. [[nodiscard]] MatrixCSR RSub(const T& s) const; //! Returns input matrix - this matrix (element-wise). [[nodiscard]] MatrixCSR RSub(const MatrixCSR& m) const; //! Returns input scalar * this matrix. [[nodiscard]] MatrixCSR RMul(const T& s) const; //! Returns input matrix / this scalar. [[nodiscard]] MatrixCSR RDiv(const T& s) const; //! Adds input scalar to this matrix. void IAdd(const T& s); //! Adds input matrix to this matrix (element-wise). void IAdd(const MatrixCSR& m); //! Subtracts input scalar from this matrix. void ISub(const T& s); //! Subtracts input matrix from this matrix (element-wise). void ISub(const MatrixCSR& m); //! Multiplies input scalar to this matrix. void IMul(const T& s); //! Multiplies input matrix to this matrix. template <size_t R, size_t C, typename ME> void IMul(const MatrixExpression<T, R, C, ME>& m); //! Divides this matrix with input scalar. void IDiv(const T& s); //! Returns sum of all elements. [[nodiscard]] T Sum() const; //! Returns average of all elements. [[nodiscard]] T Avg() const; //! Returns minimum among all elements. [[nodiscard]] T Min() const; //! Returns maximum among all elements. [[nodiscard]] T Max() const; //! Returns absolute minimum among all elements. [[nodiscard]] T AbsMin() const; //! Returns absolute maximum among all elements. [[nodiscard]] T AbsMax() const; //! Returns sum of all diagonal elements. //! \warning Should be a square matrix. [[nodiscard]] T Trace() const; //! Type-casts to different value-typed matrix. template <typename U> MatrixCSR<U> CastTo() const; //! //! \brief Compresses input (dense) matrix expression into a sparse matrix. //! //! This function sets this sparse matrix with dense input matrix. //! During the process, zero elements (less than \p epsilon) will not be //! stored. //! template <size_t R, size_t C, typename ME> MatrixCSR& operator=(const MatrixExpression<T, R, C, ME>& m); //! Addition assignment with input scalar. MatrixCSR& operator+=(const T& s); //! Addition assignment with input matrix (element-wise). MatrixCSR& operator+=(const MatrixCSR& m); //! Subtraction assignment with input scalar. MatrixCSR& operator-=(const T& s); //! Subtraction assignment with input matrix (element-wise). MatrixCSR& operator-=(const MatrixCSR& m); //! Multiplication assignment with input scalar. MatrixCSR& operator*=(const T& s); //! Multiplication assignment with input matrix. template <size_t R, size_t C, typename ME> MatrixCSR& operator*=(const MatrixExpression<T, R, C, ME>& m); //! Division assignment with input scalar. MatrixCSR& operator/=(const T& s); //! Returns (i,j) element. T operator()(size_t i, size_t j) const; //! Returns true if is equal to m. bool operator==(const MatrixCSR& m) const; //! Returns true if is not equal to m. bool operator!=(const MatrixCSR& m) const; //! Makes a m x m matrix with all diagonal elements to 1, and other elements //! to 0. static MatrixCSR<T> MakeIdentity(size_t m); private: [[nodiscard]] size_t HasElement(size_t i, size_t j) const; template <typename Op> MatrixCSR BinaryOp(const MatrixCSR& m, Op op) const; Vector2UZ m_size; NonZeroContainerType m_nonZeros; IndexContainerType m_rowPointers; IndexContainerType m_columnIndices; }; //! Float-type CSR matrix. typedef MatrixCSR<float> MatrixCSRF; //! Double-type CSR matrix. typedef MatrixCSR<double> MatrixCSRD; } // namespace CubbyFlow #include <Core/Matrix/MatrixCSR-Impl.hpp> #endif
31.949227
80
0.655773
[ "vector" ]
6ca4ab156d47dd087bf089116ad9289d4c8d127d
11,544
cc
C++
src/base/WCSimFitterTrackParMap.cc
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
src/base/WCSimFitterTrackParMap.cc
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
src/base/WCSimFitterTrackParMap.cc
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
/* * WCSimFitterTrackParMap.cc * * Created on: 27 May 2015 * Author: andy */ #include "WCSimFitterTrackParMap.hh" #include "WCSimFitterInterface.hh" #include "WCSimFitterConfig.hh" #include "WCSimTrackParameterEnums.hh" #include <cassert> #ifndef REFLEX_DICTIONARY ClassImp(WCSimFitterTrackParMap) #endif WCSimFitterTrackParMap::WCSimFitterTrackParMap(WCSimFitterConfig *config) { fFitterConfig = config; // TODO Auto-generated constructor stub } WCSimFitterTrackParMap::~WCSimFitterTrackParMap() { // TODO Auto-generated destructor stub } void WCSimFitterTrackParMap::Set() { fTrackAndTypeIndexMap.clear(); unsigned int nTracks = fFitterConfig->GetNumTracks(); std::cout << "Number of tracks set is " << nTracks << std::endl; unsigned int arrayCounter = 0; // How many unique track parameters there are for (unsigned int iTrack = 0; iTrack < nTracks; ++iTrack) { std::vector<FitterParameterType::Type> allTypes = FitterParameterType::GetAllAllowedTypes( fFitterConfig->GetTrackType(iTrack)); for (unsigned int iParam = 0; iParam < allTypes.size(); ++iParam) { // Is it joined? TrackAndType trackPar(iTrack, allTypes.at(iParam)); unsigned int isJoinedWith = fFitterConfig->GetTrackIsJoinedWith(iTrack, FitterParameterType::AsString(trackPar.second).c_str()); if (isJoinedWith == iTrack) // Itself, i.e. not joined with any other track { // Then set it to the value from the first track //std::cout << "Array counter = " << arrayCounter << " " << "Independent params = " << fFitterConfig->GetNumIndependentParameters() << std::endl; assert(arrayCounter < fFitterConfig->GetNumIndependentParameters()); fTrackAndTypeIndexMap[trackPar] = arrayCounter; arrayCounter++; } else { // Otherwise don't; set it to the next index value instead TrackAndType joinPar(isJoinedWith, allTypes.at(iParam)); fTrackAndTypeIndexMap[trackPar] = fTrackAndTypeIndexMap[joinPar]; } } } SetArrays(); } void WCSimFitterTrackParMap::SetArrays() { //std::cout << "SetArrays" << std::endl; ResizeVectors(); Int_t iParam = 0; unsigned int numTracks = fFitterConfig->GetNumTracks(); for (unsigned int jTrack = 0; jTrack < numTracks; ++jTrack) { fTypes.at(jTrack) = (fFitterConfig->GetTrackType(jTrack)); std::vector<FitterParameterType::Type> paramTypes = FitterParameterType::GetAllAllowedTypes( fTypes.at(jTrack)); for (int i=0; i<paramTypes.size(); i++) { FitterParameterType::Type param = paramTypes[i]; std::string string_name = FitterParameterType::AsString(param); const char *name = string_name.c_str(); if (fFitterConfig->GetIsParameterJoined(jTrack, param)) { continue; } // Only set it if it's a unique parameter else { fCurrentValues[iParam] = fFitterConfig->GetParStart(jTrack, name); fMinValues[iParam] = fFitterConfig->GetParMin(jTrack, name); fMaxValues[iParam] = fFitterConfig->GetParMax(jTrack, name); fSteps[iParam] = fFitterConfig->GetParStep(jTrack, name); fAlwaysFixed[iParam] = fFitterConfig->GetIsFixedParameter(jTrack, name); fCurrentlyFixed[iParam] = fAlwaysFixed[iParam]; TString parName = Form("%s_track%d", name, jTrack); fNames[iParam] = std::string(parName.Data()); fIsEnergy[iParam] = (param == FitterParameterType::kEnergy); iParam++; } } } } void WCSimFitterTrackParMap::ResizeVectors() { //std::cout << "Resize vectors" << std::endl; unsigned int arraySize = fTrackAndTypeIndexMap.size(); fCurrentValues.clear(); fMinValues.clear(); fMaxValues.clear(); fCurrentlyFixed.clear(); fAlwaysFixed.clear(); fIsEnergy.clear(); fSteps.clear(); fNames.clear(); fTypes.clear(); fCurrentValues.resize(arraySize); fMinValues.resize(arraySize); fMaxValues.resize(arraySize); fCurrentlyFixed.resize(arraySize); fAlwaysFixed.resize(arraySize); fIsEnergy.resize(arraySize); fSteps.resize(arraySize); fNames.resize(arraySize); fTypes.resize(fFitterConfig->GetNumTracks()); } void WCSimFitterTrackParMap::FixDirection(int track) { FixOrFreeDirection(1, track); } void WCSimFitterTrackParMap::FreeDirection(int track) { FixOrFreeDirection(0, track); } void WCSimFitterTrackParMap::FixVertex(int track) { FixOrFreeVertex(1, track); } void WCSimFitterTrackParMap::FreeVertex(int track) { FixOrFreeVertex(0, track); } // Fixes the vertex (position, not direction) for a certain track (or all tracks // if no argument given) if fixIt = true, otherwise frees it void WCSimFitterTrackParMap::FixOrFreeDirection(bool fixIt, int track) { int firstTrack = (track != -1) ? track : 0; int lastTrack = (track != -1) ? track : fFitterConfig->GetNumTracks(); for (int iTrack = firstTrack; iTrack < lastTrack; ++iTrack) { TrackAndType myDirTh(iTrack, FitterParameterType::kDirTh); TrackAndType myDirPhi(iTrack, FitterParameterType::kDirPhi); if (!fAlwaysFixed.at(fTrackAndTypeIndexMap[myDirTh])) { fCurrentlyFixed.at(fTrackAndTypeIndexMap[myDirTh]) = fixIt; } if (!fAlwaysFixed.at(fTrackAndTypeIndexMap[myDirPhi])) { fCurrentlyFixed.at(fTrackAndTypeIndexMap[myDirPhi]) = fixIt; } } } // Fixes the vertex (position, not direction) for a certain track (or all tracks // if no argument given) if fixIt = true, otherwise frees it void WCSimFitterTrackParMap::FixOrFreeVertex(bool fixIt, int track) { int firstTrack = (track != -1) ? track : 0; int lastTrack = (track != -1) ? track : fFitterConfig->GetNumTracks(); for (int iTrack = firstTrack; iTrack < lastTrack; ++iTrack) { TrackAndType myVtxX(iTrack, FitterParameterType::kVtxX); TrackAndType myVtxY(iTrack, FitterParameterType::kVtxY); TrackAndType myVtxZ(iTrack, FitterParameterType::kVtxZ); if (!fAlwaysFixed.at(fTrackAndTypeIndexMap[myVtxX])) { fCurrentlyFixed.at(fTrackAndTypeIndexMap[myVtxX]) = fixIt; } if (!fAlwaysFixed.at(fTrackAndTypeIndexMap[myVtxY])) { fCurrentlyFixed.at(fTrackAndTypeIndexMap[myVtxY]) = fixIt; } if (!fAlwaysFixed.at(fTrackAndTypeIndexMap[myVtxZ])) { fCurrentlyFixed.at(fTrackAndTypeIndexMap[myVtxZ]) = fixIt; } } } void WCSimFitterTrackParMap::FixEnergy(int track) { FixOrFreeEnergy(1, track); } void WCSimFitterTrackParMap::FreeEnergy(int track) { FixOrFreeEnergy(0, track); } void WCSimFitterTrackParMap::FixOrFreeEnergy(bool fixIt, int track) { int firstTrack = (track != -1) ? track : 0; int lastTrack = (track != -1) ? track : fFitterConfig->GetNumTracks(); for (int iTrack = firstTrack; iTrack < lastTrack; ++iTrack) { TrackAndType myEnergy(iTrack, FitterParameterType::kEnergy); if (!fAlwaysFixed.at(fTrackAndTypeIndexMap[myEnergy])) { fCurrentlyFixed.at(fTrackAndTypeIndexMap[myEnergy]) = fixIt; } } } void WCSimFitterTrackParMap::FixTime(int track) { FixOrFreeTime(1, track); } void WCSimFitterTrackParMap::FreeTime(int track) { FixOrFreeTime(0, track); } void WCSimFitterTrackParMap::FixOrFreeTime(bool fixIt, int track) { int firstTrack = (track != -1) ? track : 0; int lastTrack = (track != -1) ? track : fFitterConfig->GetNumTracks(); for (int iTrack = firstTrack; iTrack < lastTrack; ++iTrack) { TrackAndType myTime(iTrack, FitterParameterType::kVtxT); fCurrentlyFixed.at(fTrackAndTypeIndexMap[myTime]) = fixIt; } } void WCSimFitterTrackParMap::FixConversionLength(int track) { FixOrFreeConversionLength(1, track); } void WCSimFitterTrackParMap::FreeConversionLength(int track) { FixOrFreeConversionLength(0, track); } void WCSimFitterTrackParMap::FixOrFreeConversionLength(bool fixIt, int track) { int firstTrack = (track != -1) ? track : 0; int lastTrack = (track != -1) ? track : fFitterConfig->GetNumTracks(); for (int iTrack = firstTrack; iTrack < lastTrack; ++iTrack) { TrackAndType myConversionLength(iTrack, FitterParameterType::kConversionDistance); fCurrentlyFixed.at(fTrackAndTypeIndexMap[myConversionLength]) = fixIt; } } std::vector<double> WCSimFitterTrackParMap::GetCurrentValues() { return fCurrentValues; } std::vector<double> WCSimFitterTrackParMap::GetMinValues() { return fMinValues; } std::vector<double> WCSimFitterTrackParMap::GetMaxValues() { return fMaxValues; } std::vector<bool> WCSimFitterTrackParMap::GetCurrentlyFixed() { return fCurrentlyFixed; } std::vector<bool> WCSimFitterTrackParMap::GetAlwaysFixed() { return fAlwaysFixed; } std::vector<bool> WCSimFitterTrackParMap::GetIsEnergy() { return fIsEnergy; } std::vector<double> WCSimFitterTrackParMap::GetSteps() { return fSteps; } std::vector<std::string> WCSimFitterTrackParMap::GetNames() { return fNames; } void WCSimFitterTrackParMap::SetCurrentValue(TrackAndType pairToSet, double value) { int index = GetIndex(pairToSet); fCurrentValues[index] = value; } void WCSimFitterTrackParMap::SetCurrentValue(int trackNum, FitterParameterType type, double value) { TrackAndType myPair(trackNum, type); SetCurrentValue(myPair, value); } void WCSimFitterTrackParMap::SetCurrentValue(int arrayIndex, double value) { assert(arrayIndex >= 0 && static_cast<unsigned int>(arrayIndex) < fCurrentValues.size()); fCurrentValues.at(arrayIndex) = value; } unsigned int WCSimFitterTrackParMap::GetIndex(int track, FitterParameterType type) { TrackAndType myPair(track, type); return GetIndex(myPair); } unsigned int WCSimFitterTrackParMap::GetIndex(TrackAndType trackAndType) { std::map<TrackAndType, unsigned int>::iterator findIndex = fTrackAndTypeIndexMap.find(trackAndType); assert(findIndex != fTrackAndTypeIndexMap.end()); return (*findIndex).second; } double WCSimFitterTrackParMap::GetMinValue(int track, FitterParameterType type) { TrackAndType myPair(track, type); return GetMinValue(myPair); } double WCSimFitterTrackParMap::GetMinValue(TrackAndType trackAndType) { return fMinValues[GetIndex(trackAndType)]; } double WCSimFitterTrackParMap::GetMaxValue(int track, FitterParameterType type) { TrackAndType myPair(track, type); return GetMaxValue(myPair); } double WCSimFitterTrackParMap::GetMaxValue(TrackAndType trackAndType) { return fMaxValues[GetIndex(trackAndType)]; } double WCSimFitterTrackParMap::GetCurrentValue(int track, FitterParameterType type) { TrackAndType myPair(track, type); return GetCurrentValue(myPair); } double WCSimFitterTrackParMap::GetCurrentValue(TrackAndType trackAndType) { int index = GetIndex(trackAndType); return fCurrentValues[index]; } double WCSimFitterTrackParMap::GetStep(int track, FitterParameterType type) { TrackAndType myPair(track, type); return GetStep(myPair); } double WCSimFitterTrackParMap::GetStep(TrackAndType trackAndType) { int index = GetIndex(trackAndType); return fSteps[index]; } TrackType::Type WCSimFitterTrackParMap::GetTrackType(int track) { //std::cout << "Track = " << track << " " << "Size = " << fTypes.size() << std::endl; assert(track >= 0 && static_cast<unsigned int>(track) < fTypes.size()); return fTypes.at(track); } bool WCSimFitterTrackParMap::GetIsFixed(int track, FitterParameterType type) { TrackAndType myPair(track, type); return GetIsFixed(myPair); } bool WCSimFitterTrackParMap::GetIsFixed(TrackAndType trackAndType) { int index = GetIndex(trackAndType); return fCurrentlyFixed[index]; } void WCSimFitterTrackParMap::Print() { std::cout << "WCSimFitterTrackParMap::Print()" << std::endl; std::map<TrackAndType, unsigned int>::iterator itr = fTrackAndTypeIndexMap.begin(); while (itr != fTrackAndTypeIndexMap.end()) { std::cout << "Track " << (itr->first).first << " Type: " << (itr->first).second << " Index: " << (itr->second) << std::endl; ++itr; } return; }
27.420428
150
0.741857
[ "vector" ]
6cbb3b00773d4c5033cd20eb82839326f9737a37
28,292
cpp
C++
generator/cfg.cpp
igormironchik/cfgfile
7d319aad671f0767f7d29a93ad279b4413bcbda2
[ "MIT" ]
5
2017-05-13T05:28:27.000Z
2019-07-15T07:39:58.000Z
generator/cfg.cpp
igormironchik/cfgfile
7d319aad671f0767f7d29a93ad279b4413bcbda2
[ "MIT" ]
2
2018-02-20T21:15:45.000Z
2018-09-23T07:38:28.000Z
generator/cfg.cpp
igormironchik/cfgfile
7d319aad671f0767f7d29a93ad279b4413bcbda2
[ "MIT" ]
2
2017-09-11T13:10:52.000Z
2019-11-23T22:52:52.000Z
/*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2017 Igor Mironchik 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. */ // generator_t cfg include. #include "cfg.hpp" // C++ include. #include <algorithm> namespace cfgfile { namespace generator { namespace cfg { // // constraint_base_t // constraint_base_t::constraint_base_t() { } constraint_base_t::~constraint_base_t() { } // // min_max_constraint_t // min_max_constraint_t::min_max_constraint_t( const std::string & min_value, const std::string & max_value ) : m_min( min_value ) , m_max( max_value ) { } min_max_constraint_t::~min_max_constraint_t() { } constraint_base_t::constraint_type_t min_max_constraint_t::type() const { return min_max_constraint_type; } const std::string & min_max_constraint_t::min() const { return m_min; } const std::string & min_max_constraint_t::max() const { return m_max; } // // one_of_constraint_t // one_of_constraint_t::one_of_constraint_t( const std::vector< std::string > & values ) : m_values( values ) { } one_of_constraint_t::~one_of_constraint_t() { } constraint_base_t::constraint_type_t one_of_constraint_t::type() const { return one_of_constraint_type; } const std::vector< std::string > & one_of_constraint_t::values() const { return m_values; } // // field_t // field_t::field_t() : m_type( unknown_field_type ) , m_line_number( -1 ) , m_column_number( -1 ) , m_is_required( false ) , m_is_base( false ) { } field_t::~field_t() { } bool field_t::operator == ( const std::string & n ) const { return ( name() == n ); } field_t::field_type_t field_t::type() const { return m_type; } void field_t::set_type( field_type_t t ) { m_type = t; } const std::string & field_t::value_type() const { return m_value_type; } void field_t::set_value_type( const std::string & t ) { m_value_type = t; } const std::string & field_t::name() const { return m_name; } void field_t::set_name( const std::string & n ) { m_name = n; } bool field_t::is_constraint_null() const { return ( m_constraint.get() == nullptr ); } const std::shared_ptr< constraint_base_t > & field_t::constraint() const { return m_constraint; } void field_t::set_constraint( const std::shared_ptr< constraint_base_t > & c ) { m_constraint = c; } long long field_t::line_number() const { return m_line_number; } void field_t::set_line_number( long long num ) { m_line_number = num; } long long field_t::column_number() const { return m_column_number; } void field_t::set_column_number( long long num ) { m_column_number = num; } bool field_t::is_required() const { return m_is_required; } void field_t::set_required( bool on ) { m_is_required = on; } const std::string & field_t::default_value() const { return m_default_value; } void field_t::set_default_value( const std::string & value ) { m_default_value = value; } bool field_t::is_base() const { return m_is_base; } void field_t::set_base( bool on ) { m_is_base = on; } // // class_t // class_t::class_t() : m_base_name( c_no_value_tag_name ) , m_line_number( -1 ) , m_column_number( -1 ) , m_index( 0 ) , m_parent( 0 ) { } class_t::~class_t() { } class_t::class_t( const class_t & other ) : m_name( other.name() ) , m_tag_name( other.tag_name() ) , m_base_name( other.base_name() ) , m_base_value_type( other.base_value_type() ) , m_fields( other.fields() ) , m_line_number( other.line_number() ) , m_column_number( other.column_number() ) , m_index( other.index() ) , m_parent( nullptr ) { } class_t & class_t::operator = ( const class_t & other ) { if( this != &other ) { m_name = other.name(); m_tag_name = other.tag_name(); m_base_name = other.base_name(); m_base_value_type = other.base_value_type(); m_fields = other.fields(); m_line_number = other.line_number(); m_column_number = other.column_number(); m_index = other.index(); m_parent = nullptr; } return *this; } bool class_t::operator == ( const std::string & n ) const { return ( name() == n ); } const std::string & class_t::name() const { return m_name; } const std::string & class_t::tag_name() const { return m_tag_name; } void class_t::set_tag_name( const std::string & n ) { m_tag_name = n; } void class_t::set_name( const std::string & n ) { m_name = n; } const std::string & class_t::base_name() const { return m_base_name; } void class_t::set_base_name( const std::string & n ) { m_base_name = n; } const std::string & class_t::base_value_type() const { return m_base_value_type; } void class_t::set_base_value_type( const std::string & t ) { m_base_value_type = t; } const std::vector< field_t > & class_t::fields() const { return m_fields; } const field_t * class_t::field_by_name( const std::string & n ) const { if( n.empty() ) return 0; std::vector< field_t >::const_iterator it = m_fields.cbegin(); std::vector< field_t >::const_iterator last = m_fields.cend(); for( ; it != last; ++it ) { if( it->name() == n ) return &(*it); } return 0; } field_t * class_t::field_by_name( const std::string & n ) { if( n.empty() ) return 0; std::vector< field_t >::iterator it = m_fields.begin(); std::vector< field_t >::iterator last = m_fields.end(); for( ; it != last; ++it ) { if( it->name() == n ) return &(*it); } return 0; } void class_t::add_field( const field_t & f ) { m_fields.push_back( f ); } long long class_t::line_number() const { return m_line_number; } void class_t::set_line_number( long long num ) { m_line_number = num; } long long class_t::column_number() const { return m_column_number; } void class_t::set_column_number( long long num ) { m_column_number = num; } unsigned long long class_t::index() const { return m_index; } void class_t::set_index( unsigned long long i ) const { m_index= i; } const namespace_t * class_t::parent_namespace() const { return m_parent; } void class_t::set_parent_namespace( const namespace_t * p ) const { m_parent = p; } // // namespace_t // namespace_t::namespace_t() : m_line_number( -1 ) , m_column_number( -1 ) , m_parent( 0 ) { } namespace_t::~namespace_t() { } namespace_t::namespace_t( const namespace_t & other ) : m_name( other.name() ) , m_nested_namespaces( other.all_nested() ) , m_classes( other.classes() ) , m_line_number( other.line_number() ) , m_column_number( other.column_number() ) , m_parent( nullptr ) { } namespace_t & namespace_t::operator = ( const namespace_t & other ) { if( this != &other ) { m_name = other.name(); m_nested_namespaces = other.all_nested(); m_classes = other.classes(); m_line_number = other.line_number(); m_column_number = other.column_number(); m_parent = nullptr; } return *this; } const std::string & namespace_t::name() const { return m_name; } void namespace_t::set_name( const std::string & n ) { m_name = n; } const std::vector< namespace_t > & namespace_t::all_nested() const { return m_nested_namespaces; } std::vector< const namespace_t* > namespace_t::nested( const std::string & n ) const { std::vector< const namespace_t* > res; if( n.empty() ) return res; std::vector< namespace_t >::const_iterator it = m_nested_namespaces.cbegin(); std::vector< namespace_t >::const_iterator last = m_nested_namespaces.cend(); for( ; it != last; ++it ) { if( it->name() == n ) res.push_back( &(*it) ); } return res; } std::vector< namespace_t* > namespace_t::nested( const std::string & n ) { std::vector< namespace_t* > res; if( n.empty() ) return res; std::vector< namespace_t >::iterator it = m_nested_namespaces.begin(); std::vector< namespace_t >::iterator last = m_nested_namespaces.end(); for( ; it != last; ++it ) { if( it->name() == n ) res.push_back( &(*it) ); } return res; } void namespace_t::add_namespace( const namespace_t & n ) { m_nested_namespaces.push_back( n ); } const std::vector< class_t > & namespace_t::classes() const { return m_classes; } const class_t * namespace_t::class_by_name( const std::string & n ) const { if( n.empty() ) return 0; std::vector< class_t >::const_iterator it = m_classes.cbegin(); std::vector< class_t >::const_iterator last = m_classes.cend(); for( ; it != last; ++it ) { if( it->name() == n ) return &(*it); } return 0; } class_t * namespace_t::class_by_name( const std::string & n ) { if( n.empty() ) return 0; std::vector< class_t >::iterator it = m_classes.begin(); std::vector< class_t >::iterator last = m_classes.end(); for( ; it != last; ++it ) { if( it->name() == n ) return &(*it); } return 0; } void namespace_t::add_class( const class_t & c ) { m_classes.push_back( c ); } long long namespace_t::line_number() const { return m_line_number; } void namespace_t::set_line_number( long long num ) { m_line_number = num; } long long namespace_t::column_number() const { return m_column_number; } void namespace_t::set_column_number( long long num ) { m_column_number = num; } const namespace_t * namespace_t::parent_namespace() const { return m_parent; } void namespace_t::set_parent_namespace( const namespace_t * p ) const { m_parent = p; } // // model_t // model_t::model_t() { } model_t::~model_t() { } model_t::model_t( const model_t & other ) : m_root( other.root_namespace() ) , m_global_includes( other.global_includes() ) , m_relative_includes( other.relative_includes() ) , m_include_guard( other.include_guard() ) { } model_t & model_t::operator = ( const model_t & other ) { if( this != &other ) { m_root = other.root_namespace(); m_global_includes = other.global_includes(); m_relative_includes = other.relative_includes(); m_include_guard = other.include_guard(); } return *this; } const namespace_t & model_t::root_namespace() const { return m_root; } namespace_t & model_t::root_namespace() { return m_root; } void model_t::set_root_namespace( const namespace_t & n ) { m_root = n; } const std::vector< std::string > & model_t::global_includes() const { return m_global_includes; } void model_t::set_global_includes( const std::vector< std::string > & inc ) { m_global_includes = inc; } void model_t::add_global_include( const std::string & inc ) { m_global_includes.push_back( inc ); } const std::vector< std::string > & model_t::relative_includes() const { return m_relative_includes; } void model_t::set_relative_includes( const std::vector< std::string > & inc ) { m_relative_includes = inc; } void model_t::add_relative_include( const std::string & inc ) { m_relative_includes.push_back( inc ); } void extract_and_bind_all_classes( const namespace_t & root, std::vector< const_class_ptr_t > & data ) { { std::vector< class_t >::const_iterator it = root.classes().cbegin(); std::vector< class_t >::const_iterator last = root.classes().cend(); for( ; it != last; ++it ) { data.push_back( &(*it) ); it->set_parent_namespace( &root ); } } { std::vector< namespace_t >::const_iterator it = root.all_nested().cbegin(); std::vector< namespace_t >::const_iterator last = root.all_nested().cend(); for( ; it != last; ++it ) { it->set_parent_namespace( &root ); extract_and_bind_all_classes( *it, data ); } } } struct const_class_ptr_less { bool operator () ( const const_class_ptr_t & c1, const const_class_ptr_t & c2 ) { if( c1->line_number() < c2->line_number() ) return true; else if( c1->line_number() == c2->line_number() ) return ( c1->column_number() < c2->column_number() ); else return false; } }; void model_t::prepare() { m_indexes.clear(); std::vector< const_class_ptr_t > sorted; extract_and_bind_all_classes( m_root, sorted ); std::sort( sorted.begin(), sorted.end(), const_class_ptr_less() ); unsigned long long index = 1; for( const const_class_ptr_t & c : sorted ) { c->set_index( index ); m_indexes.insert( std::make_pair( index, c ) ); ++index; } } void model_t::check() const { std::vector< std::string > classes; const_class_ptr_t c = 0; unsigned long long index = 0; const bool included = is_included(); while( ( c = next_class( index ) ) ) { check_class( *c, classes, included ); ++index; } } const_class_ptr_t model_t::next_class( unsigned long long index ) const { index += 1; if( m_indexes.find( index ) != m_indexes.cend() ) return m_indexes.at( index ); else return 0; } static inline std::string full_name( const class_t & c, const std::string & start_name = std::string() ) { std::string name = ( start_name.empty() ? c.name() : start_name ); const namespace_t * nm = c.parent_namespace(); while( nm ) { if( !nm->name().empty() ) { name.insert( 0, c_namespace_separator ); name.insert( 0, nm->name() ); } nm = nm->parent_namespace(); } return name; } static inline bool check_is_class_defined( const std::string & class_to_check, const std::vector< std::string > & prev_defined_classes ) { return ( std::find( prev_defined_classes.cbegin(), prev_defined_classes.cend(), class_to_check ) != prev_defined_classes.cend() ); } void model_t::check_class( const class_t & c, std::vector< std::string > & prev_defined_classes, bool included ) const { const std::string class_name = full_name( c ); if( std::find( prev_defined_classes.cbegin(), prev_defined_classes.cend(), class_name ) != prev_defined_classes.cend() ) throw cfgfile::exception_t< cfgfile::string_trait_t >( std::string( "Redefinition of class \"" ) + class_name + "\". Line " + std::to_string( c.line_number() ) + ", column " + std::to_string( c.column_number() ) + "." ); prev_defined_classes.push_back( class_name ); std::vector< std::string > fields; for( const field_t & f : c.fields() ) { if( f.is_base() ) { switch( f.type() ) { case field_t::scalar_field_type : case field_t::scalar_vector_field_type : { if( f.name().empty() ) throw cfgfile::exception_t< cfgfile::string_trait_t >( std::string( "Empty name of base type. Line " ) + std::to_string( f.line_number() ) + ", column " + std::to_string( f.column_number() ) + "." ); } break; default : break; } } else if( f.name().empty() ) throw cfgfile::exception_t< cfgfile::string_trait_t >( std::string( "Empty name of field of class \"" ) + class_name + "\". Line " + std::to_string( f.line_number() ) + ", column " + std::to_string( f.column_number() ) + "." ); if( std::find( fields.cbegin(), fields.cend(), f.name() ) != fields.cend() ) throw cfgfile::exception_t< cfgfile::string_trait_t >( std::string( "Field \"" ) + f.name() + "\" already defined in class \"" + class_name + "\". Line " + std::to_string( f.line_number() ) + ", column " + std::to_string( f.column_number() ) + "." ); else fields.push_back( f.name() ); if( !included ) { if( f.type() == field_t::custom_tag_field_type || f.type() == field_t::vector_of_tags_field_type ) { if( !check_is_class_defined( f.value_type(), prev_defined_classes ) ) { throw cfgfile::exception_t< cfgfile::string_trait_t >( std::string( "Value type \"" ) + f.value_type() + "\" of member \"" + f.name() + "\" of class \"" + class_name + "\" wasn't defined. Line " + std::to_string( c.line_number() ) + ", column " + std::to_string( c.column_number() ) + "." ); } } } } } bool model_t::is_included() const { return ( !m_global_includes.empty() || !m_relative_includes.empty() ); } const std::string & model_t::include_guard() const { return m_include_guard; } void model_t::set_include_guard( const std::string & guard ) { m_include_guard = guard; } // // tag_min_max_constraint_t // tag_min_max_constraint_t::tag_min_max_constraint_t( cfgfile::tag_t< cfgfile::string_trait_t > & owner ) : cfgfile::tag_no_value_t<> ( owner, c_min_max_constraint_tag_name, false ) , m_min( *this, c_min_tag_name, true ) , m_max( *this, c_max_tag_name, true ) { } tag_min_max_constraint_t::~tag_min_max_constraint_t() { } std::shared_ptr< min_max_constraint_t > tag_min_max_constraint_t::cfg() const { return std::shared_ptr< min_max_constraint_t > ( new min_max_constraint_t( m_min.value(), m_max.value() ) ); } // // tag_one_of_constraint_t // tag_one_of_constraint_t::tag_one_of_constraint_t( cfgfile::tag_t< cfgfile::string_trait_t > & owner ) : cfgfile::tag_scalar_vector_t< std::string > ( owner, c_one_of_constraint_tag_name, false ) { } tag_one_of_constraint_t::~tag_one_of_constraint_t() { } std::shared_ptr< one_of_constraint_t > tag_one_of_constraint_t::cfg() const { return std::shared_ptr< one_of_constraint_t > ( new one_of_constraint_t( values() ) ); } // // tag_field_t // tag_field_t::tag_field_t( const std::string & name, bool is_mandatory ) : cfgfile::tag_no_value_t<> ( name, is_mandatory ) , m_name( *this, c_field_name_tag_name, true ) , m_value_type( *this, c_value_type_tag_name, false ) , m_min_max_constraint( *this ) , m_one_of_constraint( *this ) , m_is_required( *this, c_required_tag_name, false ) , m_default_value( *this, c_default_value_tag_name, false ) { } tag_field_t::~tag_field_t() { } static inline field_t::field_type_t field_type_from_string( const std::string & type ) { if( type == c_scalar_tag_name ) return field_t::scalar_field_type; else if( type == c_no_value_tag_name ) return field_t::no_value_field_type; else if( type == c_scalar_vector_tag_name ) return field_t::scalar_vector_field_type; else if( type == c_vector_of_tags_tag_name ) return field_t::vector_of_tags_field_type; else if( type == c_custom_tag_name ) return field_t::custom_tag_field_type; else return field_t::unknown_field_type; } static inline void throw_constraint_redefinition( const std::string & class_name, const std::string & field_name, long long line_number, long long column_number ) { throw cfgfile::exception_t< cfgfile::string_trait_t >( std::string( "Redefinition of " "constraint in class \"" ) + class_name + "\", field \"" + field_name + "\". Line " + std::to_string( line_number ) + ", column " + std::to_string( column_number ) + "." ); } static inline void check_constraints( const cfgfile::tag_t< cfgfile::string_trait_t > & c1, const cfgfile::tag_t< cfgfile::string_trait_t > & c2, const std::string & class_name, const std::string& field_name ) { if( c1.is_defined() && c2.is_defined() ) { if( c1.line_number() == c2.line_number() ) { if( c1.column_number() > c2.column_number() ) throw_constraint_redefinition( class_name, field_name, c1.line_number(), c1.column_number() ); else throw_constraint_redefinition( class_name, field_name, c2.line_number(), c2.column_number() ); } else if( c1.line_number() > c2.line_number() ) throw_constraint_redefinition( class_name, field_name, c1.line_number(), c1.column_number() ); else throw_constraint_redefinition( class_name, field_name, c2.line_number(), c2.column_number() ); } } field_t tag_field_t::cfg() const { field_t f; f.set_type( field_type_from_string( name() ) ); f.set_name( m_name.value() ); f.set_line_number( line_number() ); f.set_column_number( column_number() ); if( m_value_type.is_defined() ) f.set_value_type( m_value_type.value() ); if( m_is_required.is_defined() ) f.set_required(); if( m_default_value.is_defined() ) f.set_default_value( m_default_value.value() ); else if( f.type() == field_t::no_value_field_type ) f.set_default_value( "false" ); const tag_class_t * c = static_cast< const tag_class_t* > ( parent() ); check_constraints( m_min_max_constraint, m_one_of_constraint, c->name(), m_name.value() ); if( m_min_max_constraint.is_defined() ) f.set_constraint( m_min_max_constraint.cfg() ); else if( m_one_of_constraint.is_defined() ) f.set_constraint( m_one_of_constraint.cfg() ); return f; } void tag_field_t::on_finish( const parser_info_t< cfgfile::string_trait_t > & info ) { switch( field_type_from_string( name() ) ) { case field_t::scalar_field_type : case field_t::scalar_vector_field_type : case field_t::vector_of_tags_field_type : { if( !m_value_type.is_defined() ) throw cfgfile::exception_t< cfgfile::string_trait_t >( std::string( "Undefined required " "tag \"" ) + c_value_type_tag_name + "\" in tag \"" + name() + "\". Line " + std::to_string( info.line_number() ) + ", column " + std::to_string( info.column_number() ) + "." ); } break; default : break; } cfgfile::tag_no_value_t<>::on_finish( info ); } // // tag_base_class_t // tag_base_class_t::tag_base_class_t( cfgfile::tag_t< cfgfile::string_trait_t > & owner, const std::string & name, bool is_mandatory ) : cfgfile::tag_scalar_t< std::string > ( owner, name, is_mandatory ) , m_value_type( *this, c_value_type_tag_name, false ) , m_name( *this, c_field_name_tag_name, false ) , m_min_max_constraint( *this ) , m_one_of_constraint( *this ) , m_is_required( *this, c_required_tag_name, false ) , m_default_value( *this, c_default_value_tag_name, false ) { m_constraint.add_value( c_scalar_tag_name ); m_constraint.add_value( c_no_value_tag_name ); m_constraint.add_value( c_scalar_vector_tag_name ); set_constraint( &m_constraint ); } tag_base_class_t::~tag_base_class_t() { } std::string tag_base_class_t::value_type() const { return m_value_type.value(); } std::string tag_base_class_t::tag_name() const { if( m_name.is_defined() ) return m_name.value(); else return std::string(); } field_t tag_base_class_t::cfg() const { field_t f; f.set_base( true ); f.set_type( field_type_from_string( value() ) ); f.set_name( m_name.value() ); f.set_line_number( line_number() ); f.set_column_number( column_number() ); if( m_value_type.is_defined() ) f.set_value_type( m_value_type.value() ); if( m_is_required.is_defined() ) f.set_required(); if( m_default_value.is_defined() ) f.set_default_value( m_default_value.value() ); const tag_class_t * c = static_cast< const tag_class_t* > ( parent() ); check_constraints( m_min_max_constraint, m_one_of_constraint, c->name(), m_name.value() ); if( m_min_max_constraint.is_defined() ) f.set_constraint( m_min_max_constraint.cfg() ); else if( m_one_of_constraint.is_defined() ) f.set_constraint( m_one_of_constraint.cfg() ); return f; } void tag_base_class_t::on_finish( const parser_info_t< cfgfile::string_trait_t > & info ) { switch( field_type_from_string( value() ) ) { case field_t::scalar_field_type : case field_t::scalar_vector_field_type : case field_t::vector_of_tags_field_type : { if( !m_value_type.is_defined() ) throw cfgfile::exception_t< cfgfile::string_trait_t >( std::string( "Undefined required " "tag \"" ) + c_value_type_tag_name + "\" in tag \"" + c_base_class_tag_name + "\". Line " + std::to_string( info.line_number() ) + ", column " + std::to_string( info.column_number() ) + "." ); if( !m_name.is_defined() ) throw cfgfile::exception_t< cfgfile::string_trait_t >( std::string( "Undefined required " "tag \"" ) + c_field_name_tag_name + "\" in tag \"" + c_base_class_tag_name + "\". Line " + std::to_string( info.line_number() ) + ", column " + std::to_string( info.column_number() ) + "." ); } break; default : break; } cfgfile::tag_scalar_t< std::string >::on_finish( info ); } // // tag_class_t // tag_class_t::tag_class_t( const std::string & name, bool is_mandatory ) : cfgfile::tag_scalar_t< std::string > ( name, is_mandatory ) , m_base_class_name( *this, c_base_class_tag_name, false ) , m_scalar_tags( *this, c_scalar_tag_name, false ) , m_no_value_tags( *this, c_no_value_tag_name, false ) , m_scalar_vector_tags( *this, c_scalar_vector_tag_name, false ) , m_vector_of_tags_tags( *this, c_vector_of_tags_tag_name, false ) , m_custom_tags( *this, c_custom_tag_name, false ) { } tag_class_t::~tag_class_t() { } class_t tag_class_t::cfg() const { class_t c; c.set_name( value() ); if( m_base_class_name.is_defined() ) { c.set_base_name( m_base_class_name.value() ); c.set_tag_name( m_base_class_name.tag_name() ); if( c.base_name() != c_no_value_tag_name ) { c.set_base_value_type( m_base_class_name.value_type() ); c.add_field( m_base_class_name.cfg() ); } } c.set_line_number( line_number() ); c.set_column_number( column_number() ); if( m_scalar_tags.is_defined() ) { for( std::size_t i = 0; i < m_scalar_tags.size(); ++i ) c.add_field( m_scalar_tags.at( i ).cfg() ); } if( m_no_value_tags.is_defined() ) { for( std::size_t i = 0; i < m_no_value_tags.size(); ++i ) c.add_field( m_no_value_tags.at( i ).cfg() ); } if( m_scalar_vector_tags.is_defined() ) { for( std::size_t i = 0; i < m_scalar_vector_tags.size(); ++i ) c.add_field( m_scalar_vector_tags.at( i ).cfg() ); } if( m_vector_of_tags_tags.is_defined() ) { for( std::size_t i = 0; i < m_vector_of_tags_tags.size(); ++i ) c.add_field( m_vector_of_tags_tags.at( i ).cfg() ); } if( m_custom_tags.is_defined() ) { for( std::size_t i = 0; i < m_custom_tags.size(); ++i ) c.add_field( m_custom_tags.at( i ).cfg() ); } return c; } // // tag_namespace_t // tag_namespace_t::tag_namespace_t( const std::string & name, bool is_mandatory ) : cfgfile::tag_scalar_t< std::string > ( name, is_mandatory ) , m_nested_namespaces( *this, c_namespace_tag_name, false ) , m_classes( *this, c_class_tag_name, false ) { } tag_namespace_t::~tag_namespace_t() { } namespace_t tag_namespace_t::cfg() const { namespace_t n; n.set_name( value() ); n.set_line_number( line_number() ); n.set_column_number( column_number() ); if( m_nested_namespaces.is_defined() ) { for( std::size_t i = 0; i < m_nested_namespaces.size(); ++i ) n.add_namespace( m_nested_namespaces.at( i ).cfg() ); } if( m_classes.is_defined() ) { for( std::size_t i = 0; i < m_classes.size(); ++i ) n.add_class( m_classes.at( i ).cfg() ); } return n; } // // tag_model_t // tag_model_t::tag_model_t() : cfgfile::tag_scalar_t< std::string > ( c_main_cfg_tag_name, true ) , m_root_namespace( *this, c_namespace_tag_name, false ) , m_root_classes( *this, c_class_tag_name, false ) , m_global_includes( *this, c_global_include_tag_name, false ) , m_relative_includes( *this, c_relative_include_tag_name, false ) { } tag_model_t::~tag_model_t() { } model_t tag_model_t::cfg() const { model_t m; m.set_include_guard( value() ); if( m_root_namespace.is_defined() ) { for( std::size_t i = 0; i < m_root_namespace.size(); ++i ) m.root_namespace().add_namespace( m_root_namespace.at( i ).cfg() ); } if( m_root_classes.is_defined() ) { for( std::size_t i = 0; i < m_root_classes.size(); ++i ) m.root_namespace().add_class( m_root_classes.at( i ).cfg() ); } if( m_global_includes.is_defined() ) { for( std::size_t i = 0; i < m_global_includes.size(); ++i ) m.add_global_include( m_global_includes.at( i ).value() ); } if( m_relative_includes.is_defined() ) { for( std::size_t i = 0; i < m_relative_includes.size(); ++i ) m.add_relative_include( m_relative_includes.at( i ).value() ); } return m; } } /* namespace cfg */ } /* namespace generator */ } /* namespace cfgfile */
20.122333
101
0.68507
[ "vector" ]
6cbc919c88f3da4253c4b5914e0d465549fca988
6,515
cpp
C++
AllJoyn/Platform/DeviceProviders/AllJoynSignal.cpp
shuWebDev/samples
4b2c23cf16bdbe58cb2beba7c202c85242419d2e
[ "MIT" ]
1,433
2015-04-30T09:26:53.000Z
2022-03-26T12:44:12.000Z
AllJoyn/Platform/DeviceProviders/AllJoynSignal.cpp
LeCampusAzure/ms-iot-samples
c0da021a312a631c8a26771a0d203e0de80fc597
[ "MIT" ]
530
2015-05-02T09:12:48.000Z
2018-01-03T17:52:01.000Z
AllJoyn/Platform/DeviceProviders/AllJoynSignal.cpp
LeCampusAzure/ms-iot-samples
c0da021a312a631c8a26771a0d203e0de80fc597
[ "MIT" ]
1,878
2015-04-30T04:18:57.000Z
2022-03-15T16:51:17.000Z
// // Copyright (c) 2015, Microsoft Corporation // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // #include "pch.h" #include "AllJoynInterface.h" #include "AllJoynSignal.h" #include "AllJoynTypeDefinition.h" #include "TypeConversionHelpers.h" #include "AllJoynHelpers.h" using namespace Windows::Foundation::Collections; using namespace Windows::Foundation; using namespace Platform::Collections; using namespace Platform; using namespace concurrency; using namespace std; namespace DeviceProviders { map<string, WeakReference> AllJoynSignal::s_signalMap; CSLock AllJoynSignal::s_signalMapLock; AllJoynSignal::AllJoynSignal(AllJoynInterface ^ parent, const alljoyn_interfacedescription_member& signalDescription) : m_interface(parent) , m_name(signalDescription.name) , m_interfaceName(parent->GetName()) , m_objectPath(parent->GetBusObject()->GetPath()) , m_aboutData(parent->GetBusObject()->GetService()->AboutData) , m_signatureString(signalDescription.signature) , m_member(signalDescription) , m_subscriberCount(0) , m_active(true) { DEBUG_LIFETIME_IMPL(AllJoynSignal); m_signature = AllJoynTypeDefinition::CreateParameterInfo(m_signatureString, AllJoynHelpers::TokenizeArgNamesString(signalDescription.argNames)); { AutoLock lockScope(&s_signalMapLock, true); string key = BuildSignalMapKey(parent->GetBusObject()->GetPath().c_str(), parent->GetName().c_str(), m_name.c_str()); s_signalMap[key] = WeakReference(this); } //annotations m_annotations = TypeConversionHelpers::GetAnnotationsView<alljoyn_interfacedescription_member>( signalDescription, alljoyn_interfacedescription_member_getannotationscount, alljoyn_interfacedescription_member_getannotationatindex); } AllJoynSignal::~AllJoynSignal() { if (m_active) { Shutdown(); } } void AllJoynSignal::Shutdown() { m_active = false; alljoyn_busattachment_unregistersignalhandler(m_interface->GetBusAttachment(), AllJoynSignal::OnSignal, m_member, m_interface->GetBusObject()->GetPath().c_str()); } string AllJoynSignal::BuildSignalMapKey(const char *objectPath, const char *interfaceName, const char *signalName) { static const char * formatString = "path=%s,interface=%s,signal=%s"; int bufferSize = snprintf(nullptr, 0, formatString, objectPath, interfaceName, signalName); auto buffer = vector<char>(bufferSize + 1); snprintf(buffer.data(), bufferSize + 1, formatString, objectPath, interfaceName, signalName); return buffer.data(); } void AllJoynSignal::OnSignal(_In_ const alljoyn_interfacedescription_member *member, _In_ const char* srcPath, _In_ alljoyn_message message) { const char *interfaceName = alljoyn_interfacedescription_getname(member->iface); string key = BuildSignalMapKey(srcPath, interfaceName, member->name); AllJoynSignal ^ thisptr = nullptr; { AutoLock lockScope(&s_signalMapLock, true); auto iter = s_signalMap.find(key); if (iter == s_signalMap.end()) { return; } thisptr = iter->second.Resolve<AllJoynSignal>(); if (thisptr == nullptr) { return; } } auto responseSignature = alljoyn_message_getsignature(message); if (thisptr->m_signatureString != responseSignature) { return; } std::vector<string> completeTypes; TypeConversionHelpers::CreateCompleteTypeSignatureArrayFromSignature(responseSignature, completeTypes); Platform::Collections::Vector<Object ^> ^ signaledValues = ref new Vector<Object ^>(); for (size_t i = 0; i < thisptr->m_signature->Size; ++i) { Object ^ value; int32 result = TypeConversionHelpers::GetAllJoynMessageArg( alljoyn_message_getarg(message, i), completeTypes[i].c_str(), &value); if (result != ER_OK) { return; } signaledValues->Append(value); } thisptr->SignalRaised(thisptr, signaledValues); } IVector<ParameterInfo ^>^ AllJoynSignal::Signature::get() { return m_signature; } String ^ AllJoynSignal::Name::get() { return AllJoynHelpers::MultibyteToPlatformString(m_name.c_str()); } Windows::Foundation::EventRegistrationToken AllJoynSignal::SignalRaised::add(Windows::Foundation::TypedEventHandler<ISignal^, Windows::Foundation::Collections::IVector<Object^>^>^ handler) { if (m_active && m_subscriberCount++ == 0) { alljoyn_busattachment_registersignalhandler(m_interface->GetBusAttachment(), AllJoynSignal::OnSignal, m_member, m_interface->GetBusObject()->GetPath().c_str()); } return m_signalRaised += handler; } void AllJoynSignal::SignalRaised::remove(Windows::Foundation::EventRegistrationToken token) { if (m_active && --m_subscriberCount == 0) { alljoyn_busattachment_unregistersignalhandler(m_interface->GetBusAttachment(), AllJoynSignal::OnSignal, m_member, m_interface->GetBusObject()->GetPath().c_str()); } m_signalRaised -= token; } void AllJoynSignal::SignalRaised::raise(ISignal^ sender, Windows::Foundation::Collections::IVector<Object^>^ params) { m_signalRaised(sender, params); } }
35.796703
192
0.658173
[ "object", "vector" ]
6cc08351d8363737a0780d9c5df9b00d1d1de980
3,602
hpp
C++
include/analysis.hpp
CrazyOverdose/lab-04-boost-filesystem
b0ce1ab53ae3e9fe2f8a7e60bf56d0555bb7d42a
[ "MIT" ]
null
null
null
include/analysis.hpp
CrazyOverdose/lab-04-boost-filesystem
b0ce1ab53ae3e9fe2f8a7e60bf56d0555bb7d42a
[ "MIT" ]
null
null
null
include/analysis.hpp
CrazyOverdose/lab-04-boost-filesystem
b0ce1ab53ae3e9fe2f8a7e60bf56d0555bb7d42a
[ "MIT" ]
null
null
null
//Copyright 2019 CrazyOverdose #ifndef INCLUDE_ANALYSIS_HPP_ #define INCLUDE_ANALYSIS_HPP_ #include <boost/filesystem.hpp> #include <vector> #include <string> #include <cstdlib> struct Date { int day; int month; int year; }; struct information { std::string title; //название файла std:: string broker; //папка std:: string type; int account; //аккаунт Date data; // дата }; std::ostream& operator<< (std::ostream &out, const Date &date) { out << date.day << "." << date.month << "." << date.year; return out; } bool lastdate(information file1, information file2) { if (file1.data.year < file2.data.year) return 1; if (file1.data.year > file2.data.year) return 0; if (file1.data.month < file2.data.month) return 1; if (file1.data.month > file2.data.month) return 0; if (file1.data.day < file2.data.day) return 1; if (file1.data.day > file2.data.day) return 0; return 0; } class analysis { protected: boost::filesystem :: path path_to_ftp; std::vector <information> informations; std::unordered_map<int, std::vector<information>> accounts_groups; public: explicit analysis(boost::filesystem :: path path) { this->path_to_ftp = path; } void work(boost::filesystem :: path path) { for (boost::filesystem::directory_entry dir_iter : boost::filesystem::directory_iterator{ path }) { if (boost::filesystem::is_regular_file(dir_iter)) file(dir_iter); if (boost::filesystem::is_directory(dir_iter)) work(dir_iter); } } void file(boost::filesystem :: path path) { try { information new_file = parcer(path.filename().string()); informations.push_back(new_file); accounts_groups[new_file.account].push_back(new_file); } catch (const std::logic_error&){} } void print_name_files() { std::cout << "Task one " << std::endl; for (size_t i = 0; i < informations.size(); ++i) { std::cout << informations[i].broker << " "; std::cout << informations[i].title << std::endl; } } void print_information() { std::cout << "Task two " << std::endl; for (const auto& i : accounts_groups ) { std::cout << "broker: " << i.second[0].broker << "| "; std::cout << "account: " << i.first << "| "; std::cout << "files: " << i.second.size() << "| "; std::cout << "lastdate: "; std::cout << std::max_element(i.second.begin(), i.second.end(), lastdate)->data; std::cout << " "; std::cout << std::endl; } } information parcer(std::string file) { information new_file; new_file.title = file; new_file.type = file.substr(0, file.find('_')); file = file.substr(file.find('_') + 1); new_file.account = std::stoi(file.substr(0, file.find('_'))); file = file.substr(file.find('_') + 1); new_file.data.year = std::stoi(file.substr(0, 4)); new_file.data.month = std::stoi(file.substr(4, 2)); new_file.data.day = std::stoi(file.substr(6, 2)); file = file.substr(8); if (file[0] != '.' || file.substr(0, 4) == ".old") throw std::logic_error(""); if (file.substr(1).find('.') != std::string::npos) throw std::logic_error(""); return new_file; } }; #endif // INCLUDE_ANALYSIS_HPP_
24.337838
80
0.557746
[ "vector" ]
6cc2f0c0c5037cdc8694010b843bc49c15afa729
15,135
cpp
C++
src/model_parser.cpp
SausageTaste/DalbaragiTools
d07e82ecdb9117cffa886e50b89808e2dbf245c6
[ "MIT" ]
null
null
null
src/model_parser.cpp
SausageTaste/DalbaragiTools
d07e82ecdb9117cffa886e50b89808e2dbf245c6
[ "MIT" ]
null
null
null
src/model_parser.cpp
SausageTaste/DalbaragiTools
d07e82ecdb9117cffa886e50b89808e2dbf245c6
[ "MIT" ]
null
null
null
#include "daltools/model_parser.h" #include "daltools/byte_tool.h" #include "daltools/konst.h" #include "daltools/compression.h" namespace dalp = dal::parser; namespace { std::optional<std::vector<uint8_t>> unzip_dal_model(const uint8_t* const buf, const size_t buf_size) { const auto expected_unzipped_size = dal::parser::make_int32(buf + dalp::MAGIC_NUMBER_SIZE); const auto zipped_data_offset = dalp::MAGIC_NUMBER_SIZE + 4; std::vector<uint8_t> unzipped(expected_unzipped_size); const auto decomp_result = dal::decompress_zip(unzipped.data(), unzipped.size(), buf + zipped_data_offset, buf_size - zipped_data_offset); if (dal::CompressResult::success != decomp_result.m_result) { return std::nullopt; } else { return unzipped; } } bool is_magic_numbers_correct(const uint8_t* const buf) { for (int i = 0; i < dalp::MAGIC_NUMBER_SIZE; ++i) { if (buf[i] != dalp::MAGIC_NUMBERS_DAL_MODEL[i]) { return false; } } return true; } } // Parser functions namespace { const uint8_t* parse_aabb(const uint8_t* header, const uint8_t* const end, dal::parser::AABB3& output) { float fbuf[6]; header = dal::parser::assemble_4_bytes_array<float>(header, fbuf, 6); output.m_min = glm::vec3{ fbuf[0], fbuf[1], fbuf[2] }; output.m_max = glm::vec3{ fbuf[3], fbuf[4], fbuf[5] }; return header; } const uint8_t* parse_mat4(const uint8_t* header, const uint8_t* const end, glm::mat4& mat) { float fbuf[16]; header = dalp::assemble_4_bytes_array<float>(header, fbuf, 16); for ( size_t row = 0; row < 4; ++row ) { for ( size_t col = 0; col < 4; ++col ) { mat[col][row] = fbuf[4 * row + col]; } } return header; } } // Parse animations namespace { const uint8_t* parse_skeleton(const uint8_t* header, const uint8_t* const end, dalp::Skeleton& output) { header = ::parse_mat4(header, end, output.m_root_transform); const auto joint_count = dal::parser::make_int32(header); header += 4; output.m_joints.resize(joint_count); for ( int i = 0; i < joint_count; ++i ) { auto& joint = output.m_joints.at(i); joint.m_name = reinterpret_cast<const char*>(header); header += joint.m_name.size() + 1; joint.m_parent_index = dalp::make_int32(header); header += 4; const auto joint_type_index = dalp::make_int32(header); header += 4; switch ( joint_type_index ) { case 0: joint.m_joint_type = dalp::JointType::basic; break; case 1: joint.m_joint_type = dalp::JointType::hair_root; break; case 2: joint.m_joint_type = dalp::JointType::skirt_root; break; default: joint.m_joint_type = dalp::JointType::basic; } header = parse_mat4(header, end, joint.m_offset_mat); } return header; } const uint8_t* parse_animJoint(const uint8_t* header, const uint8_t* const end, dalp::AnimJoint& output) { { output.m_name = reinterpret_cast<const char*>(header); header += output.m_name.size() + 1; glm::mat4 _; header = parse_mat4(header, end, _); } { const auto num = dalp::make_int32(header); header += 4; for ( int i = 0; i < num; ++i ) { float fbuf[4]; header = dalp::assemble_4_bytes_array<float>(header, fbuf, 4); output.add_position(fbuf[0], fbuf[1], fbuf[2], fbuf[3]); } } { const auto num = dalp::make_int32(header); header += 4; for ( int i = 0; i < num; ++i ) { float fbuf[5]; header = dalp::assemble_4_bytes_array<float>(header, fbuf, 5); output.add_rotation(fbuf[0], fbuf[4], fbuf[1], fbuf[2], fbuf[3]); } } { const auto num = dalp::make_int32(header); header += 4; for ( int i = 0; i < num; ++i ) { float fbuf[2]; header = dalp::assemble_4_bytes_array<float>(header, fbuf, 2); output.add_scale(fbuf[0], fbuf[1]); } } return header; } const uint8_t* parse_animations(const uint8_t* header, const uint8_t* const end, std::vector<dalp::Animation>& animations) { const auto anim_count = dalp::make_int32(header); header += 4; animations.resize(anim_count); for ( int i = 0; i < anim_count; ++i ) { auto& anim = animations.at(i); anim.m_name = reinterpret_cast<const char*>(header); header += anim.m_name.size() + 1; const auto duration_tick = dalp::make_float32(header); header += 4; anim.m_ticks_per_sec = dalp::make_float32(header); header += 4; const auto joint_count = dalp::make_int32(header); header += 4; anim.m_joints.resize(joint_count); for ( int j = 0; j < joint_count; ++j ) { header = ::parse_animJoint(header, end, anim.m_joints.at(j)); } } return header; } } // Parse render units namespace { const uint8_t* parse_material(const uint8_t* header, const uint8_t* const end, dalp::Material& material) { material.m_roughness = dalp::make_float32(header); header += 4; material.m_metallic = dalp::make_float32(header); header += 4; material.m_transparency = dalp::make_bool8(header); header += 1; material.m_albedo_map = reinterpret_cast<const char*>(header); header += material.m_albedo_map.size() + 1; material.m_roughness_map = reinterpret_cast<const char*>(header); header += material.m_roughness_map.size() + 1; material.m_metallic_map = reinterpret_cast<const char*>(header); header += material.m_metallic_map.size() + 1; material.m_normal_map = reinterpret_cast<const char*>(header); header += material.m_normal_map.size() + 1; return header; } const uint8_t* parse_mesh(const uint8_t* header, const uint8_t* const end, dalp::Mesh_Straight& mesh) { const auto vert_count = dalp::make_int32(header); header += 4; const auto vert_count_times_3 = vert_count * 3; const auto vert_count_times_2 = vert_count * 2; mesh.m_vertices.resize(vert_count_times_3); header = dalp::assemble_4_bytes_array<float>(header, mesh.m_vertices.data(), vert_count_times_3); mesh.m_texcoords.resize(vert_count_times_2); header = dalp::assemble_4_bytes_array<float>(header, mesh.m_texcoords.data(), vert_count_times_2); mesh.m_normals.resize(vert_count_times_3); header = dalp::assemble_4_bytes_array<float>(header, mesh.m_normals.data(), vert_count_times_3); return header; } const uint8_t* parse_mesh(const uint8_t* header, const uint8_t* const end, dalp::Mesh_StraightJoint& mesh) { const auto vert_count = dalp::make_int32(header); header += 4; const auto vert_count_times_3 = vert_count * 3; const auto vert_count_times_2 = vert_count * 2; const auto vert_count_times_joint_count = vert_count * dal::parser::NUM_JOINTS_PER_VERTEX; mesh.m_vertices.resize(vert_count_times_3); header = dalp::assemble_4_bytes_array<float>(header, mesh.m_vertices.data(), vert_count_times_3); mesh.m_texcoords.resize(vert_count_times_2); header = dalp::assemble_4_bytes_array<float>(header, mesh.m_texcoords.data(), vert_count_times_2); mesh.m_normals.resize(vert_count_times_3); header = dalp::assemble_4_bytes_array<float>(header, mesh.m_normals.data(), vert_count_times_3); mesh.m_boneWeights.resize(vert_count_times_joint_count); header = dalp::assemble_4_bytes_array<float>(header, mesh.m_boneWeights.data(), vert_count_times_joint_count); mesh.m_boneIndex.resize(vert_count_times_joint_count); header = dalp::assemble_4_bytes_array<int32_t>(header, mesh.m_boneIndex.data(), vert_count_times_joint_count); return header; } const uint8_t* parse_mesh(const uint8_t* header, const uint8_t* const end, dalp::Mesh_Indexed& mesh) { const auto vertex_count = dalp::make_int32(header); header += 4; for (int32_t i = 0; i < vertex_count; ++i) { auto& vert = mesh.m_vertices.emplace_back(); float fbuf[8]; header = dalp::assemble_4_bytes_array<float>(header, fbuf, 8); vert.m_position = glm::vec3{ fbuf[0], fbuf[1], fbuf[2] }; vert.m_normal = glm::vec3{ fbuf[3], fbuf[4], fbuf[5] }; vert.m_uv_coords = glm::vec2{ fbuf[6], fbuf[7] }; } const auto index_count = dalp::make_int32(header); header += 4; for (int32_t i = 0; i < index_count; ++i) { mesh.m_indices.push_back(dalp::make_int32(header)); header += 4; } return header; } const uint8_t* parse_mesh(const uint8_t* header, const uint8_t* const end, dalp::Mesh_IndexedJoint& mesh) { const auto vertex_count = dalp::make_int32(header); header += 4; for (int32_t i = 0; i < vertex_count; ++i) { auto& vert = mesh.m_vertices.emplace_back(); float fbuf[8]; header = dalp::assemble_4_bytes_array<float>(header, fbuf, 8); float fbuf_joint[dal::parser::NUM_JOINTS_PER_VERTEX]; header = dalp::assemble_4_bytes_array<float>(header, fbuf_joint, dal::parser::NUM_JOINTS_PER_VERTEX); int32_t ibuf_joint[dal::parser::NUM_JOINTS_PER_VERTEX]; header = dalp::assemble_4_bytes_array<int32_t>(header, ibuf_joint, dal::parser::NUM_JOINTS_PER_VERTEX); vert.m_position = glm::vec3{ fbuf[0], fbuf[1], fbuf[2] }; vert.m_normal = glm::vec3{ fbuf[3], fbuf[4], fbuf[5] }; vert.m_uv_coords = glm::vec2{ fbuf[6], fbuf[7] }; static_assert(sizeof(vert.m_joint_weights.x) == sizeof(float)); static_assert(sizeof(vert.m_joint_indices.x) == sizeof(int32_t)); static_assert(sizeof(vert.m_joint_weights) == sizeof(float) * dal::parser::NUM_JOINTS_PER_VERTEX); static_assert(sizeof(vert.m_joint_indices) == sizeof(int32_t) * dal::parser::NUM_JOINTS_PER_VERTEX); memcpy(&vert.m_joint_weights, fbuf_joint, sizeof(vert.m_joint_weights)); memcpy(&vert.m_joint_indices, ibuf_joint, sizeof(vert.m_joint_indices)); } const auto index_count = dalp::make_int32(header); header += 4; for (int32_t i = 0; i < index_count; ++i) { mesh.m_indices.push_back(dalp::make_int32(header)); header += 4; } return header; } template <typename _Mesh> const uint8_t* parse_render_unit(const uint8_t* header, const uint8_t* const end, dalp::RenderUnit<_Mesh>& unit) { unit.m_name = reinterpret_cast<const char*>(header); header += unit.m_name.size() + 1; header = ::parse_material(header, end, unit.m_material); header = ::parse_mesh(header, end, unit.m_mesh); return header; } dalp::ModelParseResult parse_all(dalp::Model& output, const uint8_t* const begin, const uint8_t* const end) { const uint8_t* header = begin; header = ::parse_aabb(header, end, output.m_aabb); header = ::parse_skeleton(header, end, output.m_skeleton); header = ::parse_animations(header, end, output.m_animations); output.m_units_straight.resize(dalp::make_int32(header)); header += 4; for (auto& unit : output.m_units_straight) { header = ::parse_render_unit(header, end, unit); } output.m_units_straight_joint.resize(dalp::make_int32(header)); header += 4; for (auto& unit : output.m_units_straight_joint) { header = ::parse_render_unit(header, end, unit); } output.m_units_indexed.resize(dalp::make_int32(header)); header += 4; for (auto& unit : output.m_units_indexed) { header = ::parse_render_unit(header, end, unit); } output.m_units_indexed_joint.resize(dalp::make_int32(header)); header += 4; for (auto& unit : output.m_units_indexed_joint) { header = ::parse_render_unit(header, end, unit); } output.m_signature_hex = reinterpret_cast<const char*>(header); header += output.m_signature_hex.size() + 1; if (header != end) return dalp::ModelParseResult::corrupted_content; else return dalp::ModelParseResult::success; } } namespace dal::parser { ModelParseResult parse_dmd(Model& output, const uint8_t* const file_content, const size_t content_size) { // Check magic numbers if (!::is_magic_numbers_correct(file_content)) return dalp::ModelParseResult::magic_numbers_dont_match; // Decompress const auto unzipped = ::unzip_dal_model(file_content, content_size); if (!unzipped) return dalp::ModelParseResult::decompression_failed; // Parse return ::parse_all(output, unzipped->data(), unzipped->data() + unzipped->size()); } ModelParseResult parse_verify_dmd( Model& output, const uint8_t* const file_content, const size_t content_size, const crypto::PublicKeySignature::PublicKey& public_key, crypto::PublicKeySignature& sign_mgr ) { // Check magic numbers if (!::is_magic_numbers_correct(file_content)) return dalp::ModelParseResult::magic_numbers_dont_match; // Decompress const auto unzipped = ::unzip_dal_model(file_content, content_size); if (!unzipped) return dalp::ModelParseResult::decompression_failed; // Parse { const auto parse_result = ::parse_all(output, unzipped->data(), unzipped->data() + unzipped->size()); if (dalp::ModelParseResult::success != parse_result) return parse_result; } // Varify { const dal::crypto::PublicKeySignature::Signature signature{ output.m_signature_hex }; const auto varify_result = sign_mgr.verify( unzipped->data(), unzipped->size() - output.m_signature_hex.size() - 1, public_key, signature ); if (!varify_result) return ModelParseResult::invalid_signature; } return ModelParseResult::success; } std::optional<Model> parse_dmd(const uint8_t* const file_content, const size_t content_size) { Model output; if (ModelParseResult::success != dalp::parse_dmd(output, file_content, content_size)) return std::nullopt; else return output; } }
37.555831
146
0.615064
[ "mesh", "render", "vector", "model" ]
6cca769a208e3bf898b57f1bb12ba7b699487176
630
cpp
C++
src/sofar_isa/src/main.cpp
CristinaNRR/SOFAR
194ed37a0b870a586ea048a0d3c4d97750201ec4
[ "Unlicense" ]
1
2021-11-06T17:53:13.000Z
2021-11-06T17:53:13.000Z
src/sofar_isa/src/main.cpp
isabella-sole/Software_Architecture_Project
194ed37a0b870a586ea048a0d3c4d97750201ec4
[ "Unlicense" ]
null
null
null
src/sofar_isa/src/main.cpp
isabella-sole/Software_Architecture_Project
194ed37a0b870a586ea048a0d3c4d97750201ec4
[ "Unlicense" ]
2
2021-11-06T14:45:05.000Z
2022-01-28T08:33:43.000Z
#include "menuwindow.h" #include "welcome.h" #include <QApplication> #include <cstdlib> #include <iostream> #include <string> #include "ros/ros.h" int main(int argc, char *argv[]) { ros::init(argc, argv, "GUI"); ros::NodeHandle n; QApplication a(argc, argv); //object creation welcome *wel= new welcome(); //creates the window wel->show(); //visualize the window ros::AsyncSpinner spinner(0); spinner.start(); ros::Subscriber sub = n.subscribe("/topicPathPlanner_IdNow", 1000, &welcome::StatusNowCallback, wel); a.exec(); //execute the code ros::waitForShutdown(); return 0; }
21
105
0.660317
[ "object" ]
6cd13dd759f4524b509e5d79f6b45faf5eea92f4
7,069
cpp
C++
platform/linux/src/Rtt_LinuxSimulatorView.cpp
seyhajin/corona
844986781ce1b07f9f876e759c6405b4c56c6898
[ "MIT" ]
null
null
null
platform/linux/src/Rtt_LinuxSimulatorView.cpp
seyhajin/corona
844986781ce1b07f9f876e759c6405b4c56c6898
[ "MIT" ]
null
null
null
platform/linux/src/Rtt_LinuxSimulatorView.cpp
seyhajin/corona
844986781ce1b07f9f876e759c6405b4c56c6898
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: support@coronalabs.com // ////////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <math.h> #include <wx/string.h> #include <wx/menu.h> #include <wx/textctrl.h> #include <sstream> #include <fstream> #include "Rtt_LuaContext.h" #include "Rtt_LuaFile.h" #include "Rtt_MPlatform.h" #include "Rtt_PlatformAppPackager.h" #include "Rtt_PlatformPlayer.h" #include "Rtt_PlatformSimulator.h" #include "Rtt_RenderingStream.h" #include "Rtt_Runtime.h" #include "Rtt_SimulatorAnalytics.h" #include "Rtt_LinuxPlatform.h" #include "Rtt_LinuxSimulatorServices.h" #include "Rtt_LinuxSimulatorView.h" #include "Rtt_LinuxUtils.h" #include "Rtt_SimulatorRecents.h" #include "Rtt_WebAppPackager.h" #include "Rtt_LinuxAppPackager.h" #include "Rtt_AndroidAppPackager.h" #include "Core/Rtt_FileSystem.h" using namespace std; namespace Rtt { LinuxPlatformServices::LinuxPlatformServices(MPlatform* platform) : fPlatform(platform) { } // static initialise vars const float LinuxSimulatorView::skinScaleFactor = 1.5; const int LinuxSimulatorView::skinMinWidth = 320; std::map<int, LinuxSimulatorView::SkinProperties> LinuxSimulatorView::fSkins; bool LinuxSimulatorView::LoadSkin(lua_State* L, int skinID, std::string filePath) { int top = lua_gettop(L); int status = Lua::DoFile(L, filePath.c_str(), 0, true); lua_pop(L, 1); // remove DoFile result lua_getglobal(L, "simulator"); SkinProperties skin; if (lua_type(L, -1) == LUA_TTABLE) { lua_getfield(L, -1, "device"); if (lua_type(L, -1) == LUA_TSTRING) { skin.device = lua_tostring(L, -1); } lua_pop(L, 1); lua_getfield(L, -1, "screenOriginX"); if (lua_type(L, -1) == LUA_TNUMBER) { skin.screenOriginX = lua_tointeger(L, -1); } lua_pop(L, 1); lua_getfield(L, -1, "screenOriginY"); if (lua_type(L, -1) == LUA_TNUMBER) { skin.screenOriginY = lua_tointeger(L, -1); } lua_pop(L, 1); lua_getfield(L, -1, "screenWidth"); if (lua_type(L, -1) == LUA_TNUMBER) { skin.screenWidth = lua_tointeger(L, -1); } lua_pop(L, 1); lua_getfield(L, -1, "screenHeight"); if (lua_type(L, -1) == LUA_TNUMBER) { skin.screenHeight = lua_tointeger(L, -1); } lua_pop(L, 1); lua_getfield(L, -1, "androidDisplayApproximateDpi"); if (lua_type(L, -1) == LUA_TNUMBER) { skin.androidDisplayApproximateDpi = lua_tointeger(L, -1); } lua_pop(L, 1); lua_getfield(L, -1, "displayManufacturer"); if (lua_type(L, -1) == LUA_TSTRING) { skin.displayManufacturer = lua_tostring(L, -1); } lua_pop(L, 1); lua_getfield(L, -1, "displayName"); if (lua_type(L, -1) == LUA_TSTRING) { skin.displayName = lua_tostring(L, -1); } lua_pop(L, 1); lua_getfield(L, -1, "isUprightOrientationPortrait"); if (lua_type(L, -1) == LUA_TBOOLEAN) { skin.isUprightOrientationPortrait = lua_toboolean(L, -1); } lua_pop(L, 1); lua_getfield(L, -1, "supportsScreenRotation"); if (lua_type(L, -1) == LUA_TBOOLEAN) { skin.supportsScreenRotation = lua_toboolean(L, -1); } lua_pop(L, 1); lua_getfield(L, -1, "windowTitleBarName"); if (lua_type(L, -1) == LUA_TSTRING) { skin.windowTitleBarName = lua_tostring(L, -1); } lua_pop(L, 1); // pop simulator lua_pop(L, 1); lua_settop(L, top); wxString skinTitle(skin.windowTitleBarName); skinTitle.append(wxString::Format(wxT(" (%ix%i)"), skin.screenWidth, skin.screenHeight)); skin.skinTitle = skinTitle; skin.id = skinID; skin.selected = false; fSkins[skinID] = skin; } else { printf("Couldn't find 'simulator' table\n"); } return (status == 0); } LinuxSimulatorView::SkinProperties LinuxSimulatorView::GetSkinProperties(int skinID) { if (fSkins.count(skinID) > 0) { return fSkins[skinID]; } return fSkins.begin()->second; } LinuxSimulatorView::SkinProperties LinuxSimulatorView::GetSkinProperties(wxString skinTitle) { SkinProperties foundSkin; for (int i = 0; i < fSkins.size(); i++) { if (fSkins[i].skinTitle.IsSameAs(skinTitle)) { foundSkin = fSkins[i]; break; } } return foundSkin; } void LinuxSimulatorView::DeselectSkins() { for (int i = 0; i < fSkins.size(); i++) { fSkins[i].selected = false; } } void LinuxSimulatorView::SelectSkin(int skinID) { if (fSkins.count(skinID) > 0) { DeselectSkins(); fSkins[skinID].selected = true; } } void LinuxSimulatorView::OnLinuxPluginGet(const char* appPath, const char* appName, LinuxPlatform* platform) { const char* identity = "no-identity"; // Create the app packager. LinuxPlatformServices service(platform); LinuxAppPackager packager(service); // Read the application's "build.settings" file. bool wasSuccessful = packager.ReadBuildSettings(appPath); if (!wasSuccessful) { return; } int targetVersion = Rtt::TargetDevice::kLinux; const TargetDevice::Platform targetPlatform(TargetDevice::Platform::kLinuxPlatform); // Package build settings parameters. bool onlyGetPlugins = true; bool runAfterBuild = false; bool useWidgetResources = false; LinuxAppPackagerParams linuxBuilderParams( appName, NULL, identity, NULL, appPath, NULL, NULL, targetPlatform, targetVersion, Rtt::TargetDevice::kLinux, NULL, NULL, NULL, false, NULL, useWidgetResources, runAfterBuild, onlyGetPlugins); const char kBuildSettings[] = "build.settings"; Rtt::String buildSettingsPath; platform->PathForFile(kBuildSettings, Rtt::MPlatform::kResourceDir, Rtt::MPlatform::kTestFileExists, buildSettingsPath); linuxBuilderParams.SetBuildSettingsPath(buildSettingsPath.GetString()); int rc = packager.Build(&linuxBuilderParams, "/tmp/Solar2D"); } /// Gets a list of recent projects. void LinuxSimulatorView::GetRecentDocs(Rtt::LightPtrArray<Rtt::RecentProjectInfo>* listPointer) { if (listPointer) { listPointer->Clear(); vector<pair<string, string>> recentDocs; if (ReadRecentDocs(recentDocs)) { for (int i = 0; i < recentDocs.size(); i++) { // Create a recent project info object. RecentProjectInfo* infoPointer = new RecentProjectInfo(); if (!infoPointer) { continue; } const string& appName = recentDocs[i].first; const string& appPath = recentDocs[i].second; // Copy the project's folder name to the info object. String sTitle; sTitle.Append(appName.c_str()); infoPointer->formattedString = sTitle; // Copy the project's "main.lua" file path to the info object. String sPath; sPath.Append(appPath.c_str()); infoPointer->fullURLString = sPath; // Add the info object to the given collection. listPointer->Append(infoPointer); } } } } } // namespace Rtt
25.428058
122
0.668553
[ "object", "vector" ]
6ce4f512d285341b3d9f1f13cd9b66480bfca979
7,571
cpp
C++
hackathon/LXF/wrong_area_search/get_sub_terafly.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
hackathon/LXF/wrong_area_search/get_sub_terafly.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
hackathon/LXF/wrong_area_search/get_sub_terafly.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
#include "get_sub_terafly.h" #include "find_wrong_area.h" #define MHDIS(a,b) ( (fabs((a).x-(b).x)) + (fabs((a).y-(b).y)) + (fabs((a).z-(b).z)) ) #define NTDIS(a,b) (sqrt(((a).x-(b).x)*((a).x-(b).x)+((a).y-(b).y)*((a).y-(b).y)+((a).z-(b).z)*((a).z-(b).z))) bool get_sub_terafly(V3DPluginCallback2 &callback,QWidget *parent) { bool model=0; //1 for whole img,0 for sub img if(model) { QString inimg_file = "/home/penglab/mouseID_321237-17302/RES(54600x34412x9847)"; LandmarkList terafly_landmarks = callback.getLandmarkTeraFly(); QString pattern = "/home/penglab/Desktop/037_05082018.ano.swc"; NeuronTree nt; if (pattern.toUpper().endsWith(".SWC") ||pattern.toUpper().endsWith(".ESWC")) nt = readSWC_file(pattern); for(V3DLONG i=0;i<terafly_landmarks.size();i++) { LocationSimple t; t.x = terafly_landmarks[i].x; t.y = terafly_landmarks[i].y; t.z = terafly_landmarks[i].z; V3DLONG im_cropped_sz[4]; unsigned char * im_cropped = 0; V3DLONG pagesz; double l_x = 256; double l_y = 256; double l_z = 128; V3DLONG xb = t.x-l_x; V3DLONG xe = t.x+l_x-1; V3DLONG yb = t.y-l_y; V3DLONG ye = t.y+l_y-1; V3DLONG zb = t.z-l_z; V3DLONG ze = t.z+l_z-1; pagesz = (xe-xb+1)*(ye-yb+1)*(ze-zb+1); im_cropped_sz[0] = xe-xb+1; im_cropped_sz[1] = ye-yb+1; im_cropped_sz[2] = ze-zb+1; im_cropped_sz[3] = 1; try {im_cropped = new unsigned char [pagesz];} catch(...) {v3d_msg("cannot allocate memory for image_mip."); return false;} // cout<<"begin ==================="<<xb<<" "<<yb<<" "<<" "<<zb<<endl; // cout<<"end ==================="<<xe<<" "<<ye<<" "<<" "<<ze<<endl; // v3d_msg("test!"); QList<NeuronSWC> outswc; for(V3DLONG j=0;j<nt.listNeuron.size();j++) { NeuronSWC p; if(nt.listNeuron[j].x<xe&&nt.listNeuron[j].x>xb&&nt.listNeuron[j].y<ye&&nt.listNeuron[j].y>yb&&nt.listNeuron[j].z<ze&&nt.listNeuron[j].z>zb) { p.n = nt.listNeuron[j].n; p.x = nt.listNeuron[j].x-xb; p.y = nt.listNeuron[j].y-yb; p.z = nt.listNeuron[j].z-zb; p.type = nt.listNeuron[j].type; p.r = nt.listNeuron[j].r; p.pn = nt.listNeuron[j].pn; outswc.push_back(p); } } im_cropped = callback.getSubVolumeTeraFly(inimg_file.toStdString(),xb,xe+1, yb,ye+1,zb,ze+1); QString outimg_file,outswc_file; outimg_file = "/home/penglab/Desktop/data_for_hunanuniversity/img/test"+QString::number(i)+".tif"; outswc_file = "/home/penglab/Desktop/data_for_hunanuniversity/swc/test"+QString::number(i)+".swc"; export_list2file(outswc,outswc_file,outswc_file); simple_saveimage_wrapper(callback, outimg_file.toStdString().c_str(),(unsigned char *)im_cropped,im_cropped_sz,1); if(im_cropped) {delete []im_cropped; im_cropped = 0;} } } else { QString inimg_file = "/home/penglab/mouseID_321237-17302/RES(54600x34412x9847)"; //QString inimg_file = "/home/penglab/mouseID_321237-17302/RES(54600x34412x9847)"; QString pattern = "/home/penglab/Desktop/037_05082018.ano.swc"; //QString inimg_file = "/media/lxf/zhang/mouseID_321237-17302/RES(54600x34412x9847)"; //QString pattern = "/media/lxf/8213-B4FE/3.19/Data/finished_11/finished_11/005.swc"; //QString pattern2 = "/media/lxf/8213-B4FE/3.19/Data/auto_tracing/005_x_8584.04_y_8184.8_y_1458.26.swc"; NeuronTree nt,nt_p,bt,bt_p; if (pattern.toUpper().endsWith(".SWC") ||pattern.toUpper().endsWith(".ESWC")) nt = readSWC_file(pattern); //double prune_size =100; //prune_branch(nt_p,nt,prune_size); //nt_p = nt; int st = nt.listNeuron.size()/100; V3DLONG im_cropped_sz[4]; int i=0; while(i<19576) { NeuronSWC S; S.x = nt.listNeuron[i].x; S.y = nt.listNeuron[i].y; S.z = nt.listNeuron[i].z; double l_x = 256; double l_y = 256; double l_z = 128; V3DLONG xb = S.x-l_x; V3DLONG xe = S.x+l_x-1; V3DLONG yb = S.y-l_y; V3DLONG ye = S.y+l_y-1; V3DLONG zb = S.z-l_z; V3DLONG ze = S.z+l_z-1; unsigned char * im_cropped = 0; V3DLONG pagesz; pagesz = (xe-xb+1)*(ye-yb+1)*(ze-zb+1); im_cropped_sz[0] = xe-xb+1; im_cropped_sz[1] = ye-yb+1; im_cropped_sz[2] = ze-zb+1; im_cropped_sz[3] = 1; try {im_cropped = new unsigned char [pagesz];} catch(...) {v3d_msg("cannot allocate memory for image_mip."); return false;} // cout<<"begin ==================="<<xb<<" "<<yb<<" "<<" "<<zb<<endl; // cout<<"end ==================="<<xe<<" "<<ye<<" "<<" "<<ze<<endl; QList<NeuronSWC> outswc; for(V3DLONG j=0;j<nt.listNeuron.size();j++) { NeuronSWC p; if(nt.listNeuron[j].x<xe&&nt.listNeuron[j].x>xb&&nt.listNeuron[j].y<ye&&nt.listNeuron[j].y>yb&&nt.listNeuron[j].z<ze&&nt.listNeuron[j].z>zb) { p.n = nt.listNeuron[j].n; p.x = nt.listNeuron[j].x-xb; p.y = nt.listNeuron[j].y-yb; p.z = nt.listNeuron[j].z-zb; p.type = nt.listNeuron[j].type; p.r = nt.listNeuron[j].r; p.pn = nt.listNeuron[j].pn; outswc.push_back(p); } } im_cropped = callback.getSubVolumeTeraFly(inimg_file.toStdString(),xb,xe+1, yb,ye+1,zb,ze+1); QString outimg_file,outswc_file; outimg_file = "/home/penglab/Desktop/data_for_hunanuniversity/img/test"+QString::number(i)+".tif"; outswc_file = "/home/penglab/Desktop/data_for_hunanuniversity/swc/test"+QString::number(i)+".swc"; export_list2file(outswc,outswc_file,outswc_file); simple_saveimage_wrapper(callback, outimg_file.toStdString().c_str(),(unsigned char *)im_cropped,im_cropped_sz,1); if(im_cropped) {delete []im_cropped; im_cropped = 0;} QList<ImageMarker> listmarker,listmarker_o; ImageMarker u,u_o; u_o.x = S.x; u_o.y = S.y; u_o.z = S.z; u.x = S.x-xb; u.y = S.y-yb; u.z = S.z-zb; //v3d_msg("this is marker info"); cout<<"this is marker info"<<endl; cout<<u_o.x<<" "<<u_o.y<<" "<<u_o.z<<endl; cout<<u.x<<" "<<u.y<<" "<<u.z<<endl; listmarker.push_back(u); listmarker_o.push_back(u_o); writeMarker_file(QString(QString::number(i)+".marker"),listmarker); writeMarker_file(QString(QString::number(i)+"_o.marker"),listmarker_o); i=i+100; } } }
33.648889
156
0.507595
[ "model" ]
6ce774789a489c292cb546d50dc098304eda98aa
929
cpp
C++
Level-2/22. HashMap and Heap/Group Shifted String.cpp
anubhvshrma18/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
22
2021-06-02T04:25:55.000Z
2022-01-30T06:25:07.000Z
Level-2/22. HashMap and Heap/Group Shifted String.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
2
2021-10-17T19:26:10.000Z
2022-01-14T18:18:12.000Z
Level-2/22. HashMap and Heap/Group Shifted String.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
8
2021-07-21T09:55:15.000Z
2022-01-31T10:32:51.000Z
#include<bits/stdc++.h> using namespace std; vector<vector<string>> groupShiftedStrings(vector<string> &v){ map<string,vector<string>> map; for(auto s:v){ string temp=""; for(int i=1;i<s.length();i++){ int cc=s[i]-'0',pc = s[i-1]-'0'; int diff = (cc - pc + 26) % 26; temp += to_string(diff); temp += "@"; } map[temp].push_back(s); } vector<vector<string>> ans; for(auto a:map){ ans.push_back(a.second); } return ans; } void display(vector<vector<string>> &list) { for (auto i:list) { for (auto j:i) { cout << j << " "; } cout << endl; } } int main() { int N; cin >> N; vector<string> arr(N); for (int i = 0; i < N; i++) { cin >> arr[i]; } vector<vector<string>> ans = groupShiftedStrings(arr); for (auto i:ans) { sort(i.begin(),i.end()); } display(ans); }
18.58
62
0.499462
[ "vector" ]
6cf4020b3769e0570f9f99b23172145bee131229
22,260
cpp
C++
eval/evalExcess.cpp
ATSUnderground/peridetic
e7f86937080309aa8c0c27153de3f963c8f12ad8
[ "MIT" ]
10
2021-02-25T22:26:39.000Z
2022-02-25T17:53:31.000Z
eval/evalExcess.cpp
ATSUnderground/peridetic
e7f86937080309aa8c0c27153de3f963c8f12ad8
[ "MIT" ]
2
2021-02-26T08:04:18.000Z
2022-01-02T20:15:29.000Z
eval/evalExcess.cpp
ATSUnderground/peridetic
e7f86937080309aa8c0c27153de3f963c8f12ad8
[ "MIT" ]
3
2021-02-26T07:57:45.000Z
2022-02-25T17:53:36.000Z
// // // MIT License // // Copyright (c) 2020 Stellacore Corporation. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject // to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY // KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN // AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // #include "peridetic.h" #include "periLocal.h" #include "periSim.h" #include <algorithm> #include <fstream> #include <iostream> #include <utility> #include <vector> // NOTE: Concepts and variable names follow those of 'perideticMath' document. namespace { //! Compute constants associated with 'zeta' perturbation polynomials struct ZetaFSN { double const theFgkInv{ peri::sNan }; double const theS1k{ peri::sNan }; double const theN1k{ peri::sNan }; double const theN1SqPerMuSq{ peri::sNan }; ZetaFSN () = default; //! Compute useful parameters involved in various equations inline explicit ZetaFSN ( double const & xk , double const & grMag , double const & muSqk , double const & eta0 ) : theFgkInv{ .5 * grMag * muSqk } , theS1k{ 1. / (theFgkInv + eta0) } , theN1k{ theS1k * theFgkInv * xk } , theN1SqPerMuSq{ peri::sq(theN1k) / muSqk } { } //! Increment associated with coefficient 'Ck' inline double kN1MuS0 // ZetaFSN:: () const { return { theN1SqPerMuSq }; } //! Increment associated with coefficient 'Bk' inline double kN1MuS1 // ZetaFSN:: () const { return { theN1SqPerMuSq * theS1k }; } //! Increment associated with coefficient 'Ak' inline double kN1MuS2 // ZetaFSN:: () const { return { theN1SqPerMuSq * theS1k * theS1k }; } }; // ZetaPolyQuad::ZetaFSN //! Perturbation 'zeta'-polynomial (for testing: is NOT performant) struct ZetaPoly { peri::XYZ const theVecX{}; double const theEta0{}; double const theGrMag{}; std::array<double, 3u> const theMuSqs{}; std::array<ZetaFSN, 3u> const theFSNs{}; explicit ZetaPoly ( peri::XYZ const & xVec , double const & eta0 , double const & grMag , std::array<double, 3u> const & muSqs ) : theVecX{ xVec } , theEta0{ eta0 } , theGrMag{ grMag } , theMuSqs{ muSqs } , theFSNs { ZetaFSN(xVec[0], theGrMag, theMuSqs[0], theEta0) , ZetaFSN(xVec[1], theGrMag, theMuSqs[1], theEta0) , ZetaFSN(xVec[2], theGrMag, theMuSqs[2], theEta0) } { } // Constant Term //! Sum of (n1k/muk)^2 inline double sumN1MuS0 // ZetaPoly:: () const { return ( theFSNs[0].kN1MuS0() + theFSNs[1].kN1MuS0() + theFSNs[2].kN1MuS0() ); } // Linear Term //! Sum of (n1k/muk)^2*s1k inline double sumN1MuS1 // ZetaPoly:: () const { return ( theFSNs[0].kN1MuS1() + theFSNs[1].kN1MuS1() + theFSNs[2].kN1MuS1() ); } // Quadratic Term //! Sum of (n1k/muk)^2*s1k*s1k inline double sumN1MuS2 // ZetaPoly:: () const { return ( theFSNs[0].kN1MuS2() + theFSNs[1].kN1MuS2() + theFSNs[2].kN1MuS2() ); } }; // ZetaPoly //! Perturbation 'zeta'-polynomial expanded to only 1st order (~10^-8) struct ZetaPolyLinear : public ZetaPoly { //! Value construction (for underlying class) explicit ZetaPolyLinear ( peri::XYZ const & xVec , double const & eta0 , double const & grMag , std::array<double, 3u> const & muSqs ) : ZetaPoly(xVec, eta0, grMag, muSqs) { } //! Coefficients 'alpha,betat,gamma' for quadratic zeta polynomial inline std::array<double, 2u> coCBs // ZetaPolyLinear:: () const { return std::array<double, 2u> { (sumN1MuS0() - 1.) // constant , sumN1MuS1() // linear }; } //! Root computed exactly (linear transform) inline double rootExact // ZetaPolyLinear:: ( std::array<double, 2u> const & coCBs ) const { // shorthand notation double const & coC = coCBs[0]; double const & coB = coCBs[1]; // xArg is a relatively small quantity (used in series expansion) double const fracCoB{ coC / coB }; double const zetaExact { .5 * fracCoB }; return zetaExact; } }; // ZetaPolyLinear //! Perturbation 'zeta'-polynomial function to quadratic order (~10^-16) struct ZetaPolyQuad : public ZetaPoly { //! Value construction (for underlying class) explicit ZetaPolyQuad ( peri::XYZ const & xVec , double const & eta0 , double const & grMag , std::array<double, 3u> const & muSqs ) : ZetaPoly(xVec, eta0, grMag, muSqs) { } //! Coefficients 'alpha,betat,gamma' for quadratic zeta polynomial inline std::array<double, 3u> coCBAs // ZetaPolyQuad:: () const { return std::array<double, 3u> { (sumN1MuS0() - 1.) // constant , sumN1MuS1() // linear , 3.*sumN1MuS2() // quadratic }; } //! Root computed exactly (with square root function) inline double rootExact // ZetaPolyQuad:: ( std::array<double, 3u> const & coCBAs ) const { // shorthand notation double const & coC = coCBAs[0]; double const & coB = coCBAs[1]; double const & coA = coCBAs[2]; // xArg is a relatively small quantity (used in series expansion) double const fracCoB{ coC / coB }; double const xArg{ fracCoB * (coA / coB) }; double const radical{ std::sqrt(1. - xArg) }; double const zetaExact { (coB / coA) * (1. - radical) }; return zetaExact; } //! Root computed using linear expansion of sqrt() inline double rootApprox1st // ZetaPolyQuad:: ( std::array<double, 3u> const & coCBAs ) const { // Note: evaluation is same as ZetaPolyLinear::rootExact() // I.e. same computation steps in end result but // derived via different analytic process. // Repeated here to emphasize this point. // shorthand notation double const & coC = coCBAs[0]; double const & coB = coCBAs[1]; double const fracCoB{ coC / coB }; // first order approximation // precise to about 1.e-7 [m] (between +/- 1000[km]) double const zetaApx1 { (.5 * fracCoB) }; return zetaApx1; } //! Root computed using quadratic expansion of sqrt() inline double rootApprox2nd // ZetaPolyQuad:: ( std::array<double, 3u> const & coCBAs ) const { // shorthand notation double const & coC = coCBAs[0]; double const & coB = coCBAs[1]; double const & coA = coCBAs[2]; // xArg is a relatively small quantity (used in series expansion) double const fracCoB{ coC / coB }; double const xArg{ fracCoB * (coA / coB) }; // second order approximation // precise to about 1.e-8 [m] (between +/- 1000[km]) double const zetaApx2 { (.5 * fracCoB) * (1 + (1./4.)*xArg) }; return zetaApx2; } //! Root computed using cubic expansion of sqrt() inline double rootApprox3rd // ZetaPolyQuad:: ( std::array<double, 3u> const & coCBAs ) const { // NOTE: results insignificantly different from 2nd order // I.e. last term, "falls off of" 64-bit double computation // shorthand notation double const & coC = coCBAs[0]; double const & coB = coCBAs[1]; double const & coA = coCBAs[2]; // xArg is a relatively small quantity (used in series expansion) double const fracCoB{ coC / coB }; double const xArg{ fracCoB * (coA / coB) }; // third order approximation // precision UNmeasureable // second order approx is already in computation noise double const zetaApx3 { (.5 * fracCoB) * (1. + ((1./4.) + (1./8.)*xArg)*xArg) }; return zetaApx3; } }; // ZetaPolyQuad int evalExcess ( peri::sim::SampleSpec const & radSpec , peri::sim::SampleSpec const & parSpec , peri::EarthModel const & earth , std::ostream & ofsExcess ) { int errCount{ 0u }; peri::Shape const & shape = earth.theEllip.theShapeOrig; using namespace peri::sim; std::vector<peri::XYZ> const xyzs { meridianPlaneSamples(radSpec, parSpec) }; std::vector<double> extras{}; extras.reserve(xyzs.size()); for (peri::XYZ const & xyz : xyzs) { peri::XYZ const & xVec = xyz; peri::LPA const xLpa{ peri::lpaForXyz(xVec, earth) }; double const & eta = xLpa[2]; peri::XYZ const xDir{ peri::unit(xVec) }; peri::LPA const pLpa{ xLpa[0], xLpa[1], 0. }; peri::XYZ const pVec{ peri::xyzForLpa(pLpa, earth) }; double const rMag{ peri::ellip::radiusToward(xDir, shape) }; using peri::operator*; peri::XYZ const rVec{ rMag * xDir }; using peri::operator-; peri::XYZ const xrVec{ xVec - rVec }; peri::XYZ const xpVec{ xVec - pVec }; double const xrMag{ peri::magnitude(xrVec) }; double const xpMag{ peri::magnitude(xpVec) }; double const extra{ xrMag - xpMag }; extras.emplace_back(extra); // gradients peri::XYZ const gpVec{ shape.gradientAt(pVec) }; double const gpMag{ peri::magnitude(gpVec) }; peri::XYZ const grVec{ shape.gradientAt(rVec) }; double const grMag{ peri::magnitude(grVec) }; double const gRatio{ grMag / gpMag }; double const rEps{ gRatio - 1. }; // peri::XYZ const gDifVec{ grVec - gpVec }; // double const gDifMag{ peri::magnitude(gDifVec) }; // compute deltaEta, deltaSigma double const delEta{ xrMag - xpMag }; double const dEtaPerR{ delEta / rMag }; // info for analysis ofsExcess // << " xVec: " << peri::xyz::infoString(xVec) // << " xLpa: " << peri::lpa::infoString(xLpa) // << " Lon: " << peri::string::fixedAngular(xLpa[0]) << " Par: " << peri::string::fixedAngular(xLpa[1]) << " Alt: " << peri::string::allDigits(eta) // << " " << peri::string::fixedLinear(xrMag, "xrMag") // << " " << peri::string::fixedLinear(xpMag, "xpMag") << " " << peri::string::fixedLinear(extra, "extra") << " " << peri::string::allDigits(rEps, "rEps") << " " << peri::string::allDigits(delEta, "delEta") << " " << peri::string::allDigits(dEtaPerR, "dEtaPerR") << std::endl; } if (! extras.empty()) { std::sort(extras.begin(), extras.end()); using peri::string::fixedLinear; ofsExcess << "# minExcess: " << fixedLinear(extras.front()) << '\n'; ofsExcess << "# maxExcess: " << fixedLinear(extras.back()) << '\n'; } // needs work to define what is a reasonable test // ++errCount; return errCount; } //! Formula to evaluate vector, p, from 'zeta' root peri::XYZ pVecFor ( peri::XYZ const & xVec , double const & zeta , double const & eta0 , double const & grMag , peri::Shape const & shape ) { std::array<double, 3u> const & muSqs = shape.theMuSqs; // compute point on ellipse double const correction{ 2. * (zeta + eta0) / grMag }; peri::XYZ const pVec { xVec[0] / (1. + (correction/muSqs[0])) , xVec[1] / (1. + (correction/muSqs[1])) , xVec[2] / (1. + (correction/muSqs[2])) }; return pVec; } //! Compute point on ellipsoid, p, using perturbation expansion peri::XYZ pVecViaExcess ( peri::XYZ const & xVec , peri::EarthModel const & earth ) { using namespace peri; Shape const & shape = earth.theEllip.theShapeOrig; // radial point on ellipsoid double const rho{ peri::ellip::radiusToward(xVec, shape) }; XYZ const rVec{ rho * unit(xVec) }; // gradient at radial point XYZ const grVec{ shape.gradientAt(rVec) }; double const grMag{ magnitude(grVec) }; // radial pseudo-altitude double const xMag{ magnitude(xVec) }; double const rMag{ magnitude(rVec) }; double const eta0{ xMag - rMag }; // form and solve 'zeta' linear ZetaPolyLinear const zpoly1{ xVec, eta0, grMag, shape.theMuSqs }; std::array<double, 2u> const coCBs{ zpoly1.coCBs() }; double const zetaLineExact{ zpoly1.rootExact(coCBs) }; // form and solve 'zeta' quadratic ZetaPolyQuad const zpoly2{ xVec, eta0, grMag, shape.theMuSqs }; std::array<double, 3u> const coCBAs{ zpoly2.coCBAs() }; // double const zetaQuadExact{ zpoly2.rootExact(coCBAs) }; double const zetaQuadApx1{ zpoly2.rootApprox1st(coCBAs) }; double const zetaQuadApx2{ zpoly2.rootApprox2nd(coCBAs) }; // double const zetaQuadApx3{ zpoly2.rootApprox3rd(coCBAs) }; double const zeta{ zetaQuadApx2 }; // 1st order approx to quadratic poly == exact soln to linear poly double const difOrder1{ zetaLineExact - zetaQuadApx1 }; if (! (0. == difOrder1)) { std::cerr << "Implementation error (LineExact != QuadApprox1st)" << std::endl; std::cerr << peri::string::allDigits(difOrder1, "difOrder1") << std::endl; exit(8); } // compute point on ellipse peri::XYZ const pVec{ pVecFor(xVec, zeta, eta0, grMag, shape) }; return pVec; } //! Evaluate math equations for ellipsoidal excess at this point int checkXYZ ( peri::XYZ const & xVecExp , peri::EarthModel const & earth , std::ofstream & ostrm ) { int errCount{ 0u }; using namespace peri; // compute pLocation based on perturbation expansion XYZ const pVecGot{ pVecViaExcess(xVecExp, earth) }; // quantities for checking values LPA const xLpaExp{ lpaForXyz(xVecExp, earth) }; XYZ const pLpaExp{ xLpaExp[0], xLpaExp[1], 0. }; XYZ const pVecExp{ xyzForLpa(pLpaExp, earth) }; // error amount XYZ const pVecDif{ pVecGot - pVecExp }; double const pMagDif{ magnitude(pVecDif) }; // check that precision of computation double const pMagExp{ magnitude(pVecExp) }; double const pMagTol{ pMagExp * 1.e-15 }; if (! (pMagDif < pMagTol)) { std::cerr << "FAILURE of precision test on pMagDif" << '\n'; std::cerr << xyz::infoString(pVecExp, "pVecExp") << '\n'; std::cerr << xyz::infoString(pVecGot, "pVecGot") << '\n'; std::cerr << string::allDigits(pVecDif, "pVecDif") << '\n'; std::cerr << string::allDigits(pMagDif, "pMagDif") << '\n'; std::cerr << string::allDigits(pMagTol, "pMagTol") << '\n'; ++errCount; } // save evaluation data ostrm << lpa::infoString(xLpaExp, "xLpaExp") << " " << xyz::infoString(pVecDif, "pVecDif") << " " << string::allDigits(pMagDif, "pMagDif") << '\n'; return errCount; } //! Check equations on sampling of points int evalVecP ( peri::sim::SampleSpec const & radSpec , peri::sim::SampleSpec const & parSpec , peri::EarthModel const & earth , std::ofstream & ofsDifPVec ) { int errCount{ 0u }; using namespace peri::sim; std::vector<peri::XYZ> const xyzs { meridianPlaneSamples(radSpec, parSpec) }; for (peri::XYZ const & xyz : xyzs) { errCount += checkXYZ(xyz, earth, ofsDifPVec); } return errCount; } //! Point on surface of ellipsoid shape in direction of xVec peri::XYZ rVecToward ( peri::XYZ const & xVec , peri::Shape const & shape ) { // radial point on ellipsoid double const rho{ peri::ellip::radiusToward(xVec, shape) }; using peri::operator*; peri::XYZ const rVec{ rho * peri::unit(xVec) }; return rVec; } //! Gradient at point rVec (via rVecToward()) associated with xVec double grMagFor ( peri::XYZ const & xVec , peri::Shape const & shape ) { // gradient at radial point peri::XYZ const grVec{ shape.gradientAt(rVecToward(xVec, shape)) }; double const grMag{ peri::magnitude(grVec) }; return grMag; } //! Radial altitude (NOT geodetic) distance between rVec and xVec double eta0For ( peri::XYZ const & xVec , peri::Shape const & shape ) { // radial point on ellipsoid peri::XYZ const rVec{ rVecToward(xVec, shape) }; // radial pseudo-altitude double const xMag{ peri::magnitude(xVec) }; double const rMag{ peri::magnitude(rVec) }; double const eta0{ xMag - rMag }; return eta0; } //! Values for pVec computed via various techniques struct PVecSoln { peri::XYZ theExact{}; // "exact" solution (from periDetail) peri::XYZ theApx1{}; // first order zetaQuadratic approximation peri::XYZ theApx2{}; // second order zetaQuadratic approximation peri::XYZ theApx3{}; // third order zetaQuadratic approximation //! Compute pVec values from zeta polynomial static PVecSoln from ( peri::XYZ const & xVec , peri::XYZ const & pVecExp , peri::Shape const & shape ) { double const eta0{ eta0For(xVec, shape) }; double const grMag{ grMagFor(xVec, shape) }; // form and solve 'zeta' quadratic ZetaPolyQuad const zpoly2{ xVec, eta0, grMag, shape.theMuSqs }; std::array<double, 3u> const coCBAs{ zpoly2.coCBAs() }; double const zetaQuadApx1{ zpoly2.rootApprox1st(coCBAs) }; double const zetaQuadApx2{ zpoly2.rootApprox2nd(coCBAs) }; double const zetaQuadApx3{ zpoly2.rootApprox3rd(coCBAs) }; // computed POE with different approximation orders peri::XYZ const pVecApx1 { pVecFor(xVec, zetaQuadApx1, eta0, grMag, shape) }; peri::XYZ const pVecApx2 { pVecFor(xVec, zetaQuadApx2, eta0, grMag, shape) }; peri::XYZ const pVecApx3 { pVecFor(xVec, zetaQuadApx3, eta0, grMag, shape) }; return { pVecExp, pVecApx1, pVecApx2, pVecApx3 }; } //! Error in 1st order approximation double diffApx1 () const { using peri::operator-; return peri::magnitude(theApx1 - theExact); } //! Error in 2nd order approximation double diffApx2 () const { using peri::operator-; return peri::magnitude(theApx2 - theExact); } //! Error in 3rd order approximation double diffApx3 () const { using peri::operator-; return peri::magnitude(theApx3 - theExact); } }; // PVecSoln //! Evaluate pVec locations with various order zeta polynomial expressions struct ZetaSoln { peri::XYZ const theXVec{}; PVecSoln const thePVecs{}; explicit ZetaSoln ( peri::XYZ const & xVec , peri::XYZ const & pVecExp , peri::Shape const & shape ) : theXVec{ xVec } , thePVecs{ PVecSoln::from(theXVec, pVecExp, shape) } { } }; // ZetaSoln //! Location of evaluation sample with descriptive values struct LocSamp { //! sample location as vector peri::XYZ const theVecX{}; //! azimuth/elevation angles (geocentric) std::pair<double, double> const theAzimElev{}; //! magnitude of xVec (geocentric) double const theMag{}; explicit LocSamp ( peri::XYZ const & xVec ) : theVecX{ xVec } , theAzimElev{ peri::anglesLonParOf(xVec) } , theMag{ peri::magnitude(xVec) } { } inline double const & azim () const { return theAzimElev.first; } inline double const & elev () const { return theAzimElev.second; } }; // LocSamp //! Evaluate pVec errors at specified sampling locations std::vector<std::pair<LocSamp, PVecSoln> > sampleSolnsFor ( peri::sim::SampleSpec const & radSpec , peri::sim::SampleSpec const & parSpec , peri::EarthModel const & earth ) { std::vector<std::pair<LocSamp, PVecSoln> > locSolns{}; std::vector<peri::XYZ> const xVecs { peri::sim::meridianPlaneSamples(radSpec, parSpec) }; for (peri::XYZ const & xVec : xVecs) { // expected POE peri::XYZ const pVecExp{ earth.nearEllipsoidPointFor(xVec) }; // evaluate pVec (and related) using 'zeta' polynomial ZetaSoln const zSoln(xVec, pVecExp, earth.theEllip.theShapeOrig); PVecSoln const & pSoln = zSoln.thePVecs; // put into return collection locSolns.emplace_back(std::pair<LocSamp, PVecSoln>{ xVec, pSoln }); } return locSolns; } //! Evaluate pVec errors at specified sampling locations void saveZetaDiffs ( std::vector<std::pair<LocSamp, PVecSoln> > const & locSolns , std::ostream & ofsZetaDiff ) { for (std::pair<LocSamp, PVecSoln> const & locSoln : locSolns) { LocSamp const & locSamp = locSoln.first; PVecSoln const & pSoln = locSoln.second; ofsZetaDiff << peri::string::allDigits(locSamp.elev(), "theta") << " " << peri::string::allDigits(locSamp.theMag, "xMag") << " " << peri::string::allDigits(pSoln.diffApx1(), "difMagApx1") << " " << peri::string::allDigits(pSoln.diffApx2(), "difMagApx2") << " " << peri::string::allDigits(pSoln.diffApx3(), "difMagApx3") // << " " // << peri::string::allDigits(locSamp.theVecX, "xVec") << '\n'; } } } // [annon] //! TODO int main () { int errCount{ 0 }; // optionally save data to files for analysis std::ofstream ofsExcess ( "/dev/null" // "/dev/stdout" ); std::ofstream ofsDifPVec ( "/dev/null" // "pvecDiff.dat" ); std::ofstream ofsZeta ( // "/dev/null" "zetaDiff.dat" ); constexpr std::size_t numRad{ 32u + 1u }; constexpr std::size_t numPar{ 256u + 1u }; // odd number hits at 45-deg Lat #define UseNorm // un-define to stress-test formulae (e.g. for debugging) #if defined(UseNorm) peri::Shape const shape(peri::shape::sWGS84.normalizedShape()); constexpr double altLo{ -(100./6370.) }; constexpr double altHi{ (100./6370.) }; #else peri::Shape const shape(peri::shape::sWGS84); constexpr double altLo{ -100. * 1.e+3 }; constexpr double altHi{ 100. * 1.e+3 }; #endif peri::EarthModel const earth(shape); peri::Ellipsoid const & ellip = earth.theEllip; double const radEarth{ ellip.lambdaOrig() }; double const radMin{ radEarth + altLo }; double const radMax{ radEarth + altHi }; using Range = std::pair<double, double>; double const halfPi{ .5 * peri::pi() }; peri::sim::SampleSpec const radSpec{ numRad, Range{ radMin, radMax } }; peri::sim::SampleSpec const parSpec{ numPar, Range{ -halfPi, halfPi } }; errCount += evalExcess(radSpec, parSpec, earth, ofsExcess); errCount += evalVecP(radSpec, parSpec, earth, ofsDifPVec); std::vector<std::pair<LocSamp, PVecSoln> > const locSolns { sampleSolnsFor(radSpec, parSpec, earth) }; saveZetaDiffs(locSolns, ofsZeta); return errCount; }
26.065574
78
0.650898
[ "shape", "vector", "transform" ]
6cfa2e8b067e2f897bfd65b8f95c5be14734337f
873
cpp
C++
CSES Problems/IntroductoryProblems/CreatingStringsI.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
2
2020-09-10T15:48:02.000Z
2020-09-12T00:05:35.000Z
CSES Problems/IntroductoryProblems/CreatingStringsI.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
null
null
null
CSES Problems/IntroductoryProblems/CreatingStringsI.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
null
null
null
/* Author: Davi Augusto Neves Leite Date: 15/09/2020 */ #include <bits/stdc++.h> #define MODULO 1000000007 typedef long long ll; using namespace std; int main(){ ios::sync_with_stdio(0); cin.tie(0); /*freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);*/ string digits; cin >> digits; sort(digits.begin(), digits.end()); //Vetor contendo todas as possibilidades e contador final vector<string> possibilities; ll countPossibilities = 0; //Todas as possibilidades do{ possibilities.push_back(digits); countPossibilities++; }while(next_permutation(digits.begin(), digits.end())); cout << countPossibilities << endl; for(ll i = 0; i < possibilities.size(); i++){ cout << possibilities[i] << endl; } return 0; }
20.785714
62
0.593356
[ "vector" ]
2f5a74d5ff177b0e3bd7da0995c005a31a9c822b
3,189
cpp
C++
MeshIO/FEHyperSurfImport.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
27
2020-06-25T06:34:52.000Z
2022-03-11T08:58:57.000Z
MeshIO/FEHyperSurfImport.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
42
2020-06-15T18:40:57.000Z
2022-03-24T05:38:54.000Z
MeshIO/FEHyperSurfImport.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
12
2020-06-27T13:58:57.000Z
2022-03-24T05:39:10.000Z
/*This file is part of the FEBio Studio source code and is licensed under the MIT license listed below. See Copyright-FEBio-Studio.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #include "FEHyperSurfImport.h" #include <GeomLib/GSurfaceMeshObject.h> #include <MeshTools/GModel.h> FEHyperSurfImport::FEHyperSurfImport(FEProject& prj) : FEFileImport(prj) { } FEHyperSurfImport::~FEHyperSurfImport(void) { } bool FEHyperSurfImport::Load(const char* szfile) { FEModel& fem = m_prj.GetFEModel(); // open the file if (Open(szfile, "rt") == false) return errf("Failed opening file %s", szfile); int i; char szline[256]; // find the vertices char* ch; do { ch = fgets(szline, 255, m_fp); if (ch == 0) return errf("Error while reading file"); if (strncmp(szline, "Vertices", 8) == 0) break; } while (true); int nodes = 0; sscanf(szline+8, "%d", &nodes); FESurfaceMesh* pm = new FESurfaceMesh(); pm->Create(nodes, 0, 0); // read the nodes for (i=0; i<nodes; ++i) { ch = fgets(szline, 255, m_fp); if (ch == 0) { delete pm; Close(); return false; } FENode& node = pm->Node(i); sscanf(szline, "%lg%lg%lg", &node.r.x, &node.r.y, &node.r.z); } // find the triangles do { ch = fgets(szline, 255, m_fp); if (ch == 0) { delete pm; Close(); return false; } if (strncmp(szline, "Triangles", 9) == 0) break; } while (true); int elems = 0; sscanf(szline+9, "%d", &elems); pm->Create(0, 0, elems); // read the elements int ne[3]; for (i=0; i<elems; ++i) { ch = fgets(szline, 255, m_fp); if (ch == 0) { delete pm; Close(); return false; } FEFace& face = pm->Face(i); face.SetType(FE_FACE_TRI3); sscanf(szline, "%d%d%d", &ne[0], &ne[1], &ne[2]); face.m_gid = 0; face.n[0] = ne[0] - 1; face.n[1] = ne[1] - 1; face.n[2] = ne[2] - 1; face.n[3] = ne[2] - 1; } // close the file Close(); // create a new object pm->RebuildMesh(); GObject* po = new GSurfaceMeshObject(pm); // add the object to the model char szname[256]; FileTitle(szname); po->SetName(szname); fem.GetModel().AddObject(po); return true; }
26.355372
89
0.688931
[ "object", "model" ]
2f5c9651d586308baba14deb3b3a93ed2349b80f
624
hxx
C++
src/cpp/include/seq/seq.hxx
sguzman/Pretty-Print-Library
555780f94a0a5d04c84f3c254b500f8944826d70
[ "MIT" ]
1
2018-06-20T17:47:15.000Z
2018-06-20T17:47:15.000Z
src/cpp/include/seq/seq.hxx
sguzman/Pretty-Print-Library
555780f94a0a5d04c84f3c254b500f8944826d70
[ "MIT" ]
null
null
null
src/cpp/include/seq/seq.hxx
sguzman/Pretty-Print-Library
555780f94a0a5d04c84f3c254b500f8944826d70
[ "MIT" ]
null
null
null
#pragma once #include <array> // Some util definitions #include "../util/def.hxx" // Main implementation of sequence printing #include "../seq/impl/seq-impl.hxx" // Impl for array #include "../seq/array/array.hxx" // Impl for deque #include "../seq/deque/deque.hxx" // Impl for forward_list #include "../seq/forward_list/forward.hxx" // Impl for list #include "../seq/list/list.hxx" // Impl for raw C array #include "../seq/raw/raw.hxx" // Impl for vector #include "../seq/vector/vector.hxx" template <typename T, template <class> typename B> static inline ostream& operator<<(ostream&,conref<B<T>>) noexcept = delete;
24
75
0.703526
[ "vector" ]
2f5dfc8d79a18f3cd364cfe7a439f9bd49a27e05
341
cpp
C++
1295. Find Numbers with Even Number of Digits.cpp
MadanParth786/LeetcodeSolutions_PracticeQuestions
8a9c1eb88a6d5214abdb2becf2115a51e317a5c4
[ "MIT" ]
1
2022-01-19T14:25:36.000Z
2022-01-19T14:25:36.000Z
1295. Find Numbers with Even Number of Digits.cpp
MadanParth786/LeetcodeSolutions_PracticeQuestions
8a9c1eb88a6d5214abdb2becf2115a51e317a5c4
[ "MIT" ]
null
null
null
1295. Find Numbers with Even Number of Digits.cpp
MadanParth786/LeetcodeSolutions_PracticeQuestions
8a9c1eb88a6d5214abdb2becf2115a51e317a5c4
[ "MIT" ]
null
null
null
class Solution { public: int FindNumbers(vector<int>& nums) { int n=nums.size(); int count=0; for(int i=0;i<n;i++){ if((9<=nums[i] and nums[i]<=99) or (1000<=nums[i] and nums[i]<=9999) or (nums[i]==10000)){ count+=1; } } return count; } };
24.357143
103
0.434018
[ "vector" ]
2f6adb85c62b0fcb28a2435b03fece2cdc8f47e9
24,932
cc
C++
qtchat/src/0.9.7/core/chatter.cc
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
qtchat/src/0.9.7/core/chatter.cc
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
qtchat/src/0.9.7/core/chatter.cc
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
#include <fstream.h> #include <iomanip.h> #include <list> // STL linked list #include <string> // STL string class #include <stdio.h> #include <stdlib.h> #include <qfontmetrics.h> #include "chatter.h" #include "net.h" typedef list<string> StringList; class ChatterRef : public StateObject { public: // Constructors / Destructors ChatterRef(QString _name, bool _highlighted=false, bool _ignored=false); ChatterRef(const char *_name, bool _highlighted=false, bool _ignored=false); virtual ~ChatterRef(); static int numChatters() { return num_chatters; } QString getName() const { return QString(name); } QString getiName() const { return QString(name).lower(); } bool isMe() const { return is_me; } void setMe(bool b) { is_me = b; if(b) friend_level = (FriendLevel)((int)FRIENDLEVEL_END - 1); } bool isConnected() const; // check if chatter is me and connected bool isIgnored() const { return ignored; } bool isHighlighted() const { return highlighted; } void setIgnored(bool b) { ignored = b; if(b) addToIgnoredList(name); else removeFromIgnoredList(name); } void addToIgnoredList(const char *name) {} void removeFromIgnoredList(const char *name) {} void setHighlighted(bool b) { highlighted = b; } void setHighlightColor(QColor c) { highlight_color=c; } QColor getHighlightColor() { return highlight_color; } int incRefCount() { return ++refs; } int decRefCount() { return --refs; } FriendLevel getFriendLevel() const { return friend_level; } void setFriendLevel(FriendLevel fl) { friend_level = fl; } void setFriendLevel(char fl) { switch(fl) { case 'F': friend_level = FRIEND; break; case 'T': friend_level = TRUSTED_FRIEND; break; case 'G': friend_level = GOD; break; case 'S': default: friend_level = STRANGER; break; } } ChatEntryType getLastEventType() const { return last_event_type; } void setLastEventType(ChatEntryType t) { last_event_type = t; } float getEventsPerSec() const { return events_per_sec; } float getEventsPerSecPerSec() const { return events_per_sec_per_sec; } float getLastEventsPerSec() const { return last_events_per_sec; // last value returned by getE.P.S.() } void doEvent(QString txt); // register event done by chatter & update counters QString getLastLine() const { // last line posted by chatter return last_line; } int numPMEvents() const { // number of PMs emitted by Chatter return num_pm_events; } void incNumPMEvents() { // increment number of PMs emitted by Chatter num_pm_events++; } int numCapsEvents() const { // num. uppercase posts emitted by Chatter return num_caps_events; } void incNumCapsEvents() { // inc. num. uppercase posts emitted by Chatter num_caps_events++; } void setEventQueueSize(int size); int getEventQueueSize() const { return queue_size; } int numEvents() const { // number of events recorded in circular queue return num_events; } int numDuplicateEvents() const { // number of duplicates of most recent event return num_duplicates; } int getNumTotalEvents() const { // total number of events posted by Chatter return num_total_events; } void saveState(ostream &s) const; void restoreState(istream &s); // static int createFromStream(istream &s); static int createFromStream(istream &is, int version); private: int refs; // number of references to this object in existence static int num_chatters; // total number of ChatterRef objects in existence FriendLevel friend_level; // level of trust in chatter char *name; // chatter's name as known to Yahoo bool is_me; // this chatter is 'me' bool highlighted; // chatter is highlighted bool ignored; // chatter is ignored static QTime elapsed_time; // 24 hr elapsed time int num_pm_events; // number of PMs emitted by Chatter int num_caps_events; // number of uppercase posts emitted by Chatter ChatEntryType last_event_type; // last event issued by event int event_time[MAX_QUEUE_SIZE]; // circular queue of event times int event_time_index; // current index into queue, next time goes here int num_events; // number of events in queue int queue_size; // number of events queue can hold (max MAX_QUEUE_SIZE) float events_per_sec; // no. of events registered per second float last_events_per_sec; // last value of above float events_per_sec_per_sec; // derivative of above int num_total_events; // total number of events by chatter QColor highlight_color; // duh QString last_line; // last line posted by chatter int num_duplicates; // number of identical last posts void init(const char *_name); // used by constructors static StringList ignored_list; // list of people on ignore }; const char *FriendLevelString[] = { // string rep. of FriendLevel "Stranger", "Friend", "Trusted Friend", "God", 0 }; int toInt(FriendLevel fl) { // function to get int representation of FriendLevel return (int)(fl - STRANGER); } FriendLevel toFriendLevel(int i) { // companion to toInt(FriendLevel) return (FriendLevel)(i+(int)STRANGER); } const char *toString(FriendLevel fl) { // function to get string rep. of FriendLevel if(fl >= STRANGER && fl < FRIENDLEVEL_END) return FriendLevelString[fl-STRANGER]; else return FriendLevelString[0]; // return STRANGER by default } FriendLevel toFriendLevel(const char *str) { // companion to toString(FriendLevel) for(int i=0; FriendLevelString[i]; i++) if(strcasecmp(str, FriendLevelString[i])==0) return toFriendLevel(i); return STRANGER; } FriendLevel operator++(FriendLevel &fl) { FriendLevel tmp = fl; fl = (FriendLevel)(((int)fl)+1); return tmp; } // Init static variables StringList ChatterRef::ignored_list; ChatterRef *Chatter::chatters[MAX_NUM_CHATTERS] = {0}; int ChatterRef::num_chatters = 0; // total number of ChatterRef objects in existance QTime ChatterRef::elapsed_time; // init elapsed timer to 0:00:00 bool ChatterRef::isConnected() const { // check if chatter is me and connected if(!isMe()) return false; // non-me's can't be connected return YahooNetConnection::getMeConnection(Chatter(name)) != 0; } ChatterRef::ChatterRef(QString _name, bool _highlighted, bool _ignored) : refs(0),highlighted(_highlighted),ignored(_ignored), highlight_color(Qt::yellow), last_line() { init(_name); } ChatterRef::ChatterRef(const char *_name, bool _highlighted, bool _ignored) : refs(0),highlighted(_highlighted),ignored(_ignored), highlight_color(Qt::yellow), last_line() { init(_name); } void ChatterRef::init(const char *_name) { if(::debuglevel & DEBUGLEVEL_CONSTRUCTOR) cerr << "ChatterRef(\"" << _name << "\") constructor called." << endl; if(_name) { name = new char[strlen(_name)+1]; strcpy(name, _name); } else name = 0; friend_level = STRANGER; is_me = false; num_pm_events = 0; num_caps_events = 0; for(int i=0; i<MAX_QUEUE_SIZE; i++) event_time[i] = 0; last_event_type = CET_NULL; event_time_index = 0; num_events = 0; queue_size = 4; events_per_sec = 0.0; last_events_per_sec = 0.0; events_per_sec_per_sec = 0.0; if(elapsed_time.isNull()) { elapsed_time.setHMS(0, 0, 0, 1); elapsed_time.start(); } num_duplicates = 0; num_chatters++; if(ignored) addToIgnoredList(name); } ChatterRef::~ChatterRef() { if(debuglevel & DEBUGLEVEL_DESTRUCTOR) cerr << "ChatterRef(\"" << name << "\") destructor called." << endl; if(name) { removeFromIgnoredList(name); delete name; } num_chatters--; } void addToIgnoreList(const char *name) { } void removeFromIgnoreList(const char *name) { } void ChatterRef::doEvent(QString txt) { // first determine duplicate events if(txt == last_line) { // this also catches null strings though... num_duplicates++; } else { num_duplicates = 1; last_line = txt; } // now calculate rate/acceleration of chatter events if(queue_size) { int current_event_time = elapsed_time.elapsed(); // time of current event (ms) event_time[event_time_index] = current_event_time; int prev_event_time_index = (event_time_index-1) % queue_size; event_time_index = (event_time_index+1) % queue_size; // adjust index to range of queue if(num_events < queue_size) num_events++; int first_event_time = // time of first event (ms) event_time[(queue_size + (event_time_index-num_events)) % queue_size]; last_events_per_sec = events_per_sec; if(current_event_time != first_event_time) events_per_sec = (float)num_events*1000.0/(float)(current_event_time - first_event_time); else events_per_sec = 0.0; if(current_event_time != event_time[prev_event_time_index]) events_per_sec_per_sec = (events_per_sec - last_events_per_sec)* 1000.0/(current_event_time-event_time[prev_event_time_index]); else events_per_sec_per_sec = 0.0; } else events_per_sec = 0; } void ChatterRef::setEventQueueSize(int size) { if(size < queue_size) { } } void ChatterRef::saveState(ostream &s) const { if(name) { //**** DISABLED Version 1***** // s << "\tName=\"" << name << '\"' << endl; // s << "\tFriendLevel=\"" << toString(friend_level) << '\"' << endl; // s << "\tHighlighted=\"" << (highlighted ? "true" : "false") << '\"' << endl; // s << "\tIgnored=\"" << (ignored ? "true" : "false") << '\"' << endl; // s << "\tHighlightColor=\"" << setw(6) << setfill('0') << hex << highlight_color.rgb() << '\"' << endl << endl; //***** END DISABLED ***** // Version 2 s << name << ends; s << toString(friend_level)[0]; s << (char)highlighted; s << (char)ignored; s << (char)highlight_color.red() << (char)highlight_color.green() << (char)highlight_color.blue(); // End Version 2 } } int readTag(const char *tag, istream &is, char *buf, int len, unsigned int version) { // Get tag into buffer 'buf' of length 'len'. // Tag is formatted: *tag*"buf" // Calling readTag("Name", buf, is, len) will read ` Name="Joe" '. // check args if(!tag || !buf || !is || len <=0) { cerr << "readTag(): Bad argument(s)" << endl; return -1; } switch(version) { case 1: (is >> ws).getline(buf, len, '\"'); // read line up to first quote if(!is || strstr(buf, tag) == 0) { // look for tag cerr << "readTag(): Unable to find tag '" << tag << "' in '" << buf << "'." << endl; return -1; // error... no tag found. } is.getline(buf, len, '\"'); // read Name // is.getline(buf, len) >> ws; // read Name if(!is) { cerr << "readTag(): Unable to read value of tag '" << tag << "'." << endl; return -1; } // buf now has tag value in it break; case 2: // new version of chatters.ini switch(tag[0]) { case 'N': // "Name" tag is.getline(buf, len, '\0'); break; case 'I': // "Ignored" tag case 'H': // "Highlighted" tag is.read(buf, 1); break; case 'C': // "Highlight Color" tag is.read(buf, 3); break; case 'F': // "FriendLevel" tag is.read(buf, 1); break; break; } default: break; } return 0; } int ChatterRef::createFromStream(istream &is, int version) { char buf[1024]; unsigned long color = 0; ChatterRef *c = 0; // Get name if(readTag("Name", is, buf, 1024, version)) { cerr << "ChatterRef::createFromStream(): Error parsing 'Name' tag'" << endl; return -1; } int i; // gen. purpose int // see if this chatter already exists // this is O(n^2), so we'll specify that all chatters in file will be unique // i=findChatter(buf); // if(i >= 0) { // found one.. we'll set the properties of existing chatter // c = Chatter::chatters[i]; // } else { // doesn't already exist... make a new one c = new ChatterRef((const char *)buf); CHECK_PTR(c); i=Chatter::findFirstSpace(); if(i >=0) { // we have an empty slot... stick it in!!! Chatter::chatters[i] = c; num_chatters++; } else { // doh! cerr << "ChatterRef::createFromStream(): Unable to insert new chatter." << endl; delete c; Chatter::chatters[i] = 0; return -1; } // } // get FriendLevel if(readTag("FriendLevel", is, buf, 1024, version)) { cerr << "ChatterRef::createFromStream(): Error parsing 'FriendLevel' tag'" << endl; return -1; } if(version == 1) c->setFriendLevel(toFriendLevel(buf)); else if(version == 2) c->setFriendLevel(buf[0]); // get Highlighted if(readTag("Highlighted", is, buf, 1024, version)) { cerr << "ChatterRef::createFromStream(): Error parsing 'Highlighted' tag'" << endl; return -1; } if(version == 1) c->setHighlighted(strcasecmp(buf, "true")==0 ? true : false); else if(version == 2) c->setHighlighted(buf[0]); // get Ignored if(readTag("Ignored", is, buf, 1024, version)) { cerr << "ChatterRef::createFromStream(): Error parsing 'Ignored' tag'" << endl; return -1; } if(version == 1) c->setIgnored(strcasecmp(buf, "true")==0 ? true : false); else if(version == 2) c->setIgnored(buf[0]); // get HighlightColor if(version == 1) { if(readTag("HighlightColor", is, buf, 1024, version)) { cerr << "ChatterRef::createFromStream(): Error parsing 'HighlightColor' tag'" << endl; return -1; } sscanf(buf, "%lx", &color); c->setHighlightColor(QColor(color)); } else if(version == 2) { if(readTag("C", is, buf, 1024, version)) { cerr << "ChatterRef::createFromStream(): Error parsing 'HighlightColor' tag'" << endl; return -1; } c->setHighlightColor(QColor((unsigned int)buf[0] & 0xff, (unsigned int)buf[1] & 0xff, (unsigned int)buf[2] & 0xff)); } return 0; } void ChatterRef::restoreState(istream &is) { return; } Chatter::Chatter(QString name) { if(::debuglevel & DEBUGLEVEL_CONSTRUCTOR) cerr << "Chatter(\"" << name << "\") constructor called." << endl; if(name.isNull()) { if(::debuglevel & (DEBUGLEVEL_WARNING | DEBUGLEVEL_CONSTRUCTOR)) cerr << "Chatter::Chatter(QString): Null Chatter created. loadChatter() call needed." << endl; } int i = findChatter(name); if(i >=0) { chatters[i]->incRefCount(); index = i; } else { i = findFirstSpace(); if(i >= 0) { chatters[i] = new ChatterRef(name); chatters[i]->incRefCount(); index = i; } else { cerr << "Chatter::Chatter(QString): Unable to create ChatterRef for"; cerr << name << '.' << endl; } } lb = 0; if(index >= MAX_NUM_CHATTERS) cerr << "Chatter::Chatter(): Error: index = " << index << endl; } Chatter::Chatter(const char *name) { if(::debuglevel & DEBUGLEVEL_CONSTRUCTOR) cerr << "Chatter(\"" << name << "\") constructor called." << endl; if(!name) { if(::debuglevel & (DEBUGLEVEL_WARNING | DEBUGLEVEL_CONSTRUCTOR)) cerr << "Chatter::Chatter(const char *): Null Chatter created. loadChatter() call needed." << endl; } int i = findChatter(QString(name)); if(i >=0) { chatters[i]->incRefCount(); index = i; } else { i = findFirstSpace(); if(i >= 0) { chatters[i] = new ChatterRef(name); chatters[i]->incRefCount(); index = i; } else { cerr << "Chatter::Chatter(const char *): Unable to create ChatterRef for"; cerr << name << '.' << endl; } } lb = 0; if(index >= MAX_NUM_CHATTERS) cerr << "Chatter::Chatter(): Error: index = " << index << endl; } Chatter::Chatter(const Chatter &c) { index = c.index; lb = c.lb; int i = chatters[index]->incRefCount(); if(::debuglevel & DEBUGLEVEL_COPYCONSTRUCTOR) cerr << "Chatter(\"" << c.getName() << "\") copy constructor called (" << i << ")." << endl; } Chatter::~Chatter() { if(::debuglevel & DEBUGLEVEL_DESTRUCTOR) cerr << "Chatter(\"" << getName() << "\") destructor called ("; int i; if((i = chatters[index]->decRefCount()) == 0) { // don't delete the last chatter // delete chatters[index]; // chatters[index] = 0; } if(::debuglevel & DEBUGLEVEL_DESTRUCTOR) cerr << i << ")." << endl; } void Chatter::destroyAll() { for(int i=0; i<MAX_NUM_CHATTERS; i++) { if(chatters[i]) { delete chatters[i]; chatters[i] = 0; } } } int Chatter::findChatter(QString name) { if(!name.isNull()) { for(int i=0; i<MAX_NUM_CHATTERS; i++) { if(chatters[i] && name.lower() == chatters[i]->getName().lower()) return i; } } return -1; } int Chatter::findFirstSpace() { for(int i=0; i<MAX_NUM_CHATTERS; i++) { if(chatters[i]==0) return i; } return -1; } bool Chatter::loadChatters(istream &is) { int n; // number of chatters saved in state stream int version; // version no. if(!is) return false; // error getting state char header[256]; // <Chatter> tag is.getline(header, 256, '>'); if(!is) { // error getting state cerr << "Chatter::loadChatters(istream&): Error reading header." << endl; } else { // make sure tag is proper char *cp; if((cp=strstr(header, "<Chatter")) == NULL) return false; cp += 8; // skip the "<Chatter" substring if((cp=strstr(header, "count=")) == NULL || sscanf(cp+6, "%d", &n)!=1) return false; if((cp=strstr(header, "version=")) == NULL || (sscanf(cp+8, "%d>", &version)!=1)) version = 1; if(n > MAX_NUM_CHATTERS) { // capacity exceeded cerr << "*** Error!!! Too many chatters in file... not loading." << endl; return false; } else if(((float)n / (float)MAX_NUM_CHATTERS) > 0.9) { // about to exceed capacity cerr << "*** Warning!!! Chatter chatters[] at critical level." << endl; cerr << "*** Increase MAX_NUM_CHATTERS and recompile." << endl; } cout << "Loading Chatters... 0%" << flush; for(int i=0; i<n; i++) { if(ChatterRef::createFromStream(is, version) || !is) { cerr << "Chatter::loadChatters(istream&): error creating Chatter #"; cerr << setw(3) << setfill('0') << i << " of "; cerr << setw(3) << setfill('0') << n << '.' << endl; cerr << "Chatter::loadChatters(istream&): assuming end of file." << endl; return false; } if(i%5) { printf("\b\b\b\b%3d%%", (i+1)*100/n); fflush(stdout); // cout << "\b\b\b\b\b" << setw(3) << setfill(' ') << ios::right << (i+1)*100/n << '%' << flush; } } is.scan("</Chatters>"); } // cout << "\b\b\b\b\b100%%" << endl; printf("\b\b\b\b100%%\n"); return (bool)is; } bool Chatter::saveChatters(ostream &os) { int num_saveable_chatters = 0; for(int i=0; i<MAX_NUM_CHATTERS; i++) if(chatters[i] && ( chatters[i]->isIgnored() || chatters[i]->isHighlighted() || chatters[i]->getFriendLevel() > STRANGER)) num_saveable_chatters++; os << "<Chatters count=" << num_saveable_chatters; os << " version=2>" << endl; // set version of chatters.ini int num_saveable_chatters_check = 0; for(int i=0; i<MAX_NUM_CHATTERS; i++) { if(chatters[i] && (chatters[i]->getFriendLevel() > STRANGER || // don't save strangers chatters[i]->isHighlighted() // save people w/ interesting states || chatters[i]->isIgnored() ) ) { chatters[i]->saveState(os); num_saveable_chatters_check++; } // end if } // end for() if(num_saveable_chatters != num_saveable_chatters_check) { cerr << "Chatter::saveChatters(ostream &): Chatter count discrepancy." << endl; cerr << " : "; cerr << num_saveable_chatters << " != " << num_saveable_chatters_check << endl; } os << "</Chatters>" << endl; return (bool)os; } void Chatter::paint(QPainter *p) { if(p) { p->save(); if(isMe()) { // do something special for 'me' p->setPen(Qt::red); } else { if(isIgnored()) { p->setPen(Qt::gray); } else { switch(getFriendLevel()) { case FRIEND: p->setPen(QColor(176,48,96)); // maroon break; case TRUSTED_FRIEND: p->setPen(QColor(225,69,25)); break; case GOD: p->setPen(Qt::red); break; case STRANGER: default: p->setPen(Qt::black); break; } } if(isHighlighted()) { p->setBackgroundMode(Qt::OpaqueMode); p->setBackgroundColor(getHighlightColor()); p->setPen(Qt::darkBlue); } } QFontMetrics fm = p->fontMetrics(); p->drawText(3, fm.ascent() + fm.leading()/2, getName()); p->restore(); } } int Chatter::height(const QListBox *list) const { if(!list) list = lb; return list->fontMetrics().lineSpacing(); } int Chatter::width(const QListBox *list) const { if(!list) list = lb; QFont f=list->font(); f.setBold(true); return QFontMetrics(f).width(getName())+6; } int Chatter::height(QPainter *p) const { if(p) return p->fontMetrics().lineSpacing(); else return 0; } int Chatter::width(QPainter *p) const { if(p) return p->fontMetrics().width(getName())+6; else return 0; } // Mutators void Chatter::setFriendLevel(FriendLevel fl) { chatters[index]->setFriendLevel(fl); } void Chatter::setIgnored(bool _ignored) { chatters[index]->setIgnored(_ignored); } void Chatter::setHighlighted(bool _highlighted) { chatters[index]->setHighlighted(_highlighted); } void Chatter::setListBox(const QListBox *_lb) { lb = _lb; } void Chatter::setHighlightColor(QColor c) { chatters[index]->setHighlightColor(c); } void Chatter::setLastEventType(ChatEntryType t) { chatters[index]->setLastEventType(t); } void Chatter::doEvent(QString txt) { chatters[index]->doEvent(txt); } void Chatter::doEvent() { // register event done by chatter & update counters doEvent(QString()); } void Chatter::setEventQueueSize(int size) { chatters[index]->setEventQueueSize(size); } // Accessors int Chatter::numChatters() { return ChatterRef::numChatters(); } QString Chatter::text() const { return chatters[index]->getiName(); } Chatter *Chatter::getMe() { for(int i=0; i < MAX_NUM_CHATTERS && i<ChatterRef::numChatters(); i++) if(chatters[i] && chatters[i]->isMe()) return new Chatter(chatters[i]->getName()); return 0; } QString Chatter::getName() const { return chatters[index]->getName(); } FriendLevel Chatter::getFriendLevel() const { return chatters[index]->getFriendLevel(); } QColor Chatter::getHighlightColor() { return chatters[index]->getHighlightColor(); } Chatter::operator QString() { return text(); } bool Chatter::operator==(const Chatter &c) const { return index == c.index; } bool Chatter::operator!=(const Chatter &c) const { return index != c.index; } bool Chatter::isIgnored() const { return chatters[index]->isIgnored(); } bool Chatter::isHighlighted() const { return chatters[index]->isHighlighted(); } bool Chatter::isMe() const { return chatters[index]->isMe(); } void Chatter::setMe(bool b) { chatters[index]->setMe(b); } bool Chatter::isConnected() const { // check if chatter is me and connected return chatters[index]->isConnected(); } int Chatter::numPMEvents() const { // number of PMs emitted by Chatter return chatters[index]->numPMEvents(); } void Chatter::incNumPMEvents() { // increment number of PMs emitted by Chatter chatters[index]->incNumPMEvents(); } int Chatter::numCapsEvents() const { // num. uppercase posts emitted by Chatter return chatters[index]->numCapsEvents(); } void Chatter::incNumCapsEvents() { // inc. num. of uppercase posts emitted by Chatter chatters[index]->incNumCapsEvents(); } ChatEntryType Chatter::getLastEventType() const { return chatters[index]->getLastEventType(); } float Chatter::getEventsPerSec() const { return chatters[index]->getEventsPerSec(); } float Chatter::getLastEventsPerSec() const { return chatters[index]->getLastEventsPerSec(); } float Chatter::getEventsPerSecPerSec() const { return chatters[index]->getEventsPerSecPerSec(); } int Chatter::getEventQueueSize() const { return chatters[index]->getEventQueueSize(); } int Chatter::numEvents() const { return chatters[index]->numEvents(); } int Chatter::numDuplicateEvents() const { // number of duplicates of most recent event return chatters[index]->numDuplicateEvents(); } int Chatter::getNumTotalEvents() const { // total number of events posted by Chatter return chatters[index]->getNumTotalEvents(); } QString Chatter::getLastLine() const { // last line posted by chatter return chatters[index]->getLastLine(); } const QListBox *Chatter::getListBox() const { return lb; } // detect clones QString Chatter::isClone(float threshold, FriendLevel compare_friendlevel, float &similarity) const { int count=0; int chatters_index=0; ChatterRef *chatterptr; // only check valid Chatters if(chatters[index] == 0) return QString(); // loop through chatters while(chatters_index < MAX_NUM_CHATTERS && count < numChatters()) { if((chatterptr=chatters[chatters_index]) != 0) { // valid ChatterRef? // only compare against people who are >= compare_friendlevel if(chatterptr->getFriendLevel() >= compare_friendlevel) { // calculate similarity to current chatter float tmp_similarity = getSimilarity(chatterptr->getName(), getName()); if(tmp_similarity > threshold && fabs(1.0-tmp_similarity) > 0.000001 ) { similarity = tmp_similarity; return chatterptr->getName(); // clone found } } // end friendlevel comparison count++; // incr. num chatters tested } // end valid ChatterRef test chatters_index++; // try next ChatterRef } // end loop return QString(); // not a clone } // end function
28.428734
130
0.663003
[ "object", "3d" ]
2f6d1090741b679dc61f0cfa31c34995f0c81927
3,278
cpp
C++
src/ofApp.cpp
Poofjunior/of3DTests
fe2f4ddf8e23a3595813e57cf24a315291da4b19
[ "MIT" ]
null
null
null
src/ofApp.cpp
Poofjunior/of3DTests
fe2f4ddf8e23a3595813e57cf24a315291da4b19
[ "MIT" ]
null
null
null
src/ofApp.cpp
Poofjunior/of3DTests
fe2f4ddf8e23a3595813e57cf24a315291da4b19
[ "MIT" ]
null
null
null
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetFrameRate(60); ofBackground(ofColor::dimGray); ofNoFill(); currView_.encodeRotation(0, 1, 0, 0); lastMouseX_ = 0; lastMouseY_ = 0; q1.encodeRotation(M_PI/120, 1, 0, 1); q2.encodeRotation(M_PI/120, -1, 0, 1); q3.encodeRotation(M_PI/60, 1, 0, 0); myVec.x = 0; myVec.y = 0; myVec.z = 300; myVecs = std::vector<vec3>(3); myVecs[0].x_ = 0; myVecs[0].y_ = 0; myVecs[0].z_ = 100; myVecs[1].x_ = 0; myVecs[1].y_ = 0; myVecs[1].z_ = 100; myVecs[2].x_ = 0; myVecs[2].y_ = 0; myVecs[2].z_ = 100; } //-------------------------------------------------------------- void ofApp::update(){ q1.rotate(myVecs[0].x_, myVecs[0].y_, myVecs[0].z_); q2.rotate(myVecs[1].x_, myVecs[1].y_, myVecs[1].z_); q3.rotate(myVecs[2].x_, myVecs[2].y_, myVecs[2].z_); std::cout << currView_ << std::endl; cameraOrientation_ = currView_; cameraPosition_.set(0, 0, 600); cameraOrientation_.rotate(cameraPosition_[0], cameraPosition_[1], cameraPosition_[2]); worldCam_.setPosition(cameraPosition_); float angle, x, y, z; cameraOrientation_.getRotation(angle, x, y, z); std::cout << "angle: " << angle << std::endl; std::cout << "axis: " << x << ", " << y << ", " << z << std::endl; ofQuaternion tempQuat; tempQuat.makeRotate(angle*(180/M_PI), x, y, z); worldCam_.setOrientation(tempQuat); } void ofApp::draw(){ worldCam_.begin(); // Draw grid in the center of the screen ofDrawGrid(300, 5); ofDrawAxis(250); ofDrawSphere(0, 0, 0, 200); float theta, x, y, z; for (int i = 0; i < 3; ++i) ofDrawSphere(myVecs[i].x_, myVecs[i].y_, myVecs[i].z_, 10); worldCam_.end(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button) { Quaternion<float>xView; Quaternion<float>yView; float dampen = 0.4; yView.encodeRotation(-1*(y - lastMouseY_)*dampen * (M_PI/180.), 1, 0, 0); xView.encodeRotation(-1*(x - lastMouseX_)*dampen * (M_PI/180.), 0, 1, 0); //currView_ = xView * currView_ * yView; currView_ = currView_ * yView * xView; currView_.normalize(); lastMouseX_ = x; lastMouseY_ = y; } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button) { lastMouseX_ = mouseX; lastMouseY_ = mouseY; } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button) {} void ofApp::drawArrow(float x, float y, float z, float roll, float pitch, float yaw, float scale) { ofPushMatrix(); // Save current pose ofTranslate(x, y, z); ofRotateX(roll); ofRotateY(pitch); ofRotateZ(yaw - 90 ); // default arrow is collinear with the +x axis. ofDrawCylinder(0, scale * 20, 0, scale * 1, scale * 40); ofDrawCone(0, scale * 50, 0, scale * 5, scale * -20); ofPopMatrix(); }
24.646617
77
0.516168
[ "vector" ]
2f6d41a7438ad89a0cf2ce83a1774ea57892e6ec
2,335
hpp
C++
Engine/Source/Core/RHI/Public/Texture3D.hpp
rbetik12/RightEngine
d7db7605da0e33b8ae696429b4085e154fd9c2fa
[ "MIT" ]
null
null
null
Engine/Source/Core/RHI/Public/Texture3D.hpp
rbetik12/RightEngine
d7db7605da0e33b8ae696429b4085e154fd9c2fa
[ "MIT" ]
null
null
null
Engine/Source/Core/RHI/Public/Texture3D.hpp
rbetik12/RightEngine
d7db7605da0e33b8ae696429b4085e154fd9c2fa
[ "MIT" ]
null
null
null
#pragma once #include "Texture.hpp" #include <array> namespace RightEngine { struct CubeMapFaces { std::vector<uint8_t> face1; std::vector<uint8_t> face2; std::vector<uint8_t> face3; std::vector<uint8_t> face4; std::vector<uint8_t> face5; std::vector<uint8_t> face6; const std::vector<uint8_t>& GetFaceData(uint32_t index) const { R_CORE_ASSERT(index >= 0 && index < 6, ""); switch (index) { case 0: return face1; case 1: return face2; case 2: return face3; case 3: return face4; case 4: return face5; case 5: return face6; } } void SetFaceData(const std::vector<uint8_t>& data, uint32_t index) { R_CORE_ASSERT(index >= 0 && index < 6, ""); switch (index) { case 0: R_CORE_ASSERT(face1.empty(), ""); face1 = data; break; case 1: R_CORE_ASSERT(face2.empty(), ""); face2 = data; break; case 2: R_CORE_ASSERT(face3.empty(), ""); face3 = data; break; case 3: R_CORE_ASSERT(face4.empty(), ""); face4 = data; break; case 4: R_CORE_ASSERT(face5.empty(), ""); face5 = data; break; case 5: R_CORE_ASSERT(face6.empty(), ""); face6 = data; break; } } }; class Texture3D : public Texture { public: static std::shared_ptr<Texture3D> Create(const std::array<std::string, 6>& texturesPath); static std::shared_ptr<Texture3D> Create(const TextureSpecification& textureSpecification, const std::array<std::vector<uint8_t>, 6>& data); virtual void GenerateMipmaps() const = 0; }; }
29.1875
98
0.416702
[ "vector" ]
2f765ac1eba23c65eec7ee51d4255c4d665884fa
4,096
cpp
C++
src/dg/src/analysis/ReachingDefinitions/Srg/MarkerSRGBuilderFS.cpp
examon/llvm-stuff
0c226536361c1d4ba95b86dd7a8672525db83a78
[ "Apache-2.0" ]
1
2019-12-16T01:48:08.000Z
2019-12-16T01:48:08.000Z
src/dg/src/analysis/ReachingDefinitions/Srg/MarkerSRGBuilderFS.cpp
examon/llvm-stuff
0c226536361c1d4ba95b86dd7a8672525db83a78
[ "Apache-2.0" ]
2
2018-10-18T05:28:07.000Z
2018-11-21T10:20:23.000Z
src/analysis/ReachingDefinitions/Srg/MarkerSRGBuilderFS.cpp
ManSoSec/dg
4bd115f8cf26d3584f009c92c0f7c21b1fb57307
[ "MIT" ]
1
2021-02-10T02:14:31.000Z
2021-02-10T02:14:31.000Z
#include "analysis/ReachingDefinitions/Srg/MarkerSRGBuilderFS.h" using namespace dg::analysis::rd::srg; /** * Saves the current definition of certain variable in given block * Used from value numbering procedures. */ void MarkerSRGBuilderFS::writeVariableStrong(const DefSite& var, NodeT *assignment, BlockT *block) { detail::Interval interval = concretize(detail::Interval{var.offset, var.len}, var.target->getSize()); current_weak_def[var.target][block].killOverlapping(interval); current_def[var.target][block].killOverlapping(interval); // remember the last definition current_def[var.target][block].add(std::move(interval), assignment); } void MarkerSRGBuilderFS::writeVariableWeak(const DefSite& var, NodeT *assignment, BlockT *block) { current_weak_def[var.target][block].add(concretize(detail::Interval{var.offset, var.len}, var.target->getSize()), assignment); } std::vector<MarkerSRGBuilderFS::NodeT *> MarkerSRGBuilderFS::readVariable(const DefSite& var, BlockT *read, BlockT *start, const Intervals& covered) { assert( read ); auto& block_defs = current_def[var.target]; auto it = block_defs.find(read); std::vector<NodeT *> result; const auto interval = concretize(detail::Interval{var.offset, var.len}, var.target->getSize()); // find weak defs auto block_weak_defs = current_weak_def[var.target][read].collectAll(interval); // find the last definition if (it != block_defs.end()) { Intervals cov; bool is_covered = false; std::tie(result, cov, is_covered) = it->second.collect(interval, covered); if (!is_covered && (!interval.isUnknown() || read != start)) { NodeT *phi = readVariableRecursive(var, read, start, cov); result.push_back(phi); } } else { result.push_back(readVariableRecursive(var, read, start, covered)); } // add weak defs std::move(block_weak_defs.begin(), block_weak_defs.end(), std::back_inserter(result)); return result; } void MarkerSRGBuilderFS::addPhiOperands(const DefSite& v, NodeT *phi, BlockT *block, BlockT *start, const std::vector<detail::Interval>& covered) { DefSite var = v; const auto interval = concretize(detail::Interval{var.offset, var.len}); var.offset = interval.getStart(); var.len = interval.getLength(); phi->addDef(var, true); phi->addUse(var); for (BlockT *pred : block->predecessors()) { std::vector<NodeT *> assignments; Intervals cov; bool is_covered = false; std::tie(assignments, cov, is_covered) = last_def[var.target][pred].collect(interval, covered); // add weak updates auto weak_defs = last_weak_def[var.target][pred].collectAll(interval); std::move(weak_defs.begin(), weak_defs.end(), std::back_inserter(assignments)); if (!is_covered || (interval.isUnknown() && block != start)) { std::vector<NodeT *> assignments2 = readVariable(var, pred, start, cov); std::move(assignments2.begin(), assignments2.end(), std::back_inserter(assignments)); } for (auto& assignment : assignments) insertSrgEdge(assignment, phi, var); } } MarkerSRGBuilderFS::NodeT *MarkerSRGBuilderFS::readVariableRecursive(const DefSite& var, BlockT *block, BlockT *start, const std::vector<detail::Interval>& covered) { std::vector<NodeT *> result; auto interval = concretize(detail::Interval{var.offset, var.len}, var.target->getSize()); auto phi = std::unique_ptr<NodeT>(new NodeT(RDNodeType::PHI)); phi->setBasicBlock(block); // writeVariableStrong kills current weak definitions, which are needed in the phi node, so we need to lookup them first. auto weak_defs = current_weak_def[var.target][block].collectAll(interval); for (auto& assignment : weak_defs) insertSrgEdge(assignment, phi.get(), var); writeVariableStrong(var, phi.get(), block); addPhiOperands(var, phi.get(), block, start, covered); NodeT *val = phi.get(); phi_nodes.push_back(std::move(phi)); return val; }
41.795918
166
0.685303
[ "vector" ]
2f76b4fd15317b27085a2917e8d4bbe455a71a6e
1,273
cpp
C++
sources/2015/2015_02.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
2
2021-02-01T13:19:37.000Z
2021-02-25T10:39:46.000Z
sources/2015/2015_02.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
null
null
null
sources/2015/2015_02.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
null
null
null
#include "2015_02.h" namespace Day02_2015 { int part_one(const t_items& items) { int area = 0; vector<int> s(3); for (const auto& x : items) { const auto& [l, w, h] = x; s[0] = l * w; s[1] = w * h; s[2] = h * l; sort(s.begin(), s.end()); area += accumulate(s.begin(), s.end(), 0) * 2 + s[0]; } return area; } int part_two(const t_items& items) { int ribbon = 0; vector<int> s(3); for (const auto& x : items) { const auto& [l, w, h] = x; s[0] = l; s[1] = w; s[2] = h; sort(s.begin(), s.end()); ribbon += 2 * s[0] + 2 * s[1] + s[0] * s[1] * s[2]; } return ribbon; } t_output main(const t_input& input) { smatch matches; regex regex("([0-9]*)x([0-9]*)x([0-9]*)"); t_items items; for (const auto& line : input) { regex_search(line, matches, regex); items.push_back(make_tuple(stoi(matches[1].str()), stoi(matches[2].str()), stoi(matches[3].str()))); } auto t0 = chrono::steady_clock::now(); auto p1 = part_one(items); auto p2 = part_two(items); auto t1 = chrono::steady_clock::now(); vector<string> solutions; solutions.push_back(to_string(p1)); solutions.push_back(to_string(p2)); return make_pair(solutions, chrono::duration<double>((t1 - t0) * 1000).count()); } }
20.868852
103
0.571092
[ "vector" ]
2f7f93c6f0319cd457b11ace7d0e81a82fec994d
564
cpp
C++
C++/0398-Random-Pick-Index/soln-2.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/0398-Random-Pick-Index/soln-2.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/0398-Random-Pick-Index/soln-2.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
class Solution { vector<int> nums; public: Solution(vector<int> nums) { this->nums = nums; } int pick(int target) { int cnt = 1, idx = 0, n = nums.size(); for(int i = 0; i < n; ++i) { if (nums[i] == target) { int r = rand() % cnt; if (r == 0) idx = i; ++cnt; } } return idx; } }; /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int param_1 = obj.pick(target); */
21.692308
64
0.453901
[ "object", "vector" ]
2f80423cd080b117b00402a2d91e65ab15cdd0b2
3,236
hpp
C++
test/utils.hpp
bloomen/densitas
ede7f20ca40609c7991aed5bc39ed1f2ca85b62a
[ "MIT" ]
3
2017-05-04T20:34:28.000Z
2018-05-20T17:04:39.000Z
test/utils.hpp
bloomen/densitas
ede7f20ca40609c7991aed5bc39ed1f2ca85b62a
[ "MIT" ]
null
null
null
test/utils.hpp
bloomen/densitas
ede7f20ca40609c7991aed5bc39ed1f2ca85b62a
[ "MIT" ]
null
null
null
#pragma once #include <libunittest/all.hpp> #include <densitas/all.hpp> #define ARMA_DONT_USE_CXX11 #include <armadillo> using namespace unittest::assertions; typedef arma::vec vector_t; typedef arma::mat matrix_t; inline vector_t mkcol(std::vector<double> data) { vector_t col(data.size()); std::copy(data.begin(), data.end(), col.begin()); return col; } inline arma::rowvec mkrow(std::vector<double> data) { arma::rowvec row(data.size()); std::copy(data.begin(), data.end(), row.begin()); return row; } struct mock_model { vector_t prediction; vector_t train_y; matrix_t train_X; mock_model() : prediction(), train_y(), train_X() {} std::unique_ptr<mock_model> clone() const { std::unique_ptr<mock_model> m(new mock_model); m->prediction = prediction; m->train_y = train_y; m->train_X = train_X; return std::move(m); } void train(matrix_t& X, vector_t& y) { train_y = y; train_X = X; } vector_t predict_proba(matrix_t&) const { return prediction; } }; const int no = densitas::model_adapter::no<mock_model>(); const int yes = densitas::model_adapter::yes<mock_model>(); const double dno = static_cast<double>(no); const double dyes = static_cast<double>(yes); namespace densitas { namespace matrix_adapter { template<> inline std::size_t n_rows(const matrix_t& matrix) { return matrix.n_rows; } template<> inline std::size_t n_columns(const matrix_t& matrix) { return matrix.n_cols; } } // matrix_adapter namespace vector_adapter { template<> inline std::size_t n_elements(const vector_t& vector) { return vector.n_elem; } } // vector_adapter } // densitas namespace unittest { namespace assertions { template<typename... Args> void assert_equal_containers(const matrix_t& expected, const matrix_t& actual, const Args&... message) { assert_equal(expected.n_rows, actual.n_rows, "n_rows don't match! ", message...); assert_equal(expected.n_cols, actual.n_cols, "n_cols don't match! ", message...); for (std::size_t i=0; i<expected.n_rows; ++i) { if (!unittest::core::is_containers_equal(arma::rowvec(expected.row(i)), arma::rowvec(actual.row(i)))) { const std::string text = "matrices are not equal"; unittest::fail(UNITTEST_FUNC, text, message...); } } } template<typename... Args> void assert_approx_equal_containers(const matrix_t& expected, const matrix_t& actual, const double eps, const Args&... message) { assert_equal(expected.n_rows, actual.n_rows, "n_rows don't match! ", message...); assert_equal(expected.n_cols, actual.n_cols, "n_cols don't match! ", message...); for (std::size_t i=0; i<expected.n_rows; ++i) { if (!unittest::core::is_containers_approx_equal(arma::rowvec(expected.row(i)), arma::rowvec(actual.row(i)), eps)) { const std::string text = "matrices are not approx. equal"; unittest::fail(UNITTEST_FUNC, text, message...); } } } } // unittest } // assertions
22.472222
123
0.633189
[ "vector" ]
2f9f211645fcbbda61f82d65349836d0c761e200
3,623
cpp
C++
extobject.cpp
apfeltee/escript
d0dd02c0f05d100755333d90033f1324dfef99e3
[ "MIT" ]
null
null
null
extobject.cpp
apfeltee/escript
d0dd02c0f05d100755333d90033f1324dfef99e3
[ "MIT" ]
null
null
null
extobject.cpp
apfeltee/escript
d0dd02c0f05d100755333d90033f1324dfef99e3
[ "MIT" ]
null
null
null
// ExtObject.cpp // This file is part of the EScript programming language (https://github.com/EScript) // // Copyright (C) 2011-2013 Claudius Jähn <ClaudiusJ@live.de> // Copyright (C) 2012 Benjamin Eikel <benjamin@eikel.org> // // Licensed under the MIT License. See LICENSE file for details. // --------------------------------------------------------------------------------- #include "escript.h" #include "escript.h" #include "escript.h" namespace EScript { //! (static) Type* ExtObject::getTypeObject() { static Type* typeObject = new Type(Object::getTypeObject());// ---|> Object return typeObject; } //! (static) initMembers void ExtObject::init(EScript::Namespace& globals) { Type* typeObject = getTypeObject(); typeObject->allowUserInheritance(true); initPrintableName(typeObject, getClassName()); declareConstant(&globals, getClassName(), typeObject); //! [ESF] ExtObject new ExtObject( [Map objAttributes] ) ES_CONSTRUCTOR(typeObject, 0, 1, { ERef<ExtObject> result(new ExtObject(thisType)); if(parameter.count() > 0) { Map* m = assertType<Map>(rt, parameter[0]); for(const auto& keyValuePair : *m) { result->setAttribute(keyValuePair.first, Attribute(keyValuePair.second.value)); } } return result.detachAndDecrease(); }) } // ----------------------------------------------------------------------------------------------- //! (static) factory ExtObject* ExtObject::create() { return new ExtObject; } //! (ctor) ExtObject::ExtObject() : Object(ExtObject::getTypeObject()) { //ctor } ExtObject::ExtObject(const ExtObject& other) : Object(other.getType()) { // if(typeRef) // typeRef->copyObjAttributesTo(this); cloneAttributesFrom(&other); } //! (ctor) ExtObject::ExtObject(Type* type) : Object(type) { if(typeRef) typeRef->copyObjAttributesTo(this); //ctor } //! ---|> [Object] Object* ExtObject::clone() const { ExtObject* c = new ExtObject(getType()); c->cloneAttributesFrom(this); return c; } // ----------------------------------------------------------------------------------------------- // attributes //! ---|> [Object] void ExtObject::_initAttributes(Runtime& rt) { objAttributes.initAttributes(rt); } //! ---|> [Object] Attribute* ExtObject::_accessAttribute(const StringId& id, bool localOnly) { Attribute* attr = objAttributes.accessAttribute(id); if(attr == nullptr && !localOnly && getType() != nullptr) { attr = getType()->findTypeAttribute(id); } return attr; } //! ---|> [Object] bool ExtObject::setAttribute(const StringId& id, const Attribute& attr) { objAttributes.setAttribute(id, attr); return true; } void ExtObject::cloneAttributesFrom(const ExtObject* obj) { objAttributes.cloneAttributesFrom(obj->objAttributes); } //! ---|> Object void ExtObject::collectLocalAttributes(std::unordered_map<StringId, Object*>& attrs) { objAttributes.collectAttributes(attrs); } }// namespace EScript
29.217742
114
0.510351
[ "object" ]
2fa2c4f5335a54dbfb4fb62df38c2f3d9bb0a2f6
3,875
cpp
C++
Homeworks/04_Homework/05_zuma.cpp
NaskoVasilev/Data-Structures-And-Algorithms
1a4dba588df7e88498fddda9c04a8832f8c0dad8
[ "MIT" ]
2
2021-10-31T18:32:47.000Z
2022-01-28T08:58:34.000Z
Homeworks/04_Homework/05_zuma.cpp
NaskoVasilev/Data-Structures-And-Algorithms
1a4dba588df7e88498fddda9c04a8832f8c0dad8
[ "MIT" ]
null
null
null
Homeworks/04_Homework/05_zuma.cpp
NaskoVasilev/Data-Structures-And-Algorithms
1a4dba588df7e88498fddda9c04a8832f8c0dad8
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <list> using namespace std; int main() { int n; cin >> n; vector<list<int>::iterator> references; list<int> balls; list<int>::iterator pointer; for (int i = 0; i < n; ++i) { int ball; cin >> ball; balls.push_back(ball); if (i == 0) { pointer = balls.begin(); } else { pointer++; } references.push_back(pointer); } int queriesCount; cin >> queriesCount; vector<string> output; for (int i = 0; i < queriesCount; ++i) { int position; cin >> position; int targetBall; cin >> targetBall; if (balls.empty()) { output.push_back("Game Over"); continue; } auto currentBallPointer = references[position]; currentBallPointer++; balls.insert(currentBallPointer, targetBall); auto newBallPointer = references[position]; ++newBallPointer; references.push_back(newBallPointer); list<int>::iterator startPointer = references[position]; int totalBallsToCollapse = 0; int ballsToCollapse = 0; bool shouldRemoveFirst = false; while (startPointer != balls.begin() && *startPointer == targetBall) { ballsToCollapse++; startPointer--; } if (startPointer == balls.begin() && *startPointer == targetBall) { ballsToCollapse++; shouldRemoveFirst = true; } list<int>::iterator endPointer = references[position]; endPointer++; while (endPointer != balls.end() && *endPointer == targetBall) { ballsToCollapse++; endPointer++; } if (ballsToCollapse < 3) { output.push_back("0"); continue; } totalBallsToCollapse = ballsToCollapse; list<int>::iterator startCollapsePointer = startPointer; list<int>::iterator endCollapsePointer = endPointer; if (startPointer == balls.begin() && !shouldRemoveFirst && *startPointer == *endPointer) { int rightBallsToCollapse = 1; while (endPointer != balls.end() && *endPointer == *startPointer) { rightBallsToCollapse++; endPointer++; } if (rightBallsToCollapse >= 3) { totalBallsToCollapse += rightBallsToCollapse; } } while (endCollapsePointer != balls.end() && *startCollapsePointer == *endCollapsePointer) { targetBall = *endCollapsePointer; ballsToCollapse = 0; while (endPointer != balls.end() && *endPointer == targetBall) { ballsToCollapse++; endPointer++; } while (startPointer != balls.begin() && *startPointer == targetBall) { ballsToCollapse++; startPointer--; } if (startPointer == balls.begin() && *startPointer == targetBall) { ballsToCollapse++; shouldRemoveFirst = true; } if (ballsToCollapse < 3) { break; } startCollapsePointer = startPointer; endCollapsePointer = endPointer; totalBallsToCollapse += ballsToCollapse; } list<int>::iterator startErasePointer = shouldRemoveFirst ? balls.begin() : ++startCollapsePointer; balls.erase(startErasePointer, endCollapsePointer); output.push_back(to_string(totalBallsToCollapse)); } for (auto line : output) { cout << line << endl; } if (balls.empty()) { cout << "-1"; } else { for (int ball : balls) { cout << ball << " "; } } }
27.877698
107
0.535226
[ "vector" ]
2fa434342d0d8d7a32f91bb4f8992a9a949ba498
2,386
cpp
C++
ClassicIE9/ClassicIE9DLL/ClassicIE9DLL.cpp
sedwards/ClassicShell
c7d4bac036d7da8e053bc12decfcd2e3744e0e76
[ "MIT" ]
11
2015-10-23T03:14:26.000Z
2021-04-19T21:40:28.000Z
ClassicIE9/ClassicIE9DLL/ClassicIE9DLL.cpp
vonchenplus/ClassicShell
c7d4bac036d7da8e053bc12decfcd2e3744e0e76
[ "MIT" ]
null
null
null
ClassicIE9/ClassicIE9DLL/ClassicIE9DLL.cpp
vonchenplus/ClassicShell
c7d4bac036d7da8e053bc12decfcd2e3744e0e76
[ "MIT" ]
14
2015-11-13T07:09:35.000Z
2020-04-05T13:10:45.000Z
// Classic Shell (c) 2009-2013, Ivo Beltchev // The sources for Classic Shell are distributed under the MIT open source license #include "stdafx.h" #include "resource.h" #include "ClassicIE9DLL_i.h" #include "ClassicIE9DLL.h" #include "Settings.h" #include "dllmain.h" CSIE9API void LogMessage( const char *text, ... ) { if (GetSettingInt(L"LogLevel")==0) return; wchar_t fname[_MAX_PATH]=L"%LOCALAPPDATA%\\ClassicIE9Log.txt"; DoEnvironmentSubst(fname,_countof(fname)); FILE *f; if (_wfopen_s(&f,fname,L"a+b")==0) { va_list args; va_start(args,text); vfprintf(f,text,args); va_end(args); fclose(f); } } // Used to determine whether the DLL can be unloaded by OLE STDAPI DllCanUnloadNow(void) { return _AtlModule.DllCanUnloadNow(); } // Returns a class factory to create an object of the requested type STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { return _AtlModule.DllGetClassObject(rclsid, riid, ppv); } // DllRegisterServer - Adds entries to the system registry STDAPI DllRegisterServer(void) { // registers object, typelib and all interfaces in typelib HRESULT res=_AtlModule.DllRegisterServer(); if (SUCCEEDED(res)) { // mark the extension as compatible with the enhanced protected mode of IE10 CComPtr<ICatRegister> catRegister; catRegister.CoCreateInstance(CLSID_StdComponentCategoriesMgr); if (catRegister) { CATID CATID_AppContainerCompatible={0x59fb2056,0xd625,0x48d0,{0xa9,0x44,0x1a,0x85,0xb5,0xab,0x26,0x40}}; catRegister->RegisterClassImplCategories(CLSID_ClassicIE9BHO,1,&CATID_AppContainerCompatible); } } return res; } // DllUnregisterServer - Removes entries from the system registry STDAPI DllUnregisterServer(void) { return _AtlModule.DllUnregisterServer(); } // DllInstall - Adds/Removes entries to the system registry per user // per machine. STDAPI DllInstall(BOOL bInstall, LPCWSTR pszCmdLine) { HRESULT hr = E_FAIL; static const wchar_t szUserSwitch[] = L"user"; if (pszCmdLine != NULL) { if (_wcsnicmp(pszCmdLine, szUserSwitch, _countof(szUserSwitch)) == 0) { AtlSetPerUserRegistration(true); } } if (bInstall) { hr = DllRegisterServer(); if (FAILED(hr)) { DllUnregisterServer(); } } else { hr = DllUnregisterServer(); } return hr; }
24.597938
108
0.706203
[ "object" ]
2fa76d0bfdd11c598362b08fd2ce1d170dbd2077
2,677
cpp
C++
aws-cpp-sdk-pinpoint-sms-voice-v2/source/model/AccountLimitName.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-pinpoint-sms-voice-v2/source/model/AccountLimitName.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-pinpoint-sms-voice-v2/source/model/AccountLimitName.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/pinpoint-sms-voice-v2/model/AccountLimitName.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace PinpointSMSVoiceV2 { namespace Model { namespace AccountLimitNameMapper { static const int PHONE_NUMBERS_HASH = HashingUtils::HashString("PHONE_NUMBERS"); static const int POOLS_HASH = HashingUtils::HashString("POOLS"); static const int CONFIGURATION_SETS_HASH = HashingUtils::HashString("CONFIGURATION_SETS"); static const int OPT_OUT_LISTS_HASH = HashingUtils::HashString("OPT_OUT_LISTS"); AccountLimitName GetAccountLimitNameForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == PHONE_NUMBERS_HASH) { return AccountLimitName::PHONE_NUMBERS; } else if (hashCode == POOLS_HASH) { return AccountLimitName::POOLS; } else if (hashCode == CONFIGURATION_SETS_HASH) { return AccountLimitName::CONFIGURATION_SETS; } else if (hashCode == OPT_OUT_LISTS_HASH) { return AccountLimitName::OPT_OUT_LISTS; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<AccountLimitName>(hashCode); } return AccountLimitName::NOT_SET; } Aws::String GetNameForAccountLimitName(AccountLimitName enumValue) { switch(enumValue) { case AccountLimitName::PHONE_NUMBERS: return "PHONE_NUMBERS"; case AccountLimitName::POOLS: return "POOLS"; case AccountLimitName::CONFIGURATION_SETS: return "CONFIGURATION_SETS"; case AccountLimitName::OPT_OUT_LISTS: return "OPT_OUT_LISTS"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace AccountLimitNameMapper } // namespace Model } // namespace PinpointSMSVoiceV2 } // namespace Aws
31.494118
98
0.629809
[ "model" ]
2fa9386b1b32769a5f37a41e52fabe9fa84d80e2
1,458
hxx
C++
src/core/ipcsoc.hxx
LittleGreyCells/escheme-interpreter
4843c2615f7f576c52c1d56ba3b6b94795d8f584
[ "MIT" ]
null
null
null
src/core/ipcsoc.hxx
LittleGreyCells/escheme-interpreter
4843c2615f7f576c52c1d56ba3b6b94795d8f584
[ "MIT" ]
null
null
null
src/core/ipcsoc.hxx
LittleGreyCells/escheme-interpreter
4843c2615f7f576c52c1d56ba3b6b94795d8f584
[ "MIT" ]
null
null
null
#ifndef IPCSOC_HXX #define IPCSOC_HXX // syntax: (SOCKET-CREATE-TCP [<server-flag>]) -> <sockfd> // syntax: (SOCKET-CREATE-UDP) -> <sockfd> // syntax: (SOCKET-READ <sockfd> <numbytes>) -> <byte-vector> // syntax: (SOCKET-WRITE <sockfd> <byte-vector>) -> <fixnum> // syntax: (SOCKET-RECVFROM <sockfd> <numbytes> <from-addr>) -> <byte-vector> // syntax: (SOCKET-RECV <sockfd> <numbytes>) -> <byte-vector> // syntax: (SOCKET-SENDTO <sockfd> <byte-vector> <to-address>) -> <fixnum> // syntax: (SOCKET-BIND <sockfd> <host-addr> <port> ) -> <sockfd> // syntax: (SOCKET-BIND-ADDRESS <sockfd> <address> ) -> <sockfd> // syntax: (SOCKET-CREATE-ADDRESS <host-addr> <port> ) -> <address> // syntax: (SOCKET-LISTEN <sockfd> [<backlog>]) -> <result> // syntax: (SOCKET-ACCEPT <sockfd> ) -> <sockfd> // syntax: (SOCKET-CONNECT <fd> <server-host-addr> <server-port> [<numtries>=1] ) -> <sockfd> // syntax: (SOCKET-DISCONNECT <socket>) -> <fixnum> // syntax: (SOCKET-CLOSE <socket>) -> <fixnum> // syntax: (READ-SELECT <fd-list>) --> <ready-list> #include "sexpr.hxx" namespace escheme { namespace IPCSOC { SEXPR read(); SEXPR write(); SEXPR recvfrom(); SEXPR recv(); SEXPR sendto(); SEXPR create_tcp(); SEXPR create_udp(); SEXPR bind(); SEXPR bind_address(); SEXPR create_address(); SEXPR listen(); SEXPR accept(); SEXPR connect(); SEXPR disconnect(); SEXPR close(); SEXPR read_select(); } } #endif
25.578947
93
0.628258
[ "vector" ]
2fb1d0fc5ba70a64100010d5938d4556edb474f5
9,530
hxx
C++
Modules/IO/ImageIO/include/otbImageSeriesFileReader.hxx
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
null
null
null
Modules/IO/ImageIO/include/otbImageSeriesFileReader.hxx
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
null
null
null
Modules/IO/ImageIO/include/otbImageSeriesFileReader.hxx
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * Copyright (C) 2007-2012 Institut Mines Telecom / Telecom Bretagne * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbImageSeriesFileReader_hxx #define otbImageSeriesFileReader_hxx #include "otbImageSeriesFileReader.h" namespace otb { template <class TImage, class TInternalImage> ImageSeriesFileReader<TImage, TInternalImage> ::ImageSeriesFileReader () { m_ExtractorList = ExtractSelectionListType::New(); } template <class TImage, class TInternalImage> void ImageSeriesFileReader<TImage, TInternalImage> ::AllocateListOfComponents() { for (unsigned int i = 0; i < this->GetNumberOfOutputs(); ++i) { this->m_ImageFileReaderList->PushBack(ReaderType::New()); this->m_OutputList->PushBack(OutputImageType::New()); m_ExtractorList->PushBack(ExtractSelectionListType::New()); } } template <class TImage, class TInternalImage> void ImageSeriesFileReader<TImage, TInternalImage> ::GenerateData(DataObjectPointerArraySizeType itkNotUsed(idx)) { std::ostringstream msg; msg << "Something wrong... Check the template definition of this class in the program...\n"; msg << "\"ENVI META FILE\" FileName: " << this->m_FileName << "\n"; ImageSeriesFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; } /* ********************************************************** * Methods that are specific to instantiation with Image type * ********************************************************** */ template <class TPixel, class TInternalPixel> ImageSeriesFileReader<Image<TPixel, 2>, Image<TInternalPixel, 2> > ::ImageSeriesFileReader () { m_ExtractorList = ExtractSelectionListType::New(); } /** * Allocation of the component... Here, based on ExtractROI */ template <class TPixel, class TInternalPixel> void ImageSeriesFileReader<Image<TPixel, 2>, Image<TInternalPixel, 2> > ::AllocateListOfComponents() { for (unsigned int i = 0; i < this->GetNumberOfOutputs(); ++i) { this->m_ImageFileReaderList->PushBack(ReaderType::New()); this->m_OutputList->PushBack(OutputImageType::New()); m_ExtractorList->PushBack(ExtractSelectionType::New()); } } /** * TestBandSelection tests if the templated Image type is compatible * with the bande selection provided in the Meta File */ template <class TPixel, class TInternalPixel> void ImageSeriesFileReader<Image<TPixel, 2>, Image<TInternalPixel, 2> > ::TestBandSelection(std::vector<unsigned int>& bands) { if (bands.size() != 1) { std::ostringstream msg; msg << "Unable to handle multicomponent file from Image<> class\n"; msg << "\"ENVI META FILE\" FileName: " << this->m_FileName << "\n"; ImageSeriesFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; } if (bands[0] != 1) { std::ostringstream msg; msg << "Unable to handle given band reading from multicomponent file with Image<> class\n"; msg << "\"ENVI META FILE\" FileName: " << this->m_FileName << "\n"; ImageSeriesFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; } return; } /** * GenerateData for Image type */ template <class TPixel, class TInternalPixel> void ImageSeriesFileReader<Image<TPixel, 2>, Image<TInternalPixel, 2> > ::GenerateData(DataObjectPointerArraySizeType idx) { otbMsgDebugMacro(<< "Reading " << idx << "th image: " << this->m_ListOfFileNames[idx]); ReaderType * reader = static_cast<ReaderType*>(this->m_ImageFileReaderList->GetNthElement(idx)); reader->SetFileName(this->m_ListOfFileNames[idx]); ExtractSelectionType * selection = static_cast<ExtractSelectionType*>(m_ExtractorList->GetNthElement(idx)); selection->SetExtractionRegion(this->m_ListOfRegionSelection[idx]); selection->SetInput(reader->GetOutput()); selection->GraftOutput(this->m_OutputList->GetNthElement(idx)); selection->Update(); this->m_OutputList->GetNthElement(idx)->Graft(selection->GetOutput()); } /* ********************************************************************* * Methods that are specific to instantiation with Image type for TImage * and VectorImage as TInternalImage * ********************************************************************* */ /** * Constructor */ template <class TPixel, class TInternalPixel> ImageSeriesFileReader<Image<TPixel, 2>, VectorImage<TInternalPixel, 2> > ::ImageSeriesFileReader () { //this->m_OutputList = OutputImageListType::New(); //this->m_ImageFileReaderList = ReaderListType::New(); m_ExtractorList = ExtractSelectionListType::New(); } /** * Allocation of the component... Here, based on MultiToMonoChannelExtractROI */ template <class TPixel, class TInternalPixel> void ImageSeriesFileReader<Image<TPixel, 2>, VectorImage<TInternalPixel, 2> > ::AllocateListOfComponents() { for (unsigned int i = 0; i < this->GetNumberOfOutputs(); ++i) { this->m_ImageFileReaderList->PushBack(ReaderType::New()); this->m_OutputList->PushBack(OutputImageType::New()); m_ExtractorList->PushBack(ExtractSelectionType::New()); } } /** * TestBandSelection tests if the templated Image type is compatible * with the bande selection provided in the Meta File */ template <class TPixel, class TInternalPixel> void ImageSeriesFileReader<Image<TPixel, 2>, VectorImage<TInternalPixel, 2> > ::TestBandSelection(std::vector<unsigned int>& bands) { if (bands.size() != 1) { std::ostringstream msg; msg << "Unable to handle multicomponent file from Image<> class as output\n"; msg << "\"ENVI META FILE\" FileName: " << this->m_FileName << "\n"; ImageSeriesFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; } return; } /** * GenerateData for Image type as output and VectorImage type for reading */ template <class TPixel, class TInternalPixel> void ImageSeriesFileReader<Image<TPixel, 2>, VectorImage<TInternalPixel, 2> > ::GenerateData(DataObjectPointerArraySizeType idx) { otbMsgDebugMacro(<< "Reading " << idx << "th image: " << this->m_ListOfFileNames[idx]); ReaderType * reader = static_cast<ReaderType*>(this->m_ImageFileReaderList->GetNthElement(idx)); reader->SetFileName(this->m_ListOfFileNames[idx]); ExtractSelectionType * selection = static_cast<ExtractSelectionType*>(this->m_ExtractorList->GetNthElement(idx)); selection->SetExtractionRegion(this->m_ListOfRegionSelection[idx]); selection->SetChannel(this->m_ListOfBandSelection[idx][0]); selection->SetInput(reader->GetOutput()); selection->GraftOutput(this->m_OutputList->GetNthElement(idx)); selection->Update(); this->m_OutputList->GetNthElement(idx)->Graft(selection->GetOutput()); } /* ****************************************************************** * Methods that are specific to instantiation with VectorImage types * ****************************************************************** */ /** * Constructor */ template <class TPixel, class TInternalPixel> ImageSeriesFileReader<VectorImage<TPixel, 2>, VectorImage<TInternalPixel, 2> > ::ImageSeriesFileReader () { //this->m_OutputList = OutputImageListType::New(); //this->m_ImageFileReaderList = ReaderListType::New(); m_ExtractorList = ExtractSelectionListType::New(); } /** * Allocation of the component... Here, based on MultiChannelExtractROI */ template <class TPixel, class TInternalPixel> void ImageSeriesFileReader<VectorImage<TPixel, 2>, VectorImage<TInternalPixel, 2> > ::AllocateListOfComponents() { for (unsigned int i = 0; i < this->GetNumberOfOutputs(); ++i) { this->m_ImageFileReaderList->PushBack(ReaderType::New()); this->m_OutputList->PushBack(OutputImageType::New()); m_ExtractorList->PushBack(ExtractSelectionType::New()); } } /** * GenerateData specialised for VectorImages */ template <class TPixel, class TInternalPixel> void ImageSeriesFileReader<VectorImage<TPixel, 2>, VectorImage<TInternalPixel, 2> > ::GenerateData(DataObjectPointerArraySizeType idx) { otbMsgDebugMacro(<< "Reading " << idx << "th image: " << this->m_ListOfFileNames[idx]); ReaderType * reader = static_cast<ReaderType*>(this->m_ImageFileReaderList->GetNthElement(idx)); reader->SetFileName(this->m_ListOfFileNames[idx]); ExtractSelectionType * selection = static_cast<ExtractSelectionType*>(this->m_ExtractorList->GetNthElement(idx)); selection->SetExtractionRegion(this->m_ListOfRegionSelection[idx]); for (std::vector<unsigned int>::iterator band = this->m_ListOfBandSelection[idx].begin(); band != this->m_ListOfBandSelection[idx].end(); ++band) { selection->SetChannel(*band); } selection->SetInput(reader->GetOutput()); selection->GraftOutput(this->m_OutputList->GetNthElement(idx)); selection->Update(); this->m_OutputList->GetNthElement(idx)->Graft(selection->GetOutput()); } } // end of namespace otb #endif
32.087542
95
0.700315
[ "vector" ]
2fc1b770c196c6b9cd780636aecd9de33c09e357
6,132
cpp
C++
ttk/core/vtk/ttkPersistenceDiagramsClustering/ttkPersistenceDiagramsClustering.cpp
julesvidal/wasserstein-pd-barycenter
1f62a5e1c40700030357b2bfb9a2f86fe4736861
[ "BSD-Source-Code" ]
1
2019-09-10T12:36:52.000Z
2019-09-10T12:36:52.000Z
ttk/core/vtk/ttkPersistenceDiagramsClustering/ttkPersistenceDiagramsClustering.cpp
julesvidal/wasserstein-pd-barycenter
1f62a5e1c40700030357b2bfb9a2f86fe4736861
[ "BSD-Source-Code" ]
null
null
null
ttk/core/vtk/ttkPersistenceDiagramsClustering/ttkPersistenceDiagramsClustering.cpp
julesvidal/wasserstein-pd-barycenter
1f62a5e1c40700030357b2bfb9a2f86fe4736861
[ "BSD-Source-Code" ]
1
2021-04-28T12:36:58.000Z
2021-04-28T12:36:58.000Z
#include <ttkPersistenceDiagramsClustering.h> #ifndef macroDiagramTuple #define macroDiagramTuple std::tuple<ttk::SimplexId, ttk::CriticalType, ttk::SimplexId, \ ttk::CriticalType, VTK_TT, ttk::SimplexId, \ VTK_TT, float, float, float, VTK_TT, float, float, float> #endif #ifndef macroMatchingTuple #define macroMatchingTuple std::tuple<ttk::SimplexId, ttk::SimplexId, VTK_TT> #endif using namespace std; using namespace ttk; vtkStandardNewMacro(ttkPersistenceDiagramsClustering) ttkPersistenceDiagramsClustering::ttkPersistenceDiagramsClustering(){ UseAllCores = false; WassersteinMetric = "2"; UseOutputMatching = true; NumberOfClusters=1; Deterministic = 1; ThreadNumber = 1; PairTypeClustering = -1; UseProgressive = 1; UseAccelerated = 1; UseKmeansppInit = 1; Alpha = 1; Lambda = 1; SetNumberOfInputPorts(1); SetNumberOfOutputPorts(2); } ttkPersistenceDiagramsClustering::~ttkPersistenceDiagramsClustering(){} // transmit abort signals -- to copy paste in other wrappers bool ttkPersistenceDiagramsClustering::needsToAbort(){ return GetAbortExecute(); } // transmit progress status -- to copy paste in other wrappers int ttkPersistenceDiagramsClustering::updateProgress(const float &progress){ { stringstream msg; msg << "[ttkPersistenceDiagramsClustering] " << progress*100 << "% processed...." << endl; dMsg(cout, msg.str(), advancedInfoMsg); } UpdateProgress(progress); return 0; } int ttkPersistenceDiagramsClustering::doIt(vtkDataSet** input, vtkUnstructuredGrid *outputClusters, vtkUnstructuredGrid *outputCentroids, int numInputs){ // Get arrays from input datas //vtkDataArray* inputDiagram[numInputs] = { NULL }; vector<vtkUnstructuredGrid*> inputDiagram(numInputs); for(int i=0 ; i<numInputs ; ++i){ inputDiagram[i] = vtkUnstructuredGrid::SafeDownCast(input[i]); } // Calling the executing package int dataType = inputDiagram[0]->GetCellData()->GetArray("Persistence")->GetDataType(); // TODO If Windows, we need to get rid of one pair of parenthesis switch(dataType){ vtkTemplateMacro(( { PersistenceDiagramsClustering<VTK_TT> persistenceDiagramsClustering; persistenceDiagramsClustering.setWrapper(this); string wassersteinMetric = WassersteinMetric; persistenceDiagramsClustering.setWasserstein(wassersteinMetric); persistenceDiagramsClustering.setDeterministic(Deterministic); persistenceDiagramsClustering.setPairTypeClustering(PairTypeClustering); persistenceDiagramsClustering.setNumberOfInputs(numInputs); persistenceDiagramsClustering.setDebugLevel(debugLevel_); persistenceDiagramsClustering.setTimeLimit(TimeLimit); persistenceDiagramsClustering.setUseProgressive(UseProgressive); persistenceDiagramsClustering.setThreadNumber(ThreadNumber); persistenceDiagramsClustering.setAlpha(Alpha); persistenceDiagramsClustering.setLambda(Lambda); persistenceDiagramsClustering.setNumberOfClusters(NumberOfClusters); persistenceDiagramsClustering.setUseAccelerated(UseAccelerated); persistenceDiagramsClustering.setUseKmeansppInit(UseKmeansppInit); std::vector<std::vector<macroDiagramTuple> > intermediateDiagrams(numInputs); double max_dimension_total=0; for(int i = 0; i < numInputs; i++){ double Spacing = 0; double max_dimension = getPersistenceDiagram<VTK_TT>( &(intermediateDiagrams[i]), inputDiagram[i], Spacing, 0); if(max_dimension_total<max_dimension){ max_dimension_total=max_dimension; } } persistenceDiagramsClustering.setDiagrams((void *) &intermediateDiagrams); std::vector<std::vector<macroDiagramTuple>> final_centroids; std::vector<int> inv_clustering = persistenceDiagramsClustering.execute(&final_centroids); outputClusters->ShallowCopy(createOutputClusteredDiagrams(intermediateDiagrams, inv_clustering, max_dimension_total)); outputCentroids->ShallowCopy(createOutputCentroids<VTK_TT>(&final_centroids, inv_clustering, max_dimension_total)); } )); } return 0; } int ttkPersistenceDiagramsClustering::FillInputPortInformation(int port, vtkInformation *info){ if(!this->Superclass::FillInputPortInformation(port, info)){ return 0; } info->Set(vtkAlgorithm::INPUT_IS_REPEATABLE(), 1); return 1; } int ttkPersistenceDiagramsClustering::FillOutputPortInformation(int port, vtkInformation *info){ if(!this->Superclass::FillOutputPortInformation(port, info)){ return 0; } if(port==0 || port==1 || port==3) info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkDataSet"); return 1; } // to adapt if your wrapper does not inherit from vtkDataSetAlgorithm int ttkPersistenceDiagramsClustering::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector){ Memory m; // Number of input files int numInputs = numberOfInputsFromCommandLine; // int numInputs = inputVector[0]->GetNumberOfInformationObjects(); { stringstream msg; dMsg(cout, msg.str(), infoMsg); } // Get input datas vtkDataSet* *input = new vtkDataSet*[numInputs]; for(int i=0 ; i<numInputs ; ++i) { input[i] = vtkDataSet::GetData(inputVector[i], 0); if(!input[i]){ std::cout<<"No data in input["<<i<<"]"<<std::endl; } } // TODO Set output vtkInformation* outInfo1; outInfo1 = outputVector->GetInformationObject(0); vtkDataSet* output1 = vtkDataSet::SafeDownCast(outInfo1->Get(vtkDataObject::DATA_OBJECT())); vtkUnstructuredGrid* output_clusters = vtkUnstructuredGrid::SafeDownCast(output1); vtkInformation* outInfo2; outInfo2 = outputVector->GetInformationObject(1); vtkDataSet* output2 = vtkDataSet::SafeDownCast(outInfo2->Get(vtkDataObject::DATA_OBJECT())); vtkUnstructuredGrid* output_centroids = vtkUnstructuredGrid::SafeDownCast(output2); doIt(input, output_clusters, output_centroids, numInputs); delete[] input; { stringstream msg; msg << "[ttkPersistenceDiagramsClustering] Memory usage: " << m.getElapsedUsage() << " MB." << endl; dMsg(cout, msg.str(), memoryMsg); } return 1; }
33.326087
153
0.753914
[ "vector" ]
2fc7738c4502ac4c3f21b591f399e660d7e61607
3,843
cpp
C++
reflex/ext/reflex/shape.cpp
xord/reflexion
7d864267152dca1ffeef757d0584777b16a92ede
[ "MIT" ]
3
2015-12-18T09:04:48.000Z
2022-01-04T22:21:20.000Z
reflex/ext/reflex/shape.cpp
xord/reflexion
7d864267152dca1ffeef757d0584777b16a92ede
[ "MIT" ]
null
null
null
reflex/ext/reflex/shape.cpp
xord/reflexion
7d864267152dca1ffeef757d0584777b16a92ede
[ "MIT" ]
null
null
null
#include "reflex/ruby/shape.h" #include <rays/ruby/bounds.h> #include "reflex/exception.h" #include "reflex/ruby/view.h" #include "defs.h" #include "selector.h" RUCY_DEFINE_WRAPPER_VALUE_FROM_TO(Reflex::Shape) #define THIS to<Reflex::Shape*>(self) #define CHECK RUCY_CHECK_OBJ(Reflex::Shape, self) #define CALL(fun) RUCY_CALL_SUPER(THIS, fun) static RUCY_DEF_ALLOC(alloc, klass) { Reflex::reflex_error(__FILE__, __LINE__, "can not instantiate Shape class."); } RUCY_END static RUCY_DEF0(owner) { CHECK; return value(THIS->owner()); } RUCY_END static RUCY_DEFN(set_frame) { CHECK; THIS->set_frame(to<Rays::Bounds>(argc, argv)); return value(THIS->frame()); } RUCY_END static RUCY_DEF0(get_frame) { CHECK; return value(THIS->frame()); } RUCY_END static RUCY_DEF1(set_density, density) { CHECK; THIS->set_density(to<float>(density)); return density; } RUCY_END static RUCY_DEF0(get_density) { CHECK; return value(THIS->density()); } RUCY_END static RUCY_DEF1(set_friction, friction) { CHECK; THIS->set_friction(to<float>(friction)); return friction; } RUCY_END static RUCY_DEF0(get_friction) { CHECK; return value(THIS->friction()); } RUCY_END static RUCY_DEF1(set_restitution, restitution) { CHECK; THIS->set_restitution(to<float>(restitution)); return restitution; } RUCY_END static RUCY_DEF0(get_restitution) { CHECK; return value(THIS->restitution()); } RUCY_END static RUCY_DEF1(set_sensor, state) { CHECK; THIS->set_sensor(state); return state; } RUCY_END static RUCY_DEF0(is_sensor) { CHECK; return value(THIS->is_sensor()); } RUCY_END static RUCY_DEF1(set_category_bits, bits) { CHECK; THIS->set_category_bits(to<uint>(bits)); return bits; } RUCY_END static RUCY_DEF0(get_category_bits) { CHECK; return value(THIS->category_bits()); } RUCY_END static RUCY_DEF1(set_collision_mask, mask) { CHECK; THIS->set_collision_mask(to<uint>(mask)); return mask; } RUCY_END static RUCY_DEF0(get_collision_mask) { CHECK; return value(THIS->collision_mask()); } RUCY_END static RUCY_DEF1(on_draw, event) { CHECK; CALL(on_draw(to<Reflex::DrawEvent*>(event))); } RUCY_END static RUCY_DEF1(on_contact, event) { CHECK; CALL(on_contact(to<Reflex::ContactEvent*>(event))); } RUCY_END static RUCY_DEF1(on_contact_begin, event) { CHECK; CALL(on_contact_begin(to<Reflex::ContactEvent*>(event))); } RUCY_END static RUCY_DEF1(on_contact_end, event) { CHECK; CALL(on_contact_end(to<Reflex::ContactEvent*>(event))); } RUCY_END static Class cShape; void Init_shape () { Module mReflex = define_module("Reflex"); cShape = mReflex.define_class("Shape"); cShape.define_alloc_func(alloc); cShape.define_method("owner", owner); cShape.define_method("frame=", set_frame); cShape.define_method("frame", get_frame); cShape.define_method("density=", set_density); cShape.define_method("density", get_density); cShape.define_method("friction=", set_friction); cShape.define_method("friction", get_friction); cShape.define_method("restitution=", set_restitution); cShape.define_method("restitution", get_restitution); cShape.define_method("sensor=", set_sensor); cShape.define_method("sensor", is_sensor); cShape.define_method("category_bits=", set_category_bits); cShape.define_method("category_bits", get_category_bits); cShape.define_method("collision_mask=", set_collision_mask); cShape.define_method("collision_mask", get_collision_mask); cShape.define_method("on_draw", on_draw); cShape.define_private_method("call_contact!", on_contact); cShape.define_private_method("call_contact_begin!", on_contact_begin); cShape.define_private_method("call_contact_end!", on_contact_end); define_selector_methods<Reflex::Shape>(cShape); } namespace Reflex { Class shape_class () { return cShape; } }// Reflex
16.564655
78
0.745251
[ "shape" ]
2fced6c55050bbe492ae3ffc964562917ea38288
897
hpp
C++
RubikSolver-iOS/RubikSolver-ImageProcessingEngine/Source/ColorDetector.hpp
rhcpfan/ios-rubik-solver
3429f9b0a2eee218db70a3aca7324662a6231b69
[ "MIT" ]
129
2017-03-13T12:20:38.000Z
2022-01-31T16:07:06.000Z
RubikSolver-iOS/RubikSolver-ImageProcessingEngine/Source/ColorDetector.hpp
rhcpfan/ios-rubik-solver
3429f9b0a2eee218db70a3aca7324662a6231b69
[ "MIT" ]
5
2017-03-17T10:39:23.000Z
2019-01-03T16:00:49.000Z
RubikSolver-iOS/RubikSolver-ImageProcessingEngine/Source/ColorDetector.hpp
rhcpfan/ios-rubik-solver
3429f9b0a2eee218db70a3aca7324662a6231b69
[ "MIT" ]
15
2017-03-14T06:25:20.000Z
2022-03-25T06:17:34.000Z
// // ColorDetector.hpp // RubikSolver // // Created by rhcpfan on 15/01/17. // Copyright © 2017 HomeApps. All rights reserved. // #ifndef ColorDetector_hpp #define ColorDetector_hpp #include <stdio.h> #include <opencv2/opencv.hpp> #endif /* ColorDetector_hpp */ class ColorDetector { private: std::vector<float> GetPixelFeatures(const cv::Mat &bgrImage, const cv::Mat &hsvImage, const cv::Point &location); std::vector<std::vector<float>> GetFaceFeatures(const cv::Mat& bgrImage, const cv::Mat& hsvImage); cv::Ptr<cv::ml::SVM> _svmClassifier; public: ColorDetector(); ~ColorDetector(); void TrainSVMFromImages(const std::vector<cv::Mat> &patchImages, const std::vector<std::string> colorNames); void LoadSVMFromFile(const std::string &filePath); std::vector<std::string> RecognizeColors(const cv::Mat &cubeFaceImage); };
27.181818
118
0.688963
[ "vector" ]
2fd0b9aecf722de4309565897ce7fca3341e48e6
2,204
cpp
C++
geode/force/Gravity.cpp
jjqcat/geode
157cc904c113cc5e29a1ffe7c091a83b8ec2cf8e
[ "BSD-3-Clause" ]
75
2015-02-08T22:04:31.000Z
2022-02-26T14:31:43.000Z
geode/force/Gravity.cpp
bantamtools/geode
d906f1230b14953b68af63aeec2f7b0418d5fdfd
[ "BSD-3-Clause" ]
15
2015-01-08T15:11:38.000Z
2021-09-05T13:27:22.000Z
geode/force/Gravity.cpp
bantamtools/geode
d906f1230b14953b68af63aeec2f7b0418d5fdfd
[ "BSD-3-Clause" ]
22
2015-03-11T16:43:13.000Z
2021-02-15T09:37:51.000Z
//##################################################################### // Class Gravity //##################################################################### #include <geode/force/Gravity.h> #include <geode/python/Class.h> namespace geode { typedef real T; template<> GEODE_DEFINE_TYPE(Gravity<Vector<real,3> >) template<class TV> Gravity<TV>::Gravity(Array<const T> mass) : mass(mass) { gravity[m-1] = -9.8; } template<class TV> Gravity<TV>::~Gravity() {} template<class TV> int Gravity<TV>::nodes() const { return mass.size(); } template<class TV> void Gravity<TV>::update_position(Array<const TV> X_,bool definite) { X = X_; GEODE_ASSERT(X.size()==mass.size()); } template<class TV> void Gravity<TV>::add_frequency_squared(RawArray<T> frequency_squared) const {} template<class TV> typename TV::Scalar Gravity<TV>::elastic_energy() const { T energy=0; for (int i=0;i<mass.size();i++) energy -= mass[i]*dot(gravity,X[i]); return energy; } template<class TV> void Gravity<TV>::add_elastic_force(RawArray<TV> F) const { GEODE_ASSERT(F.size()==mass.size()); for (int i=0;i<mass.size();i++) F[i] += mass[i]*gravity; } template<class TV> void Gravity<TV>::add_elastic_differential(RawArray<TV> dF,RawArray<const TV> dX) const {} template<class TV> void Gravity<TV>::add_elastic_gradient_block_diagonal(RawArray<SymmetricMatrix<T,m> > dFdX) const {} template<class TV> typename TV::Scalar Gravity<TV>::damping_energy(RawArray<const TV> V) const { return 0; } template<class TV> void Gravity<TV>::add_damping_force(RawArray<TV> force,RawArray<const TV> V) const {} template<class TV> typename TV::Scalar Gravity<TV>::strain_rate(RawArray<const TV> V) const { return 0; } template<class TV> void Gravity<TV>::structure(SolidMatrixStructure& structure) const {} template<class TV> void Gravity<TV>::add_elastic_gradient(SolidMatrix<TV>& matrix) const {} template<class TV> void Gravity<TV>::add_damping_gradient(SolidMatrix<TV>& matrix) const {} } using namespace geode; void wrap_gravity() { typedef real T; typedef Vector<T,3> TV; typedef Gravity<TV> Self; Class<Self>("Gravity") .GEODE_INIT(Array<const T>) .GEODE_FIELD(gravity) ; }
29.783784
119
0.667423
[ "vector" ]
2fd729c776804db8c9a2e07c9a2a607ccd84a406
1,455
cpp
C++
Websites/HackeEarth/hackerEarthMayEasy2.cpp
TechieErica/Algorithms
cfe3b0ba7853e57e4e594179213ef93c18a440d6
[ "MIT" ]
1
2020-05-15T02:19:19.000Z
2020-05-15T02:19:19.000Z
Websites/HackeEarth/hackerEarthMayEasy2.cpp
Ergerica/Algorithms
cfe3b0ba7853e57e4e594179213ef93c18a440d6
[ "MIT" ]
null
null
null
Websites/HackeEarth/hackerEarthMayEasy2.cpp
Ergerica/Algorithms
cfe3b0ba7853e57e4e594179213ef93c18a440d6
[ "MIT" ]
null
null
null
//https://www.hackerearth.com/submission/25990669/ Hacker earth extra points 0.16 points #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi ; typedef vector<string> vs ; typedef vector<long long> vl ; #define FOR(i,a,b) for(int i=a;i<b;++i) #define rep(i,n) FOR(i,0,n) ll minn = 1000000001,n; bool check(ll key,ll i, ll j) { if((key*abs(i-j)) > minn) return true; return false; } ll binary_search_first_yes( ll lo, ll hi,ll i,ll j ) { // Find smallest x such that check(x) is true while (lo < hi) { ll mid = lo + (hi-lo)/2; if ( check(mid,i,j) ) hi = mid; else lo = mid+1; } assert( check(lo,i,j) ); // abort if check(x) is false for all x return lo; // lo is the least x for which check(x) is true } int main() { int t; cin>>t; vl lol; lol.push_back(0); ll minn = 0; rep(i,t) { int num; cin>>num; if(num==1) { ll p; cin>>p; lol.push_back(p); minn = min(p,minn); } if(num==2) { int r; cin>>r; minn = 1000000000001; rep(i,lol.size()) { lol[i] = lol[i]^r; minn = min(minn,lol[i]); } } if(num==3) { cout<<minn<<endl; } } return 0; }
21.397059
93
0.470103
[ "vector" ]
7c841dda58885240753ff69b7ebae8c88534ecd8
5,186
cpp
C++
Game/graphics/worldview.cpp
djeada/OpenGothic
a10fc3dd7a296a96b72bb8d3f9cf3b40da992580
[ "MIT" ]
1
2020-07-03T22:51:15.000Z
2020-07-03T22:51:15.000Z
Game/graphics/worldview.cpp
djeada/OpenGothic
a10fc3dd7a296a96b72bb8d3f9cf3b40da992580
[ "MIT" ]
null
null
null
Game/graphics/worldview.cpp
djeada/OpenGothic
a10fc3dd7a296a96b72bb8d3f9cf3b40da992580
[ "MIT" ]
null
null
null
#include "worldview.h" #include <Tempest/Application> #include "world/world.h" #include "rendererstorage.h" #include "graphics/submesh/packedmesh.h" #include "graphics/dynamic/painter3d.h" using namespace Tempest; WorldView::WorldView(const World &world, const PackedMesh &wmesh, const RendererStorage &storage) : owner(world),storage(storage),sGlobal(storage),visuals(sGlobal), objGroup(visuals),pfxGroup(sGlobal,visuals),land(*this,visuals,wmesh) { visuals.setWorld(owner); pfxGroup.resetTicks(); } WorldView::~WorldView() { // cmd buffers must not be in use storage.device.waitIdle(); } void WorldView::initPipeline(uint32_t w, uint32_t h) { proj.perspective(45.0f, float(w)/float(h), 0.05f, 100.0f); vpWidth = w; vpHeight = h; } Matrix4x4 WorldView::viewProj(const Matrix4x4 &view) const { auto viewProj=proj; viewProj.mul(view); return viewProj; } const Light &WorldView::mainLight() const { return sGlobal.sun; } void WorldView::tick(uint64_t /*dt*/) { auto pl = owner.player(); if(pl!=nullptr) { pfxGroup.setViewerPos(pl->position()); } } void WorldView::addLight(const ZenLoad::zCVobData& vob) { uint8_t cl[4]; std::memcpy(cl,&vob.zCVobLight.color,4); Light l; l.setPosition(Vec3(vob.position.x,vob.position.y,vob.position.z)); l.setColor (Vec3(cl[2]/255.f,cl[1]/255.f,cl[1]/255.f)); l.setRange (vob.zCVobLight.range); pendingLights.push_back(l); } void WorldView::setupSunDir(float pulse,float ang) { float a = 360-360*ang; a = a*float(M_PI/180.0); sGlobal.sun.setDir(std::cos(a),std::min(0.9f,-1.0f*pulse),std::sin(a)); } void WorldView::setModelView(const Matrix4x4& view, const Tempest::Matrix4x4* shadow, size_t shCount) { updateLight(); sGlobal.setModelView(viewProj(view),shadow,shCount); } void WorldView::setFrameGlobals(const Texture2d& shadow, uint64_t tickCount, uint8_t fId) { if(pendingLights.size()!=sGlobal.lights.size()) { sGlobal.lights.set(pendingLights); // wait before update all descriptors sGlobal.storage.device.waitIdle(); visuals.setupUbo(); } if(&shadow!=sGlobal.shadowMap) { // wait before update all descriptors sGlobal.storage.device.waitIdle(); sGlobal.setShadowmMap(shadow); visuals.setupUbo(); } pfxGroup.tick(tickCount); sGlobal .setTime(tickCount); sGlobal .commitUbo(fId); visuals .preFrameUpdate(fId); pfxGroup.preFrameUpdate(fId); } void WorldView::drawShadow(Tempest::Encoder<CommandBuffer>& cmd, Painter3d& painter, uint8_t fId, uint8_t layer) { visuals.drawShadow(painter,cmd,fId,layer); } void WorldView::drawMain(Tempest::Encoder<CommandBuffer>& cmd, Painter3d& painter, uint8_t fId) { visuals.draw(painter,cmd,fId); } MeshObjects::Mesh WorldView::getView(const char* visual, int32_t headTex, int32_t teethTex, int32_t bodyColor) { if(auto mesh=Resources::loadMesh(visual)) return objGroup.get(*mesh,headTex,teethTex,bodyColor,false); return MeshObjects::Mesh(); } MeshObjects::Mesh WorldView::getItmView(const char* visual, int32_t material) { if(auto mesh=Resources::loadMesh(visual)) return objGroup.get(*mesh,material,0,0,true); return MeshObjects::Mesh(); } MeshObjects::Mesh WorldView::getAtachView(const ProtoMesh::Attach& visual) { return objGroup.get(visual,false); } MeshObjects::Mesh WorldView::getStaticView(const char* visual) { if(auto mesh=Resources::loadMesh(visual)) return objGroup.get(*mesh,0,0,0,true); return MeshObjects::Mesh(); } MeshObjects::Mesh WorldView::getDecalView(const ZenLoad::zCVobData& vob, const Tempest::Matrix4x4& obj, ProtoMesh& out) { out = owner.physic()->decalMesh(vob,obj); return objGroup.get(out,0,0,0,true); } PfxObjects::Emitter WorldView::getView(const ParticleFx *decl) { if(decl!=nullptr) return pfxGroup.get(*decl); return PfxObjects::Emitter(); } PfxObjects::Emitter WorldView::getView(const ZenLoad::zCVobData& vob) { return pfxGroup.get(vob); } void WorldView::updateLight() { const int64_t rise = gtime(3,1).toInt(); const int64_t meridian = gtime(11,46).toInt(); const int64_t set = gtime(20,32).toInt(); const int64_t midnight = gtime(1,0,0).toInt(); const int64_t now = owner.time().timeInDay().toInt(); float pulse = 0.f; if(rise<=now && now<meridian){ pulse = 0.f + float(now-rise)/float(meridian-rise); } else if(meridian<=now && now<set){ pulse = 1.f - float(now-meridian)/float(set-meridian); } else if(set<=now){ pulse = 0.f - float(now-set)/float(midnight-set); } else if(now<rise){ pulse = -1.f + (float(now)/float(rise)); } float k = float(now)/float(midnight); float a = std::max(0.f,std::min(pulse*3.f,1.f)); auto clr = Vec3(0.75f,0.75f,0.75f)*a; sGlobal.ambient = Vec3(0.2f,0.2f,0.3f)*(1.f-a)+Vec3(0.25f,0.25f,0.25f)*a; setupSunDir(pulse,std::fmod(k+0.25f,1.f)); sGlobal.sun.setColor(clr); visuals.setDayNight(std::min(std::max(pulse*3.f,0.f),1.f)); } void WorldView::resetCmd() { // cmd buffers must not be in use storage.device.waitIdle(); mainLay = nullptr; shadowLay = nullptr; }
29.134831
114
0.688392
[ "mesh" ]
7c844794c41d0bb69633ab033b8600374ac0ea8c
447
cpp
C++
ARRAYS/Easy/Check if the Sentence Is Pangram/Code.cpp
HassanRahim26/LEETCODE
c0ec81b037ff7b2d6e6030ac9835c21ed825100f
[ "MIT" ]
3
2021-08-31T11:02:28.000Z
2022-01-17T08:07:00.000Z
ARRAYS/Easy/Check if the Sentence Is Pangram/Code.cpp
HassanRahim26/LEETCODE
c0ec81b037ff7b2d6e6030ac9835c21ed825100f
[ "MIT" ]
null
null
null
ARRAYS/Easy/Check if the Sentence Is Pangram/Code.cpp
HassanRahim26/LEETCODE
c0ec81b037ff7b2d6e6030ac9835c21ed825100f
[ "MIT" ]
null
null
null
/* PROBLEM LINK:- https://leetcode.com/problems/check-if-the-sentence-is-pangram/ */ class Solution { public: bool checkIfPangram(string str) { int n = str.size(); vector v(26,0); for(int i = 0; i < n; i++) { v[str[i]-'a']++; } for(int i = 0; i < v.size(); i++) { if(v[i] == 0) return false; } return true; } };
18.625
78
0.418345
[ "vector" ]
7c8741663e0bfa21bd7a26ac8df5ee01cf0cf033
2,096
hpp
C++
src/plugins/intel_gna/layers/gna_crop_layer.hpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/plugins/intel_gna/layers/gna_crop_layer.hpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/plugins/intel_gna/layers/gna_crop_layer.hpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <legacy/ie_layers.h> #include "gna_graph_tools.hpp" namespace GNAPluginNS { class GNACropLayer { InferenceEngine::CNNLayerPtr cropLayer; public: explicit GNACropLayer(InferenceEngine::CNNLayerPtr layer) : cropLayer(layer) {} InferenceEngine::CNNLayerPtr getCrop() { return cropLayer; } /** * pointer to gna croped memory beginning */ void *gna_ptr = nullptr; }; /** * @brief returns parameters extracted from Crop layer: elements offset, elements output size and axes * @param cropLayer pointer to a Crop layer */ inline std::tuple<size_t, size_t, std::vector<int32_t>> GetCropParams(InferenceEngine::CropLayer* cropLayer) { IE_ASSERT(!cropLayer->axis.empty()); IE_ASSERT(cropLayer->axis.size() == cropLayer->dim.size()); IE_ASSERT(cropLayer->axis.size() == cropLayer->offset.size()); std::vector<int> axis, dim, offset; auto inputs = cropLayer->insData.begin()->lock(); for (int n = 0; n < cropLayer->axis.size(); n++) { uint32_t input_dim = GetDataDimSize(inputs, inputs->getDims().size() - cropLayer->axis[n]); // Exclude crop layer components that do nothing if (cropLayer->offset[n] == 0 && cropLayer->dim[n] == input_dim) { continue; } axis.push_back(cropLayer->axis[n]); dim.push_back(cropLayer->dim[n]); offset.push_back(cropLayer->offset[n]); } if (axis.size() != 1) { THROW_GNA_EXCEPTION << "Crop layer does not support the number of (non-trivial) cropped dimensions more than 1, provided: " << axis.size() << "."; } size_t cropOffset = offset.front(); size_t cropOutputSize = dim.front(); // fix for crop on tensor dim > 2D for (int n = axis[0]+1; n < cropLayer->dim.size(); n++) { cropOffset *= cropLayer->dim[n]; cropOutputSize *= cropLayer->dim[n]; } return std::make_tuple(cropOffset, cropOutputSize, axis); } } // namespace GNAPluginNS
30.823529
112
0.643607
[ "vector" ]
7c8e9b0a87d3001e793317631b8578c1f6d33e20
427
cpp
C++
leetcode/archives_am/852.peak-index-in-a-mountain-array.cpp
saurabhraj042/dsaPrep
0973a03bc565a2850003c7e48d99b97ff83b1d01
[ "MIT" ]
23
2021-10-30T04:11:52.000Z
2021-11-27T09:16:18.000Z
leetcode/archives_am/852.peak-index-in-a-mountain-array.cpp
saurabhraj042/dsaPrep
0973a03bc565a2850003c7e48d99b97ff83b1d01
[ "MIT" ]
null
null
null
leetcode/archives_am/852.peak-index-in-a-mountain-array.cpp
saurabhraj042/dsaPrep
0973a03bc565a2850003c7e48d99b97ff83b1d01
[ "MIT" ]
4
2021-10-30T03:26:05.000Z
2021-11-14T12:15:04.000Z
// https://leetcode.com/problems/peak-index-in-a-mountain-array/ class Solution { public: int peakIndexInMountainArray(vector<int>& a) { int l = 0; int h = size(a) - 1; while(l < h){ int m = (l + h) / 2; if(a[m] < a[m+1]){ l = m + 1; } else { h = m; } } return l; } };
21.35
64
0.367681
[ "vector" ]
7c9626337adbf9a5e4cf475a429712bc6ba51f29
21,950
cpp
C++
util/test/demos/d3d11/d3d11_pixel_history_zoo.cpp
orsonbraines/renderdoc
ed9ac9f7bf594f79f834ce8fa0b9717b69d13b0e
[ "MIT" ]
1
2022-02-17T21:18:24.000Z
2022-02-17T21:18:24.000Z
util/test/demos/d3d11/d3d11_pixel_history_zoo.cpp
orsonbraines/renderdoc
ed9ac9f7bf594f79f834ce8fa0b9717b69d13b0e
[ "MIT" ]
null
null
null
util/test/demos/d3d11/d3d11_pixel_history_zoo.cpp
orsonbraines/renderdoc
ed9ac9f7bf594f79f834ce8fa0b9717b69d13b0e
[ "MIT" ]
null
null
null
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2022 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "d3d11_test.h" const std::string dxgiFormatName[] = { "DXGI_FORMAT_UNKNOWN", "DXGI_FORMAT_R32G32B32A32_TYPELESS", "DXGI_FORMAT_R32G32B32A32_FLOAT", "DXGI_FORMAT_R32G32B32A32_UINT", "DXGI_FORMAT_R32G32B32A32_SINT", "DXGI_FORMAT_R32G32B32_TYPELESS", "DXGI_FORMAT_R32G32B32_FLOAT", "DXGI_FORMAT_R32G32B32_UINT", "DXGI_FORMAT_R32G32B32_SINT", "DXGI_FORMAT_R16G16B16A16_TYPELESS", "DXGI_FORMAT_R16G16B16A16_FLOAT", "DXGI_FORMAT_R16G16B16A16_UNORM", "DXGI_FORMAT_R16G16B16A16_UINT", "DXGI_FORMAT_R16G16B16A16_SNORM", "DXGI_FORMAT_R16G16B16A16_SINT", "DXGI_FORMAT_R32G32_TYPELESS", "DXGI_FORMAT_R32G32_FLOAT", "DXGI_FORMAT_R32G32_UINT", "DXGI_FORMAT_R32G32_SINT", "DXGI_FORMAT_R32G8X24_TYPELESS", "DXGI_FORMAT_D32_FLOAT_S8X24_UINT", "DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS", "DXGI_FORMAT_X32_TYPELESS_G8X24_UINT", "DXGI_FORMAT_R10G10B10A2_TYPELESS", "DXGI_FORMAT_R10G10B10A2_UNORM", "DXGI_FORMAT_R10G10B10A2_UINT", "DXGI_FORMAT_R11G11B10_FLOAT", "DXGI_FORMAT_R8G8B8A8_TYPELESS", "DXGI_FORMAT_R8G8B8A8_UNORM", "DXGI_FORMAT_R8G8B8A8_UNORM_SRGB", "DXGI_FORMAT_R8G8B8A8_UINT", "DXGI_FORMAT_R8G8B8A8_SNORM", "DXGI_FORMAT_R8G8B8A8_SINT", "DXGI_FORMAT_R16G16_TYPELESS", "DXGI_FORMAT_R16G16_FLOAT", "DXGI_FORMAT_R16G16_UNORM", "DXGI_FORMAT_R16G16_UINT", "DXGI_FORMAT_R16G16_SNORM", "DXGI_FORMAT_R16G16_SINT", "DXGI_FORMAT_R32_TYPELESS", "DXGI_FORMAT_D32_FLOAT", "DXGI_FORMAT_R32_FLOAT", "DXGI_FORMAT_R32_UINT", "DXGI_FORMAT_R32_SINT", "DXGI_FORMAT_R24G8_TYPELESS", "DXGI_FORMAT_D24_UNORM_S8_UINT", "DXGI_FORMAT_R24_UNORM_X8_TYPELESS", "DXGI_FORMAT_X24_TYPELESS_G8_UINT", "DXGI_FORMAT_R8G8_TYPELESS", "DXGI_FORMAT_R8G8_UNORM", "DXGI_FORMAT_R8G8_UINT", "DXGI_FORMAT_R8G8_SNORM", "DXGI_FORMAT_R8G8_SINT", "DXGI_FORMAT_R16_TYPELESS", "DXGI_FORMAT_R16_FLOAT", "DXGI_FORMAT_D16_UNORM", "DXGI_FORMAT_R16_UNORM", "DXGI_FORMAT_R16_UINT", "DXGI_FORMAT_R16_SNORM", "DXGI_FORMAT_R16_SINT", "DXGI_FORMAT_R8_TYPELESS", "DXGI_FORMAT_R8_UNORM", "DXGI_FORMAT_R8_UINT", "DXGI_FORMAT_R8_SNORM", "DXGI_FORMAT_R8_SINT", "DXGI_FORMAT_A8_UNORM", "DXGI_FORMAT_R1_UNORM", "DXGI_FORMAT_R9G9B9E5_SHAREDEXP", "DXGI_FORMAT_R8G8_B8G8_UNORM", "DXGI_FORMAT_G8R8_G8B8_UNORM", "DXGI_FORMAT_BC1_TYPELESS", "DXGI_FORMAT_BC1_UNORM", "DXGI_FORMAT_BC1_UNORM_SRGB", "DXGI_FORMAT_BC2_TYPELESS", "DXGI_FORMAT_BC2_UNORM", "DXGI_FORMAT_BC2_UNORM_SRGB", "DXGI_FORMAT_BC3_TYPELESS", "DXGI_FORMAT_BC3_UNORM", "DXGI_FORMAT_BC3_UNORM_SRGB", "DXGI_FORMAT_BC4_TYPELESS", "DXGI_FORMAT_BC4_UNORM", "DXGI_FORMAT_BC4_SNORM", "DXGI_FORMAT_BC5_TYPELESS", "DXGI_FORMAT_BC5_UNORM", "DXGI_FORMAT_BC5_SNORM", "DXGI_FORMAT_B5G6R5_UNORM", "DXGI_FORMAT_B5G5R5A1_UNORM", "DXGI_FORMAT_B8G8R8A8_UNORM", "DXGI_FORMAT_B8G8R8X8_UNORM", "DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM", "DXGI_FORMAT_B8G8R8A8_TYPELESS", "DXGI_FORMAT_B8G8R8A8_UNORM_SRGB", "DXGI_FORMAT_B8G8R8X8_TYPELESS", "DXGI_FORMAT_B8G8R8X8_UNORM_SRGB", "DXGI_FORMAT_BC6H_TYPELESS", "DXGI_FORMAT_BC6H_UF16", "DXGI_FORMAT_BC6H_SF16", "DXGI_FORMAT_BC7_TYPELESS", "DXGI_FORMAT_BC7_UNORM", "DXGI_FORMAT_BC7_UNORM_SRGB", "DXGI_FORMAT_AYUV", "DXGI_FORMAT_Y410", "DXGI_FORMAT_Y416", "DXGI_FORMAT_NV12", "DXGI_FORMAT_P010", "DXGI_FORMAT_P016", "DXGI_FORMAT_420_OPAQUE", "DXGI_FORMAT_YUY2", "DXGI_FORMAT_Y210", "DXGI_FORMAT_Y216", "DXGI_FORMAT_NV11", "DXGI_FORMAT_AI44", "DXGI_FORMAT_IA44", "DXGI_FORMAT_P8", "DXGI_FORMAT_A8P8", "DXGI_FORMAT_B4G4R4A4_UNORM", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "DXGI_FORMAT_P208", "DXGI_FORMAT_V208", "DXGI_FORMAT_V408", }; RD_TEST(D3D11_Pixel_History_Zoo, D3D11GraphicsTest) { static constexpr const char *Description = "Checks pixel history on different formats, scenarios, overdraw, etc."; bool IsUIntFormat(DXGI_FORMAT f) { switch(f) { case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32_UINT: case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R32G32_UINT: case DXGI_FORMAT_R10G10B10A2_UINT: case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R16G16_UINT: case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R8G8_UINT: case DXGI_FORMAT_R16_UINT: case DXGI_FORMAT_R8_UINT: return true; default: break; } return false; } bool IsSIntFormat(DXGI_FORMAT f) { switch(f) { case DXGI_FORMAT_R32G32B32A32_SINT: case DXGI_FORMAT_R32G32B32_SINT: case DXGI_FORMAT_R16G16B16A16_SINT: case DXGI_FORMAT_R32G32_SINT: case DXGI_FORMAT_R8G8B8A8_SINT: case DXGI_FORMAT_R16G16_SINT: case DXGI_FORMAT_R32_SINT: case DXGI_FORMAT_R8G8_SINT: case DXGI_FORMAT_R16_SINT: case DXGI_FORMAT_R8_SINT: return true; default: break; } return false; } DXGI_FORMAT GetTypelessFormat(DXGI_FORMAT f) { switch(f) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: return DXGI_FORMAT_R32G32B32A32_TYPELESS; case DXGI_FORMAT_R32G32B32_TYPELESS: case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R32G32B32_UINT: case DXGI_FORMAT_R32G32B32_SINT: return DXGI_FORMAT_R32G32B32_TYPELESS; case DXGI_FORMAT_R16G16B16A16_TYPELESS: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R16G16B16A16_SINT: return DXGI_FORMAT_R16G16B16A16_TYPELESS; case DXGI_FORMAT_R32G32_TYPELESS: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R32G32_UINT: case DXGI_FORMAT_R32G32_SINT: return DXGI_FORMAT_R32G32_TYPELESS; case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: return DXGI_FORMAT_R32G8X24_TYPELESS; case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_UINT: case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: // maybe not valid cast? return DXGI_FORMAT_R10G10B10A2_TYPELESS; case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R8G8B8A8_SINT: return DXGI_FORMAT_R8G8B8A8_TYPELESS; case DXGI_FORMAT_R16G16_TYPELESS: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_UINT: case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R16G16_SINT: return DXGI_FORMAT_R16G16_TYPELESS; case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_D32_FLOAT: // maybe not valid cast? case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: return DXGI_FORMAT_R32_TYPELESS; // maybe not valid casts? case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_D24_UNORM_S8_UINT: case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: case DXGI_FORMAT_X24_TYPELESS_G8_UINT: return DXGI_FORMAT_R24G8_TYPELESS; case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_R8G8_B8G8_UNORM: // maybe not valid cast? case DXGI_FORMAT_G8R8_G8B8_UNORM: // maybe not valid cast? return DXGI_FORMAT_B8G8R8A8_TYPELESS; case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8X8_TYPELESS: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8X8_TYPELESS; case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_UINT: case DXGI_FORMAT_R8G8_SNORM: case DXGI_FORMAT_R8G8_SINT: return DXGI_FORMAT_R8G8_TYPELESS; case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_D16_UNORM: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R16_UINT: case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R16_SINT: return DXGI_FORMAT_R16_TYPELESS; case DXGI_FORMAT_R8_TYPELESS: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_UINT: case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_R8_SINT: return DXGI_FORMAT_R8_TYPELESS; case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: return DXGI_FORMAT_BC1_TYPELESS; case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: return DXGI_FORMAT_BC4_TYPELESS; case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: return DXGI_FORMAT_BC2_TYPELESS; case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: return DXGI_FORMAT_BC3_TYPELESS; case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: return DXGI_FORMAT_BC5_TYPELESS; case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16: return DXGI_FORMAT_BC6H_TYPELESS; case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: return DXGI_FORMAT_BC7_TYPELESS; case DXGI_FORMAT_R1_UNORM: case DXGI_FORMAT_A8_UNORM: case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: case DXGI_FORMAT_B5G6R5_UNORM: case DXGI_FORMAT_B5G5R5A1_UNORM: case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_AYUV: case DXGI_FORMAT_Y410: case DXGI_FORMAT_YUY2: case DXGI_FORMAT_Y416: case DXGI_FORMAT_NV12: case DXGI_FORMAT_P010: case DXGI_FORMAT_P016: case DXGI_FORMAT_420_OPAQUE: case DXGI_FORMAT_Y210: case DXGI_FORMAT_Y216: case DXGI_FORMAT_NV11: case DXGI_FORMAT_AI44: case DXGI_FORMAT_IA44: case DXGI_FORMAT_P8: case DXGI_FORMAT_A8P8: case DXGI_FORMAT_P208: case DXGI_FORMAT_V208: case DXGI_FORMAT_V408: case DXGI_FORMAT_B4G4R4A4_UNORM: return f; case DXGI_FORMAT_UNKNOWN: return DXGI_FORMAT_UNKNOWN; default: return DXGI_FORMAT_UNKNOWN; } } std::string vertex = R"EOSHADER( struct vertin { float3 pos : POSITION; float4 col : COLOR0; float2 uv : TEXCOORD0; }; struct v2f { float4 pos : SV_POSITION; float4 col : COLOR0; float2 uv : TEXCOORD0; }; v2f main(vertin IN, uint vid : SV_VertexID) { v2f OUT = (v2f)0; OUT.pos = float4(IN.pos.xy, 0.5f, 1.0f); OUT.col = IN.col; OUT.uv = IN.uv; return OUT; } )EOSHADER"; std::string pixel = R"EOSHADER( cbuffer refcounter : register(b0) { uint expected; }; cbuffer uavcounter : register(b1) { uint actual; }; float4 main() : SV_Target0 { if(expected != actual) return float4(1.0f, 0.0f, 0.0f, 1.0f); return float4(0.0f, 1.0f, 0.1234f, 0.5f); } )EOSHADER"; std::string pixelUInt = R"EOSHADER( cbuffer refcounter : register(b0) { uint expected; }; cbuffer uavcounter : register(b1) { uint actual; }; uint4 main() : SV_Target0 { if(expected != actual) return uint4(1, 0, 0, 1); return uint4(0, 1, 1234, 5); } )EOSHADER"; std::string pixelSInt = R"EOSHADER( cbuffer refcounter : register(b0) { uint expected; }; cbuffer uavcounter : register(b1) { uint actual; }; int4 main() : SV_Target0 { if(expected != actual) return int4(1, 0, 0, 1); return int4(0, 1, -1234, 5); } )EOSHADER"; std::string compute = R"EOSHADER( RWBuffer<uint> buf : register(u0); [numthreads(1,1,1)] void main() { InterlockedAdd(buf[0], 1); } )EOSHADER"; int main() { // initialise, create window, create device, etc if(!Init()) return 3; ID3DBlobPtr vsblob = Compile(vertex, "main", "vs_4_0"); CreateDefaultInputLayout(vsblob); ID3D11VertexShaderPtr vs = CreateVS(vsblob); ID3D11PixelShaderPtr ps = CreatePS(Compile(pixel, "main", "ps_4_0")); ID3D11PixelShaderPtr psUInt = CreatePS(Compile(pixelUInt, "main", "ps_4_0")); ID3D11PixelShaderPtr psSInt = CreatePS(Compile(pixelSInt, "main", "ps_4_0")); ID3D11ComputeShaderPtr cs = CreateCS(Compile(compute, "main", "cs_5_0")); ID3D11BufferPtr vb = MakeBuffer().Vertex().Data(DefaultTri); const DXGI_FORMAT depthFormats[] = { DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, }; const DXGI_FORMAT dsvFormats[] = { DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, }; static_assert(sizeof(depthFormats) == sizeof(dsvFormats), "depth arrays should be identical sizes."); ID3D11BufferPtr bufRef = MakeBuffer().Size(256).Constant(); ID3D11BufferPtr bufCounter = MakeBuffer().Size(256).UAV(); ID3D11BufferPtr bufCounterCB = MakeBuffer().Size(256).Constant(); ID3D11UnorderedAccessViewPtr bufCounterUAV = MakeUAV(bufCounter).Format(DXGI_FORMAT_R32_UINT); ctx->CSSetUnorderedAccessViews(0, 1, &bufCounterUAV.GetInterfacePtr(), NULL); ctx->CSSetShader(cs, NULL, 0); std::vector<ID3D11DepthStencilViewPtr> dsvs; std::vector<ID3D11RenderTargetViewPtr> rts; for(size_t i = 0; i < ARRAY_COUNT(dsvFormats); i++) { // normal dsvs.push_back( MakeDSV(MakeTexture(depthFormats[i], 16, 16).DSV().Tex2D()).Format(dsvFormats[i])); // submip and subslice selected dsvs.push_back(MakeDSV(MakeTexture(depthFormats[i], 32, 32).Array(32).DSV().Mips(2).Tex2D()) .Format(dsvFormats[i]) .FirstMip(1) .NumMips(1) .FirstSlice(4) .NumSlices(1)); } const DXGI_FORMAT colorFormats[] = { DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32B32A32_UINT, DXGI_FORMAT_R32G32B32A32_SINT, DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32B32_UINT, DXGI_FORMAT_R32G32B32_SINT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_UNORM, DXGI_FORMAT_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_SNORM, DXGI_FORMAT_R16G16B16A16_SINT, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32G32_UINT, DXGI_FORMAT_R32G32_SINT, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R10G10B10A2_UINT, DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R8G8B8A8_SNORM, DXGI_FORMAT_R8G8B8A8_SINT, DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_UNORM, DXGI_FORMAT_R16G16_UINT, DXGI_FORMAT_R16G16_SNORM, DXGI_FORMAT_R16G16_SINT, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_SINT, DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R8G8_UINT, DXGI_FORMAT_R8G8_SNORM, DXGI_FORMAT_R8G8_SINT, DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R16_SNORM, DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8_UINT, DXGI_FORMAT_R8_SNORM, DXGI_FORMAT_R8_SINT, DXGI_FORMAT_A8_UNORM, DXGI_FORMAT_R1_UNORM, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB, DXGI_FORMAT_B4G4R4A4_UNORM, }; for(size_t i = 0; i < ARRAY_COUNT(colorFormats); i++) { DXGI_FORMAT f = colorFormats[i]; UINT supp = 0; dev->CheckFormatSupport(f, &supp); if((supp & D3D11_FORMAT_SUPPORT_RENDER_TARGET) == 0) continue; std::vector<DXGI_FORMAT> fmts = {f}; // test typeless->casted for the first three (RGBA32) if(i < 3) fmts.push_back(GetTypelessFormat(f)); for(DXGI_FORMAT tex_fmt : fmts) { // make a normal one rts.push_back(MakeRTV(MakeTexture(tex_fmt, 16, 16).RTV().Tex2D()).Format(f)); // make a subslice and submip one rts.push_back(MakeRTV(MakeTexture(tex_fmt, 32, 32).Array(32).Mips(2).RTV().Tex2D()) .Format(f) .FirstMip(1) .NumMips(1) .FirstSlice(4) .NumSlices(1)); } } // make a simple dummy texture for MRT testing ID3D11RenderTargetViewPtr mrt = MakeRTV(MakeTexture(DXGI_FORMAT_R8G8B8A8_UNORM, 16, 16).RTV().Tex2D()); while(Running()) { ClearRenderTargetView(bbRTV, {0.2f, 0.2f, 0.2f, 1.0f}); IASetVertexBuffer(vb, sizeof(DefaultA2V), 0); ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); ctx->IASetInputLayout(defaultLayout); ctx->VSSetShader(vs, NULL, 0); ctx->PSSetShader(ps, NULL, 0); RSSetViewport({0.0f, 0.0f, 16.0f, 16.0f, 0.0f, 1.0f}); UINT zero[4] = {}; ctx->ClearUnorderedAccessViewUint(bufCounterUAV, zero); uint32_t testCounter = 0; // for each DSV and for none for(size_t dsvIdx = 0; dsvIdx <= dsvs.size(); dsvIdx++) { ID3D11DepthStencilViewPtr dsv = dsvIdx < dsvs.size() ? dsvs[dsvIdx] : NULL; DXGI_FORMAT df = DXGI_FORMAT_UNKNOWN; if(dsv) { D3D11_DEPTH_STENCIL_VIEW_DESC desc; dsv->GetDesc(&desc); df = desc.Format; } // for each RT for(size_t rtIdx = 0; rtIdx < rts.size(); rtIdx++) { ID3D11RenderTargetViewPtr rt = rts[rtIdx]; ID3D11RenderTargetViewPtr dummy = mrt; DXGI_FORMAT f = DXGI_FORMAT_UNKNOWN; { D3D11_RENDER_TARGET_VIEW_DESC desc; rt->GetDesc(&desc); f = desc.Format; } // for all but the first DSV and the last (none) DSV, skip the bulk of the colour tests to // reduce the test matrix. if(dsvIdx > 0 && dsvIdx < dsvs.size()) { if(rtIdx > 10) break; } pushMarker("Test RTV: " + dxgiFormatName[f] + " & depth: " + (df == DXGI_FORMAT_UNKNOWN ? "None" : dxgiFormatName[df])); ctx->OMSetRenderTargets(1, &rt.GetInterfacePtr(), dsv); // dispatch the CS to increment the buffer counter on the GPU ctx->Dispatch(1, 1, 1); // increment the CPU counter testCounter++; // update CBs so we can check for validity uint32_t data[256 / 4]; data[0] = testCounter; ctx->UpdateSubresource(bufRef, 0, NULL, data, 256, 256); ctx->CopyResource(bufCounterCB, bufCounter); ctx->PSSetConstantBuffers(0, 1, &bufRef.GetInterfacePtr()); ctx->PSSetConstantBuffers(1, 1, &bufCounterCB.GetInterfacePtr()); setMarker("Test " + std::to_string(testCounter)); if(IsUIntFormat(f)) { setMarker("UInt tex"); ctx->PSSetShader(psUInt, NULL, 0); } else if(IsSIntFormat(f)) { setMarker("SInt tex"); ctx->PSSetShader(psSInt, NULL, 0); } else { setMarker("Float tex"); ctx->PSSetShader(ps, NULL, 0); } if(dsv) { setMarker("DSVClear"); ctx->ClearDepthStencilView(dsv, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); } setMarker("RTVClear"); ClearRenderTargetView(rt, Vec4f(1.0f, 0.0f, 1.0f, 1.0f)); setMarker("BasicDraw"); ctx->Draw(3, 0); popMarker(); } } Present(); } return 0; } }; REGISTER_TEST();
29.782904
100
0.680729
[ "vector" ]
7c9d2b57ac9927ba214d9e4f04db2b983ebab617
1,543
cpp
C++
minpro2017/c.cpp
nel215/atcoder-grand-contest
a13ce146516c03881f50b7ac284be23d16d29ffe
[ "MIT" ]
null
null
null
minpro2017/c.cpp
nel215/atcoder-grand-contest
a13ce146516c03881f50b7ac284be23d16d29ffe
[ "MIT" ]
null
null
null
minpro2017/c.cpp
nel215/atcoder-grand-contest
a13ce146516c03881f50b7ac284be23d16d29ffe
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <fstream> #include <string> #include <vector> #include <list> #include <set> #include <map> #include <queue> #include <stack> #include <deque> #include <complex> #include <algorithm> #include <cstdio> #include <cmath> #include <cstring> #define REP(i,x) for(int i=0 ; i<(int)(x) ; i++) #define ALL(x) (x).begin(),(x).end() #define LL long long using namespace std; int main(){ int N, K; cin >> N >> K; vector<int> req(N); REP(i, K){ int a; cin >> a; a--; req[a] = 1; } vector<string> S(N); string max_req = ""; REP(i, N){ cin >> S[i]; if(!req[i])continue; if(max_req.size() < S[i].size()){ max_req = S[i]; } } queue<int> que; REP(i, N){ que.push(i); } string res = ""; int satisfy = N; bool ok = true; REP(idx, max_req.size()){ // cerr << ok << " " << satisfy << " " << expire.size() << " " << que.size() << endl; if(satisfy==K || !ok)break; queue<int> nque; char c = max_req[idx]; while(!que.empty()){ int i = que.front();que.pop(); if(idx==(int)S[i].size() || S[i][idx]!=c){ satisfy--; if(req[i])ok = false; }else{ nque.push(i); } } if(satisfy<K)ok = false; que = nque; res += c; } ok = ok && (satisfy == K); cout << (ok ? res : "-1") << endl; return 0; }
20.851351
93
0.456902
[ "vector" ]
7cab94a20de3a1cf0e5d9be5fc1e589dcf81c1b5
18,166
cpp
C++
src/sendData.cpp
lbussy/tiltbridge
eef5406c4eb598febe4e22651dacfef24b63efd8
[ "Apache-2.0" ]
null
null
null
src/sendData.cpp
lbussy/tiltbridge
eef5406c4eb598febe4e22651dacfef24b63efd8
[ "Apache-2.0" ]
null
null
null
src/sendData.cpp
lbussy/tiltbridge
eef5406c4eb598febe4e22651dacfef24b63efd8
[ "Apache-2.0" ]
null
null
null
// // Created by John Beeler on 2/18/19. // #include<ctime> #include <nlohmann/json.hpp> // for convenience using json = nlohmann::json; #include "tiltBridge.h" #include "wifi_setup.h" #include "sendData.h" #include <Arduino.h> #include <HTTPClient.h> #include <WiFi.h> #ifdef USE_SECURE_GSCRIPTS #include <WiFiMulti.h> #include <WiFiClientSecure.h> #include "SecureWithRedirects.h" #endif dataSendHandler data_sender; // Global data sender dataSendHandler::dataSendHandler() { send_to_brewstatus_at = 40 * 1000; // Trigger the first send to BrewStatus 40 seconds out send_to_fermentrack_at = 45 * 1000; // Trigger the first send to Fermentrack 45 seconds out send_to_brewfather_at = 50 * 1000; // Trigger the first send to Fermentrack 50 seconds out send_to_brewers_friend_at = 55 * 1000; // Trigger the first send to Brewer's Friend 55 seconds out send_to_google_at = 65 * 1000; // Trigger the first send to Google Sheets 65 seconds out #ifdef ENABLE_TEST_CHECKINS send_checkin_at = 35 * 1000; // If we have send_checkins enabled (this is a testing thing!) send at 35 seconds #endif } #ifdef USE_SECURE_GSCRIPTS void dataSendHandler::setClock() { configTime(0, 0, "pool.ntp.org", "time.nist.gov"); time_t nowSecs = time(nullptr); while (nowSecs < 8 * 3600 * 2) { delay(500); yield(); nowSecs = time(nullptr); } struct tm timeinfo; gmtime_r(&nowSecs, &timeinfo); } #endif void dataSendHandler::init() { #ifdef USE_SECURE_GSCRIPTS setClock(); #endif } bool dataSendHandler::send_to_fermentrack() { nlohmann::json j; bool result = true; // This should look like this when sent to Fermentrack: // { // 'mdns_id': 'mDNS ID Goes Here', // 'tilts': {'color': 'Purple', 'temp': 74, 'gravity': 1.043}, // {'color': 'Orange', 'temp': 66, 'gravity': 1.001} // } j["mdns_id"] = app_config.config["mdnsID"].get<std::string>(); j["tilts"] = tilt_scanner.tilt_to_json(); if(!send_to_url(app_config.config["fermentrackURL"].get<std::string>().c_str(), "", j.dump().c_str(), "application/json")) result = false; // There was an error with the previous send j.clear(); return result; } bool dataSendHandler::send_to_brewstatus() { bool result = true; const int payload_size = 512; char payload[payload_size]; // The payload should look like this when sent to Brewstatus: // ('Request payload:', 'SG=1.019&Temp=71.0&Color=ORANGE&Timepoint=43984.33630927084&Beer=Beer&Comment=Comment') // BrewStatus ignors Beer, so we just set this to Undefined. // BrewStatus will record Comment if it set, but just leave it blank. // The Timepoint is Google Sheets time, which is fractional days since 12/30/1899 // Using https://www.timeanddate.com/date/durationresult.html?m1=12&d1=30&y1=1899&m2=1&d2=1&y2=1970 gives // us 25,569 days from the start of Google Sheets time to the start of the Unix epoch. // BrewStatus wants local time, so we allow the user to specify a time offset. // Loop through each of the tilt colors cached by tilt_scanner, sending data for each of the active tilts for(uint8_t i = 0;i<TILT_COLORS;i++) { if(tilt_scanner.tilt(i)->is_loaded()) { snprintf(payload, payload_size, "SG=%f&Temp=%f&Color=%s&Timepoint=%.11f&Beer=Undefined&Comment=", (float) tilt_scanner.tilt(i)->gravity / 1000, (float) tilt_scanner.tilt(i)->temp, tilt_scanner.tilt(i)->color_name().c_str(), ((double) std::time(0) + (app_config.config["brewstatusTZoffset"].get<double>() * 3600.0)) / 86400.0 + 25569.0); if(!send_to_url(app_config.config["brewstatusURL"].get<std::string>().c_str(), "", payload, "application/x-www-form-urlencoded")) result = false; // There was an error with the previous send } } return result; } #ifdef USE_SECURE_GSCRIPTS // For sending data to Google Scripts, we have to use secure_client but otherwise we're doing the same thing as before. bool dataSendHandler::send_to_url_https(const char *url, const char *apiKey, const char *dataToSend, const char *contentType) { // This handles the generic act of sending data to an endpoint bool result = false; if (strlen(dataToSend) > 5) { #ifdef DEBUG_PRINTS Serial.print("[HTTPS] Sending data to: "); Serial.println(url); Serial.print("Data to send: "); Serial.println(dataToSend); Serial.printf("[HTTPS] Pre-deinit RAM left %d\r\n", esp_get_free_heap_size()); #endif // We're severely memory starved. Deinitialize bluetooth and free the related memory // NOTE - This is not strictly true under NimBLE. Deinit now only waits for a scan to complete before tilt_scanner.deinit(); yield(); #ifdef DEBUG_PRINTS Serial.printf("[HTTPS] Post-deinit RAM left %d\r\n", esp_get_free_heap_size()); Serial.println("[HTTPS] Calling SWR::send_with_redirects"); #endif SecureWithRedirects SWR(url, apiKey, dataToSend, contentType); result = SWR.send_with_redirects(); SWR.end(); #ifdef DEBUG_PRINTS Serial.printf("[HTTPS] Post-SWR RAM left %d\r\n", esp_get_free_heap_size()); #endif yield(); tilt_scanner.init(); yield(); #ifdef DEBUG_PRINTS Serial.printf("[HTTPS] Post-reinit RAM left %d\r\n", esp_get_free_heap_size()); #endif } return result; } #endif bool dataSendHandler::send_to_google() { HTTPClient http; nlohmann::json j; nlohmann::json payload; bool result = true; // There are two configuration options which are mandatory when using the Google Sheets integration if(app_config.config["scriptsURL"].get<std::string>().length() <= GSCRIPTS_MIN_URL_LENGTH || app_config.config["scriptsEmail"].get<std::string>().length() < GSCRIPTS_MIN_EMAIL_LENGTH) { //#ifdef DEBUG_PRINTS // Serial.println("Either scriptsURL or scriptsEmail not populated. Returning."); //#endif return false; } // This should look like this when sent to the proxy that sends to Google (once per Tilt): // { // 'payload': { // Payload is what gets ultimately sent on to Google Scripts // 'Beer': 'Key Goes Here', // 'Temp': 65, // 'SG': 1.050, // This is sent as a float // 'Color': 'Blue', // 'Comment': '', // 'Email': 'xxx@gmail.com', // }, // 'gscripts_url': 'https://script.google.com/.../', // This is specific to the proxy // } // // For secure GScripts support, we don't send the 'j' json object - just the payload. // Loop through each of the tilt colors cached by tilt_scanner, sending data for each of the active tilts for(uint8_t i = 0;i<TILT_COLORS;i++) { if(tilt_scanner.tilt(i)->is_loaded()) { if(tilt_scanner.tilt(i)->gsheets_beer_name().length() <= 0) { continue; // If there is no gsheets beer name, we don't know where to log to. Skip this tilt. } payload["Beer"] = tilt_scanner.tilt(i)->gsheets_beer_name(); payload["Temp"] = tilt_scanner.tilt(i)->temp; // Always in Fahrenheit payload["SG"] = (float) tilt_scanner.tilt(i)->gravity / 1000; payload["Color"] = tilt_scanner.tilt(i)->color_name(); payload["Comment"] = ""; payload["Email"] = app_config.config["scriptsEmail"].get<std::string>(); // The gmail email address associated with the script on google #ifdef USE_SECURE_GSCRIPTS // When sending the data to GScripts directly, we're sending the payload - not the wrapped payload if(!send_to_url_https(app_config.config["scriptsURL"].get<std::string>().c_str(), "", payload.dump().c_str(), "application/json")) result = false; // There was an error with the previous send payload.clear(); #else j["gscripts_url"] = app_config.config["scriptsURL"].get<std::string>(); j["payload"] = payload; // All data for non-secure gscripts goes through the TiltBridge google proxy script. I'm not happy with this // but it's the best I've got until HTTPS can be readded if(!send_to_url("http://www.tiltbridge.com/tiltbridge_google_proxy/", "", j.dump().c_str(), "application/json")) result = false; // There was an error with the previous send payload.clear(); j.clear(); #endif } } return result; } bool dataSendHandler::send_to_bf_and_bf(const uint8_t which_bf) { // This function combines the data formatting for both "BF"s - Brewers Friend & Brewfather // Once the data is formatted, it is dispatched to send_to_url to be sent out. bool result = true; nlohmann::json j; std::string apiKeyStr; std::string url; // As this function is being used for both Brewer's Friend and Brewfather, let's determine which we want and set up // the URL/API key accordingly. if(which_bf == BF_MEANS_BREWFATHER) { apiKeyStr = app_config.config["brewfatherKey"].get<std::string>(); if (apiKeyStr.length() <= BREWFATHER_MIN_KEY_LENGTH) { #ifdef DEBUG_PRINTS Serial.println("brewfatherKey not populated. Returning.\r\n"); #endif return false; } url = "http://log.brewfather.net/stream?id=" + apiKeyStr; } else if(which_bf == BF_MEANS_BREWERS_FRIEND) { apiKeyStr = app_config.config["brewersFriendKey"].get<std::string>(); if(apiKeyStr.length() <= BREWERS_FRIEND_MIN_KEY_LENGTH) { #ifdef DEBUG_PRINTS Serial.println("brewersFriendKey not populated. Returning."); #endif return false; } url = "http://log.brewersfriend.com/stream/" + apiKeyStr; } else { #ifdef DEBUG_PRINTS Serial.println("Invalid value of which_bf passed to send_to_bf_and_bf!"); #endif return false; } // The data should look like this when sent to Brewfather or Brewers Friend (once per Tilt): // { // 'name': 'Red', // The color of the Tilt // 'temp': 65, // 'temp_unit': 'F', // Always in Fahrenheit // 'gravity': 1.050, // This is sent as a float // 'gravity_unit': 'G', // We send specific gravity, not plato // 'device_source': 'TiltBridge', // } // Loop through each of the tilt colors cached by tilt_scanner, sending data for each of the active tilts for(uint8_t i = 0;i<TILT_COLORS;i++) { if(tilt_scanner.tilt(i)->is_loaded()) { #ifdef DEBUG_PRINTS Serial.print("Tilt loaded with color name: "); Serial.println(tilt_scanner.tilt(i)->color_name().c_str()); #endif j["name"] = tilt_scanner.tilt(i)->color_name(); j["temp"] = tilt_scanner.tilt(i)->temp; // Always in Fahrenheit j["temp_unit"] = "F"; j["gravity"] = tilt_scanner.tilt(i)->converted_gravity(); j["gravity_unit"] = "G"; j["device_source"] = "TiltBridge"; if(!send_to_url(url.c_str(), apiKeyStr.c_str(), j.dump().c_str(), "application/json")) result = false; // There was an error with the previous send j.clear(); } } return result; } bool dataSendHandler::send_to_url(const char *url, const char *apiKey, const char *dataToSend, const char *contentType) { // This handles the generic act of sending data to an endpoint HTTPClient http; bool result = false; if(strlen(dataToSend) > 5) { #ifdef DEBUG_PRINTS Serial.print("Sending data to: "); Serial.println(url); Serial.print("Data to send: "); Serial.println(dataToSend); #endif // If we're really memory starved, we can wait to send any data until current scans complete // tilt_scanner.wait_until_scan_complete(); http.begin(url); http.addHeader("Content-Type", contentType); //Specify content-type header if (apiKey) { http.addHeader("X-API-KEY", apiKey); //Specify API key header } int httpResponseCode = http.POST(dataToSend); //Send the actual POST request if (httpResponseCode > 0) { result = true; #ifdef DEBUG_PRINTS String response = http.getString(); //Get the response to the request Serial.println(httpResponseCode); //Print return code Serial.println(response); //Print request answer } else { Serial.print("Error on sending POST: "); Serial.println(httpResponseCode); //Print return code #endif } http.end(); //Free resources } return result; } #ifdef ENABLE_TEST_CHECKINS u_long checkin_no = 0; void send_checkin_stat() { HTTPClient http; String Data = "checkin_no="; Data += String(checkin_no); // Data += "\r\n\r\n"; // Serial.print("Data to send: "); // Serial.println(Data); http.begin("http://www.fermentrack.com/checkin/"); //Specify destination for HTTP request http.addHeader("Content-Type", "application/json"); //Specify content-type header int httpResponseCode = http.POST(Data); //Send the actual POST request if (httpResponseCode > 0) { // String response = http.getString(); //Get the response to the request // Serial.println(httpResponseCode); //Print return code // Serial.println(response); //Print request answer } else { // Serial.print("Error on sending POST: "); // Serial.println(httpResponseCode); } http.end(); //Free resources checkin_no = checkin_no + 1; } #endif void dataSendHandler::process() { // dataSendHandler::process() processes each tick & dispatches HTTP clients to push data out as necessary // Check & send to Fermentrack if necessary if(send_to_fermentrack_at <= xTaskGetTickCount()) { if(WiFiClass::status()== WL_CONNECTED && app_config.config["fermentrackURL"].get<std::string>().length() > FERMENTRACK_MIN_URL_LENGTH) { //Check WiFi connection status #ifdef DEBUG_PRINTS Serial.printf("Calling send to Fermentrack\r\n"); #endif send_to_fermentrack(); send_to_fermentrack_at = xTaskGetTickCount() + (app_config.config["fermentrackPushEvery"].get<int>() * 1000); } else { // If the user adds the setting, we want this to kick in within 10 seconds send_to_fermentrack_at = xTaskGetTickCount() + 10000; } yield(); } // Check & send to Brewstatus if necessary if(send_to_brewstatus_at <= xTaskGetTickCount()) { if(WiFiClass::status()== WL_CONNECTED && app_config.config["brewstatusURL"].get<std::string>().length() > BREWSTATUS_MIN_URL_LENGTH) { //Check WiFi connection status #ifdef DEBUG_PRINTS Serial.printf("Calling send to Brewstatus\r\n"); #endif send_to_brewstatus(); send_to_brewstatus_at = xTaskGetTickCount() + (app_config.config["brewstatusPushEvery"].get<int>() * 1000); } else { // If the user adds the setting, we want this to kick in within 10 seconds send_to_brewstatus_at = xTaskGetTickCount() + 10000; } yield(); } // Check & send to Google Scripts if necessary if(send_to_google_at <= xTaskGetTickCount()) { if(WiFiClass::status()== WL_CONNECTED && app_config.config["scriptsURL"].get<std::string>().length() > GSCRIPTS_MIN_URL_LENGTH) { #ifdef DEBUG_PRINTS Serial.printf("Calling send to Google\r\n"); #endif // tilt_scanner.wait_until_scan_complete(); send_to_google(); send_to_google_at = xTaskGetTickCount() + GSCRIPTS_DELAY; } else { // If the user adds the setting, we want this to kick in within 10 seconds send_to_google_at = xTaskGetTickCount() + 10000; } yield(); } // Check & send to Brewers Friend if necessary if(send_to_brewers_friend_at <= xTaskGetTickCount()) { if(WiFiClass::status()== WL_CONNECTED && app_config.config["brewersFriendKey"].get<std::string>().length() > BREWERS_FRIEND_MIN_KEY_LENGTH) { #ifdef DEBUG_PRINTS Serial.printf("Calling send to Brewers Friend\r\n"); #endif send_to_bf_and_bf(BF_MEANS_BREWERS_FRIEND); send_to_brewers_friend_at = xTaskGetTickCount() + BREWERS_FRIEND_DELAY; } else { // If the user adds the setting, we want this to kick in within 10 seconds send_to_brewers_friend_at = xTaskGetTickCount() + 10000; } yield(); } #ifdef ENABLE_TEST_CHECKINS if(send_checkin_at <= xTaskGetTickCount()) { if(WiFiClass::status()== WL_CONNECTED) { //Check WiFi connection status #ifdef DEBUG_PRINTS Serial.printf("Calling check-in to fermentrack.com\r\n"); #endif // tilt_scanner.wait_until_scan_complete(); send_checkin_stat(); } send_checkin_at = xTaskGetTickCount() + (60*5 * 1000); yield(); } #endif if (send_to_brewfather_at <= xTaskGetTickCount()) { if(WiFiClass::status() == WL_CONNECTED && app_config.config["brewfatherKey"].get<std::string>().length() > BREWFATHER_MIN_KEY_LENGTH) { #ifdef DEBUG_PRINTS Serial.printf("Calling send to Brewfather\r\n"); #endif send_to_bf_and_bf(BF_MEANS_BREWFATHER); send_to_brewfather_at = xTaskGetTickCount() + BREWFATHER_DELAY; } else { // If the user adds the setting, we want this to kick in within 10 seconds send_to_brewfather_at = xTaskGetTickCount() + 10000; } yield(); } }
38.324895
177
0.627106
[ "object" ]
7caccfff8a66fbe6b18c5b904e749311944dfc15
38,691
cpp
C++
tests/model/test-brep.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
64
2019-08-02T14:31:01.000Z
2022-03-30T07:46:50.000Z
tests/model/test-brep.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
395
2019-08-02T17:15:10.000Z
2022-03-31T15:10:27.000Z
tests/model/test-brep.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
8
2019-08-19T21:32:15.000Z
2022-03-06T18:41:10.000Z
/* * Copyright (c) 2019 - 2021 Geode-solutions * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <geode/basic/assert.h> #include <geode/basic/logger.h> #include <geode/basic/range.h> #include <geode/basic/uuid.h> #include <geode/geometry/point.h> #include <geode/mesh/builder/edged_curve_builder.h> #include <geode/mesh/builder/point_set_builder.h> #include <geode/mesh/builder/surface_mesh_builder.h> #include <geode/mesh/builder/triangulated_surface_builder.h> #include <geode/mesh/core/geode_edged_curve.h> #include <geode/mesh/core/geode_point_set.h> #include <geode/mesh/core/geode_polygonal_surface.h> #include <geode/mesh/core/geode_polyhedral_solid.h> #include <geode/mesh/core/geode_triangulated_surface.h> #include <geode/mesh/core/point_set.h> #include <geode/model/mixin/core/block.h> #include <geode/model/mixin/core/corner.h> #include <geode/model/mixin/core/detail/count_relationships.h> #include <geode/model/mixin/core/line.h> #include <geode/model/mixin/core/model_boundary.h> #include <geode/model/mixin/core/surface.h> #include <geode/model/representation/builder/brep_builder.h> #include <geode/model/representation/builder/detail/copy.h> #include <geode/model/representation/core/brep.h> #include <geode/model/representation/io/brep_input.h> #include <geode/model/representation/io/brep_output.h> #include <geode/tests/common.h> std::array< geode::uuid, 6 > add_corners( const geode::BRep& model, geode::BRepBuilder& builder ) { std::array< geode::uuid, 6 > uuids; for( const auto c : geode::Range{ 6 } ) { uuids[c] = builder.add_corner(); builder.set_corner_name( uuids[c], absl::StrCat( "corner", c + 1 ) ); } const auto& temp_corner = model.corner( builder.add_corner( geode::OpenGeodePointSet3D::impl_name_static() ) ); builder.remove_corner( temp_corner ); const auto message = absl::StrCat( "[Test] BRep should have ", 6, " corners" ); OPENGEODE_EXCEPTION( model.nb_corners() == 6, message ); OPENGEODE_EXCEPTION( geode::detail::count_relationships( model.corners() ) == 6, message ); OPENGEODE_EXCEPTION( model.corner( uuids[3] ).name() == "corner4", "[Test] Wrong Corner name" ); return uuids; } std::array< geode::uuid, 9 > add_lines( const geode::BRep& model, geode::BRepBuilder& builder ) { std::array< geode::uuid, 9 > uuids; for( const auto l : geode::Range{ 9 } ) { uuids[l] = builder.add_line(); builder.set_line_name( uuids[l], absl::StrCat( "line", l + 1 ) ); } const auto& temp_line = model.line( builder.add_line( geode::OpenGeodeEdgedCurve3D::impl_name_static() ) ); builder.remove_line( temp_line ); const auto message = absl::StrCat( "[Test] BRep should have ", 9, " lines" ); OPENGEODE_EXCEPTION( model.nb_lines() == 9, message ); OPENGEODE_EXCEPTION( geode::detail::count_relationships( model.lines() ) == 9, message ); OPENGEODE_EXCEPTION( model.line( uuids[3] ).name() == "line4", "[Test] Wrong Line name" ); return uuids; } std::array< geode::uuid, 5 > add_surfaces( const geode::BRep& model, geode::BRepBuilder& builder ) { std::array< geode::uuid, 5 > uuids; for( const auto s : geode::Range{ 2 } ) { uuids[s] = builder.add_surface( geode::OpenGeodeTriangulatedSurface3D::impl_name_static() ); builder.set_surface_name( uuids[s], absl::StrCat( "surface", s + 1 ) ); } for( const auto s : geode::Range{ 2, 5 } ) { uuids[s] = builder.add_surface( geode::OpenGeodePolygonalSurface3D::impl_name_static() ); } const auto& temp_surface = model.surface( builder.add_surface() ); builder.remove_surface( temp_surface ); const auto message = absl::StrCat( "[Test] BRep should have ", 5, " surfaces" ); OPENGEODE_EXCEPTION( model.nb_surfaces() == 5, message ); OPENGEODE_EXCEPTION( geode::detail::count_relationships( model.surfaces() ) == 5, message ); OPENGEODE_EXCEPTION( model.surface( uuids[1] ).name() == "surface2", "[Test] Wrong Surface name" ); return uuids; } std::array< geode::uuid, 1 > add_blocks( const geode::BRep& model, geode::BRepBuilder& builder ) { std::array< geode::uuid, 1 > uuids; for( const auto b : geode::Range{ 1 } ) { uuids[b] = builder.add_block(); builder.set_block_name( uuids[b], absl::StrCat( "block", b + 1 ) ); } const auto& temp_block = model.block( builder.add_block( geode::OpenGeodePolyhedralSolid3D::impl_name_static() ) ); builder.remove_block( temp_block ); const auto message = absl::StrCat( "[Test] BRep should have ", 1, " block" ); OPENGEODE_EXCEPTION( model.nb_blocks() == 1, message ); OPENGEODE_EXCEPTION( geode::detail::count_relationships( model.blocks() ) == 1, message ); OPENGEODE_EXCEPTION( model.block( uuids[0] ).name() == "block1", "[Test] Wrong Block name" ); return uuids; } std::array< geode::uuid, 3 > add_model_boundaries( const geode::BRep& model, geode::BRepBuilder& builder ) { std::array< geode::uuid, 3 > uuids; for( const auto mb : geode::Range{ 3 } ) { uuids[mb] = builder.add_model_boundary(); builder.set_model_boundary_name( uuids[mb], absl::StrCat( "boundary", mb + 1 ) ); } const auto& temp_boundary = model.model_boundary( builder.add_model_boundary() ); builder.remove_model_boundary( temp_boundary ); const auto message = absl::StrCat( "[Test] BRep should have ", 3, " model boundaries" ); OPENGEODE_EXCEPTION( model.nb_model_boundaries() == 3, message ); OPENGEODE_EXCEPTION( geode::detail::count_relationships( model.model_boundaries() ) == 3, message ); OPENGEODE_EXCEPTION( model.model_boundary( uuids[0] ).name() == "boundary1", "[Test] Wrong ModelBoundary name" ); return uuids; } void add_corner_line_boundary_relation( const geode::BRep& model, geode::BRepBuilder& builder, absl::Span< const geode::uuid > corner_uuids, absl::Span< const geode::uuid > line_uuids ) { builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[0] ), model.line( line_uuids[0] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[0] ), model.line( line_uuids[5] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[0] ), model.line( line_uuids[2] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[1] ), model.line( line_uuids[0] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[1] ), model.line( line_uuids[1] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[1] ), model.line( line_uuids[3] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[2] ), model.line( line_uuids[1] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[2] ), model.line( line_uuids[2] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[2] ), model.line( line_uuids[4] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[3] ), model.line( line_uuids[5] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[3] ), model.line( line_uuids[6] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[3] ), model.line( line_uuids[8] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[4] ), model.line( line_uuids[3] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[4] ), model.line( line_uuids[6] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[4] ), model.line( line_uuids[7] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[5] ), model.line( line_uuids[4] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[5] ), model.line( line_uuids[7] ) ); builder.add_corner_line_boundary_relationship( model.corner( corner_uuids[5] ), model.line( line_uuids[8] ) ); for( const auto& corner_id : corner_uuids ) { for( const auto& incidence : model.incidences( model.corner( corner_id ) ) ) { OPENGEODE_EXCEPTION( absl::c_find( line_uuids, incidence.id() ) != line_uuids.end(), "[Test] All Corners incidences should be Lines" ); } OPENGEODE_EXCEPTION( model.nb_incidences( corner_id ) == 3, "[Test] All Corners should be connected to 3 Lines" ); } for( const auto& line_id : line_uuids ) { for( const auto& boundary : model.boundaries( model.line( line_id ) ) ) { OPENGEODE_EXCEPTION( absl::c_find( corner_uuids, boundary.id() ) != corner_uuids.end(), "[Test] All Lines incidences should be Corners" ); } OPENGEODE_EXCEPTION( model.nb_boundaries( line_id ) == 2, "[Test] All Lines should be connected to 2 Corners" ); } } void add_line_surface_boundary_relation( const geode::BRep& model, geode::BRepBuilder& builder, absl::Span< const geode::uuid > line_uuids, absl::Span< const geode::uuid > surface_uuids ) { builder.add_line_surface_boundary_relationship( model.line( line_uuids[0] ), model.surface( surface_uuids[0] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[0] ), model.surface( surface_uuids[1] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[1] ), model.surface( surface_uuids[0] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[1] ), model.surface( surface_uuids[2] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[2] ), model.surface( surface_uuids[0] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[2] ), model.surface( surface_uuids[3] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[3] ), model.surface( surface_uuids[1] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[3] ), model.surface( surface_uuids[2] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[4] ), model.surface( surface_uuids[2] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[4] ), model.surface( surface_uuids[3] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[5] ), model.surface( surface_uuids[1] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[5] ), model.surface( surface_uuids[3] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[6] ), model.surface( surface_uuids[1] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[6] ), model.surface( surface_uuids[4] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[7] ), model.surface( surface_uuids[2] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[7] ), model.surface( surface_uuids[4] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[8] ), model.surface( surface_uuids[3] ) ); builder.add_line_surface_boundary_relationship( model.line( line_uuids[8] ), model.surface( surface_uuids[4] ) ); for( const auto& line_id : line_uuids ) { for( const auto& incidence : model.incidences( model.line( line_id ) ) ) { OPENGEODE_EXCEPTION( absl::c_find( surface_uuids, incidence.id() ) != surface_uuids.end(), "[Test] All Lines incidences should be Surfaces" ); } OPENGEODE_EXCEPTION( model.nb_incidences( line_id ) == 2, "[Test] All Lines should be connected to 2 Surfaces" ); } } void add_surface_block_relation( const geode::BRep& model, geode::BRepBuilder& builder, absl::Span< const geode::uuid > surface_uuids, absl::Span< const geode::uuid > block_uuids ) { for( const auto& surface_id : surface_uuids ) { builder.add_surface_block_boundary_relationship( model.surface( surface_id ), model.block( block_uuids.front() ) ); } for( const auto& surface_id : surface_uuids ) { for( const auto& incidence : model.incidences( model.surface( surface_id ) ) ) { OPENGEODE_EXCEPTION( block_uuids.front() == incidence.id(), "[Test] All Surfaces incidences should be Blocks" ); } OPENGEODE_EXCEPTION( model.nb_incidences( surface_id ) == 1, "[Test] All Surfaces should be connected to 1 Block" ); } OPENGEODE_EXCEPTION( model.nb_boundaries( block_uuids.front() ) == surface_uuids.size(), "[Test] The Block should be connected to all Surfaces" ); } void add_surfaces_in_model_boundaries( const geode::BRep& model, geode::BRepBuilder& builder, absl::Span< const geode::uuid > surface_uuids, absl::Span< const geode::uuid > boundary_uuids ) { builder.add_surface_in_model_boundary( model.surface( surface_uuids[0] ), model.model_boundary( boundary_uuids[0] ) ); for( const auto i : geode::Range{ 1, 4 } ) { builder.add_surface_in_model_boundary( model.surface( surface_uuids[i] ), model.model_boundary( boundary_uuids[1] ) ); } builder.add_surface_in_model_boundary( model.surface( surface_uuids[4] ), model.model_boundary( boundary_uuids[2] ) ); for( const auto& surface_id : surface_uuids ) { OPENGEODE_EXCEPTION( model.nb_collections( surface_id ) == 1, "[Test] All Surfaces should be in 1 collection (of type " "Boundary)" ); } } void add_internal_corner_relations( const geode::BRep& model, geode::BRepBuilder& builder, absl::Span< const geode::uuid > corner_uuids, absl::Span< const geode::uuid > surface_uuids, absl::Span< const geode::uuid > block_uuids ) { for( const auto& corner_id : corner_uuids ) { builder.add_corner_surface_internal_relationship( model.corner( corner_id ), model.surface( surface_uuids.front() ) ); builder.add_corner_block_internal_relationship( model.corner( corner_id ), model.block( block_uuids.front() ) ); } for( const auto& corner_id : corner_uuids ) { for( const auto& embedding : model.embedding_surfaces( model.corner( corner_id ) ) ) { OPENGEODE_EXCEPTION( surface_uuids.front() == embedding.id(), "[Test] All Corners embedded surfaces should be Surfaces" ); OPENGEODE_EXCEPTION( model.nb_internal_corners( embedding ) == corner_uuids.size(), "[Test] Surface should embed all Lines" ); } for( const auto& embedding : model.embedding_blocks( model.corner( corner_id ) ) ) { OPENGEODE_EXCEPTION( block_uuids.front() == embedding.id(), "[Test] All Corners embedded blocks should be Blocks" ); OPENGEODE_EXCEPTION( model.nb_internal_corners( embedding ) == corner_uuids.size(), "[Test] Block should embed all Lines" ); } OPENGEODE_EXCEPTION( model.nb_embeddings( corner_id ) == 2, "[Test] All Corners should be embedded to 1 Block and 1 Surface" ); OPENGEODE_EXCEPTION( model.nb_embedding_surfaces( model.corner( corner_id ) ) == 1, "[Test] All Corners should be embedded to 1 Surface" ); OPENGEODE_EXCEPTION( model.nb_embedding_blocks( model.corner( corner_id ) ) == 1, "[Test] All Corners should be embedded to 1 Block" ); } } void add_internal_line_relations( const geode::BRep& model, geode::BRepBuilder& builder, absl::Span< const geode::uuid > line_uuids, absl::Span< const geode::uuid > surface_uuids, absl::Span< const geode::uuid > block_uuids ) { for( const auto& line_id : line_uuids ) { builder.add_line_surface_internal_relationship( model.line( line_id ), model.surface( surface_uuids.front() ) ); builder.add_line_block_internal_relationship( model.line( line_id ), model.block( block_uuids.front() ) ); } for( const auto& line_id : line_uuids ) { for( const auto& embedding : model.embedding_surfaces( model.line( line_id ) ) ) { OPENGEODE_EXCEPTION( surface_uuids.front() == embedding.id(), "[Test] All Line embedded surfaces should be Surfaces" ); OPENGEODE_EXCEPTION( model.nb_internal_lines( embedding ) == line_uuids.size(), "[Test] Surface should embed all Lines" ); } for( const auto& embedding : model.embedding_blocks( model.line( line_id ) ) ) { OPENGEODE_EXCEPTION( block_uuids.front() == embedding.id(), "[Test] All Lines embedded blocks should be Blocks" ); OPENGEODE_EXCEPTION( model.nb_internal_lines( embedding ) == line_uuids.size(), "[Test] Block should embed all Lines" ); } OPENGEODE_EXCEPTION( model.nb_embeddings( line_id ) == 2, "[Test] All Surfaces should be embedded to 1 Block and 1 Surface" ); OPENGEODE_EXCEPTION( model.nb_embedding_surfaces( model.line( line_id ) ) == 1, "[Test] All Surfaces should be embedded to 1 Surface" ); OPENGEODE_EXCEPTION( model.nb_embedding_blocks( model.line( line_id ) ) == 1, "[Test] All Surfaces should be embedded to 1 Block" ); } } void add_internal_surface_relations( const geode::BRep& model, geode::BRepBuilder& builder, absl::Span< const geode::uuid > surface_uuids, absl::Span< const geode::uuid > block_uuids ) { for( const auto& surface_id : surface_uuids ) { builder.add_surface_block_internal_relationship( model.surface( surface_id ), model.block( block_uuids.front() ) ); } for( const auto& surface_id : surface_uuids ) { for( const auto& embedding : model.embedding_blocks( model.surface( surface_id ) ) ) { OPENGEODE_EXCEPTION( model.nb_internal_surfaces( embedding ) == surface_uuids.size(), "[Test] Block should embed all Surfaces" ); OPENGEODE_EXCEPTION( block_uuids.front() == embedding.id(), "[Test] All Surfaces embeddings should be Blocks" ); } OPENGEODE_EXCEPTION( model.nb_embeddings( surface_id ) == 1, "[Test] All Surfaces should be embedded to 1 Block" ); OPENGEODE_EXCEPTION( model.nb_embedding_blocks( model.surface( surface_id ) ) == 1, "[Test] All Surfaces should be embedded to 1 Block" ); } } void set_geometry( geode::BRepBuilder& builder, absl::Span< const geode::uuid > corner_uuids, absl::Span< const geode::uuid > line_uuids, absl::Span< const geode::uuid > surface_uuids ) { std::array< geode::Point3D, 6 > points; points[0] = geode::Point3D{ { 0., 0., 0. } }; points[1] = geode::Point3D{ { 0., 1., 0. } }; points[2] = geode::Point3D{ { 1., 1., 0. } }; points[3] = geode::Point3D{ { 1., 1., 2. } }; points[4] = geode::Point3D{ { 1., 2., 2. } }; points[5] = geode::Point3D{ { 2., 2., 2. } }; for( const auto i : geode::Range{ 6 } ) { builder.corner_mesh_builder( corner_uuids[i] ) ->create_point( points[i] ); } builder.line_mesh_builder( line_uuids[0] )->create_point( points[0] ); builder.line_mesh_builder( line_uuids[0] )->create_point( points[1] ); builder.line_mesh_builder( line_uuids[1] )->create_point( points[1] ); builder.line_mesh_builder( line_uuids[1] )->create_point( points[2] ); builder.line_mesh_builder( line_uuids[2] )->create_point( points[0] ); builder.line_mesh_builder( line_uuids[2] )->create_point( points[2] ); builder.line_mesh_builder( line_uuids[3] )->create_point( points[1] ); builder.line_mesh_builder( line_uuids[3] )->create_point( points[4] ); builder.line_mesh_builder( line_uuids[4] )->create_point( points[2] ); builder.line_mesh_builder( line_uuids[4] )->create_point( points[5] ); builder.line_mesh_builder( line_uuids[5] )->create_point( points[0] ); builder.line_mesh_builder( line_uuids[5] )->create_point( points[3] ); builder.line_mesh_builder( line_uuids[6] )->create_point( points[3] ); builder.line_mesh_builder( line_uuids[6] )->create_point( points[4] ); builder.line_mesh_builder( line_uuids[7] )->create_point( points[4] ); builder.line_mesh_builder( line_uuids[7] )->create_point( points[5] ); builder.line_mesh_builder( line_uuids[8] )->create_point( points[3] ); builder.line_mesh_builder( line_uuids[8] )->create_point( points[5] ); for( const auto i : geode::Range{ 9 } ) { builder.line_mesh_builder( line_uuids[i] )->create_edge( 0, 1 ); } builder .surface_mesh_builder< geode::TriangulatedSurface3D >( surface_uuids[0] ) ->create_point( points[0] ); builder .surface_mesh_builder< geode::TriangulatedSurface3D >( surface_uuids[0] ) ->create_point( points[1] ); builder .surface_mesh_builder< geode::TriangulatedSurface3D >( surface_uuids[0] ) ->create_point( points[2] ); builder .surface_mesh_builder< geode::TriangulatedSurface3D >( surface_uuids[0] ) ->create_polygon( { 0, 1, 2 } ); builder.surface_mesh_builder( surface_uuids[1] )->create_point( points[0] ); builder.surface_mesh_builder( surface_uuids[1] )->create_point( points[1] ); builder.surface_mesh_builder( surface_uuids[1] )->create_point( points[4] ); builder.surface_mesh_builder( surface_uuids[1] )->create_point( points[3] ); builder.surface_mesh_builder( surface_uuids[1] ) ->create_polygon( { 0, 1, 2 } ); builder.surface_mesh_builder( surface_uuids[1] ) ->create_polygon( { 0, 2, 3 } ); builder.surface_mesh_builder( surface_uuids[2] )->create_point( points[4] ); builder.surface_mesh_builder( surface_uuids[2] )->create_point( points[1] ); builder.surface_mesh_builder( surface_uuids[2] )->create_point( points[2] ); builder.surface_mesh_builder( surface_uuids[2] )->create_point( points[5] ); builder.surface_mesh_builder( surface_uuids[2] ) ->create_polygon( { 0, 1, 2 } ); builder.surface_mesh_builder( surface_uuids[2] ) ->create_polygon( { 0, 2, 3 } ); builder.surface_mesh_builder( surface_uuids[3] )->create_point( points[3] ); builder.surface_mesh_builder( surface_uuids[3] )->create_point( points[0] ); builder.surface_mesh_builder( surface_uuids[3] )->create_point( points[2] ); builder.surface_mesh_builder( surface_uuids[3] )->create_point( points[5] ); builder.surface_mesh_builder( surface_uuids[3] ) ->create_polygon( { 0, 1, 2 } ); builder.surface_mesh_builder( surface_uuids[3] ) ->create_polygon( { 0, 2, 3 } ); builder.surface_mesh_builder( surface_uuids[4] )->create_point( points[3] ); builder.surface_mesh_builder( surface_uuids[4] )->create_point( points[4] ); builder.surface_mesh_builder( surface_uuids[4] )->create_point( points[5] ); builder.surface_mesh_builder( surface_uuids[4] ) ->create_polygon( { 0, 1, 2 } ); } void test_boundary_ranges( const geode::BRep& model, absl::Span< const geode::uuid > corner_uuids, absl::Span< const geode::uuid > line_uuids, absl::Span< const geode::uuid > surface_uuids, absl::Span< const geode::uuid > block_uuids ) { geode::index_t line_boundary_count{ 0 }; for( const auto& line_boundary : model.boundaries( model.line( line_uuids[0] ) ) ) { line_boundary_count++; OPENGEODE_EXCEPTION( line_boundary.id() == corner_uuids[0] || line_boundary.id() == corner_uuids[1], "[Test] BoundaryCornerRange iteration result is not correct" ); OPENGEODE_EXCEPTION( model.is_boundary( line_boundary, model.line( line_uuids[0] ) ), "[Test] Corner should be boundary of Line" ); } OPENGEODE_EXCEPTION( line_boundary_count == 2, "[Test] BoundaryCornerRange should iterates on 2 Corners" ); geode::index_t surface_boundary_count{ 0 }; for( const auto& surface_boundary : model.boundaries( model.surface( surface_uuids[0] ) ) ) { surface_boundary_count++; OPENGEODE_EXCEPTION( surface_boundary.id() == line_uuids[0] || surface_boundary.id() == line_uuids[1] || surface_boundary.id() == line_uuids[2], "[Test] BoundaryLineRange iteration result is not correct" ); OPENGEODE_EXCEPTION( model.is_boundary( surface_boundary, model.surface( surface_uuids[0] ) ), "[Test] Line should be boundary of Surface" ); } OPENGEODE_EXCEPTION( surface_boundary_count == 3, "[Test] BoundaryLineRange should iterates on 3 Lines" ); geode::index_t block_boundary_count{ 0 }; for( const auto& block_boundary : model.boundaries( model.block( block_uuids[0] ) ) ) { block_boundary_count++; OPENGEODE_EXCEPTION( block_boundary.id() == surface_uuids[0] || block_boundary.id() == surface_uuids[1] || block_boundary.id() == surface_uuids[2] || block_boundary.id() == surface_uuids[3] || block_boundary.id() == surface_uuids[4], "[Test] BoundarySurfaceRange iteration result is not correct" ); OPENGEODE_EXCEPTION( model.is_boundary( block_boundary, model.block( block_uuids[0] ) ), "[Test] Surface should be boundary of Block" ); } OPENGEODE_EXCEPTION( block_boundary_count == 5, "[Test] BoundarySurfaceRange should iterates on 5 Surfaces" ); } void test_incidence_ranges( const geode::BRep& model, absl::Span< const geode::uuid > corner_uuids, absl::Span< const geode::uuid > line_uuids, absl::Span< const geode::uuid > surface_uuids, absl::Span< const geode::uuid > block_uuids ) { geode::index_t corner_incidence_count{ 0 }; for( const auto& corner_incidence : model.incidences( model.corner( corner_uuids[0] ) ) ) { corner_incidence_count++; OPENGEODE_EXCEPTION( corner_incidence.id() == line_uuids[0] || corner_incidence.id() == line_uuids[2] || corner_incidence.id() == line_uuids[5], "[Test] IncidentLineRange iteration result is not correct" ); } OPENGEODE_EXCEPTION( corner_incidence_count == 3, "[Test] IncidentLineRange should iterates on 3 Lines" ); geode::index_t line_incidence_count{ 0 }; for( const auto& line_incidence : model.incidences( model.line( line_uuids[0] ) ) ) { line_incidence_count++; OPENGEODE_EXCEPTION( line_incidence.id() == surface_uuids[0] || line_incidence.id() == surface_uuids[1], "[Test] IncidentSurfaceRange iteration result is not correct" ); } OPENGEODE_EXCEPTION( line_incidence_count == 2, "[Test] IncidentSurfaceRange should iterates on 2 Surfaces" ); const auto& surface_incidences = model.incidences( model.surface( surface_uuids[0] ) ); geode::index_t surface_incidence_count{ 0 }; for( const auto& surface_incidence : surface_incidences ) { surface_incidence_count++; OPENGEODE_EXCEPTION( surface_incidence.id() == block_uuids[0], "[Test] IncidentBlockRange iteration result is not correct" ); } OPENGEODE_EXCEPTION( surface_incidence_count == 1, "[Test] IncidentBlockRange should iterates on 1 Block" ); } void test_item_ranges( const geode::BRep& model, absl::Span< const geode::uuid > surface_uuids, absl::Span< const geode::uuid > boundary_uuids ) { const auto& boundary_items = model.model_boundary_items( model.model_boundary( boundary_uuids[1] ) ); geode::index_t boundary_item_count{ 0 }; for( const auto& boundary_item : boundary_items ) { boundary_item_count++; OPENGEODE_EXCEPTION( boundary_item.id() == surface_uuids[1] || boundary_item.id() == surface_uuids[2] || boundary_item.id() == surface_uuids[3], "[Test] ItemSurfaceRange iteration result is not correct" ); OPENGEODE_EXCEPTION( model.is_model_boundary_item( boundary_item, model.model_boundary( boundary_uuids[1] ) ), "[Test] Surface should be item of ModelBoundary" ); } OPENGEODE_EXCEPTION( boundary_item_count == 3, "[Test] IncidentLineRange should iterates " "on 3 Surfaces (Boundary 1)" ); } void test_reloaded_brep( const geode::BRep& model ) { OPENGEODE_EXCEPTION( model.nb_corners() == 6, "[Test] Number of Corners in reloaded BRep should be 6" ); OPENGEODE_EXCEPTION( model.nb_lines() == 9, "[Test] Number of Lines in reloaded BRep should be 9" ); OPENGEODE_EXCEPTION( model.nb_surfaces() == 5, "[Test] Number of Surfaces in reloaded BRep should be 5" ); OPENGEODE_EXCEPTION( model.nb_blocks() == 1, "[Test] Number of Blocks in reloaded BRep should be 1" ); OPENGEODE_EXCEPTION( model.nb_model_boundaries() == 3, "[Test] Number of Boundaries in reloaded BRep should be 3" ); } void test_moved_brep( const geode::BRep& model ) { OPENGEODE_EXCEPTION( model.nb_corners() == 6, "[Test] Number of Corners in moved BRep should be 6" ); OPENGEODE_EXCEPTION( model.nb_lines() == 9, "[Test] Number of Lines in moved BRep should be 9" ); OPENGEODE_EXCEPTION( model.nb_surfaces() == 5, "[Test] Number of Surfaces in moved BRep should be 5" ); OPENGEODE_EXCEPTION( model.nb_blocks() == 1, "[Test] Number of Blocks in moved BRep should be 1" ); OPENGEODE_EXCEPTION( model.nb_model_boundaries() == 3, "[Test] Number of Boundaries in moved BRep should be 3" ); } void test_clone( const geode::BRep& brep ) { geode::BRep brep2; geode::BRepBuilder builder{ brep2 }; builder.copy( brep ); OPENGEODE_EXCEPTION( brep2.nb_corners() == 6, "[Test] BRep should have 6 corners" ); OPENGEODE_EXCEPTION( brep2.nb_lines() == 9, "[Test] BRep should have 9 lines" ); OPENGEODE_EXCEPTION( brep2.nb_surfaces() == 5, "[Test] BRep should have 5 surfaces" ); OPENGEODE_EXCEPTION( brep2.nb_blocks() == 1, "[Test] BRep should have 1 block" ); OPENGEODE_EXCEPTION( brep2.nb_model_boundaries() == 3, "[Test] BRep should have 3 model boundaries" ); const auto mappings = builder.copy_components( brep ); builder.copy_relationships( mappings, brep ); OPENGEODE_EXCEPTION( brep2.nb_corners() == 12, "[Test] BRep should have 12 corners" ); OPENGEODE_EXCEPTION( brep2.nb_lines() == 18, "[Test] BRep should have 18 lines" ); OPENGEODE_EXCEPTION( brep2.nb_surfaces() == 10, "[Test] BRep should have 10 surfaces" ); OPENGEODE_EXCEPTION( brep2.nb_blocks() == 2, "[Test] BRep should have 2 blocks" ); OPENGEODE_EXCEPTION( brep2.nb_model_boundaries() == 6, "[Test] BRep should have 6 model boundaries" ); for( const auto& corner : brep.corners() ) { const auto& new_corner = brep2.corner( mappings.at( geode::Corner3D::component_type_static() ) .in2out( corner.id() ) ); for( const auto& line : brep.incidences( corner ) ) { bool found{ false }; for( const auto& new_line : brep2.incidences( new_corner ) ) { if( mappings.at( geode::Line3D::component_type_static() ) .in2out( line.id() ) == new_line.id() ) { found = true; break; } } OPENGEODE_EXCEPTION( found, "[Test] All Corners incidences are not correct" ); } } for( const auto& line : brep.lines() ) { const auto& new_line = brep2.line( mappings.at( geode::Line3D::component_type_static() ) .in2out( line.id() ) ); for( const auto& surface : brep.incidences( line ) ) { bool found = { false }; for( const auto& new_surface : brep2.incidences( new_line ) ) { if( mappings.at( geode::Surface3D::component_type_static() ) .in2out( surface.id() ) == new_surface.id() ) { found = true; break; } } OPENGEODE_EXCEPTION( found, "[Test] All Lines incidences are not correct" ); } } for( const auto& surface : brep.surfaces() ) { const auto& new_surface = brep2.surface( mappings.at( geode::Surface3D::component_type_static() ) .in2out( surface.id() ) ); for( const auto& block : brep.incidences( surface ) ) { bool found = { false }; for( const auto& new_block : brep2.incidences( new_surface ) ) { if( mappings.at( geode::Block3D::component_type_static() ) .in2out( block.id() ) == new_block.id() ) { found = true; break; } } OPENGEODE_EXCEPTION( found, "[Test] All Surfaces incidences are not correct" ); } } for( const auto& model_boundary : brep.model_boundaries() ) { const auto& new_model_boundary = brep2.model_boundary( mappings.at( geode::ModelBoundary3D::component_type_static() ) .in2out( model_boundary.id() ) ); for( const auto& surface : brep.model_boundary_items( model_boundary ) ) { bool found = { false }; for( const auto& new_surface : brep2.model_boundary_items( new_model_boundary ) ) { if( mappings.at( geode::Surface3D::component_type_static() ) .in2out( surface.id() ) == new_surface.id() ) { found = true; break; } } OPENGEODE_EXCEPTION( found, "[Test] All ModelBoundaries incidences are not correct" ); } } } void test() { geode::BRep model; geode::BRepBuilder builder( model ); // This BRep represents a prism const auto corner_uuids = add_corners( model, builder ); const auto line_uuids = add_lines( model, builder ); const auto surface_uuids = add_surfaces( model, builder ); const auto block_uuids = add_blocks( model, builder ); const auto model_boundary_uuids = add_model_boundaries( model, builder ); set_geometry( builder, corner_uuids, line_uuids, surface_uuids ); add_corner_line_boundary_relation( model, builder, corner_uuids, line_uuids ); add_line_surface_boundary_relation( model, builder, line_uuids, surface_uuids ); add_surface_block_relation( model, builder, surface_uuids, block_uuids ); add_surfaces_in_model_boundaries( model, builder, surface_uuids, model_boundary_uuids ); add_internal_corner_relations( model, builder, corner_uuids, surface_uuids, block_uuids ); add_internal_line_relations( model, builder, line_uuids, surface_uuids, block_uuids ); add_internal_surface_relations( model, builder, surface_uuids, block_uuids ); OPENGEODE_EXCEPTION( model.nb_internals( block_uuids.front() ) == corner_uuids.size() + line_uuids.size() + surface_uuids.size(), "[Test] The Block should embed all Corners & Lines & Surfaces " "(that are internal to the " "Block)" ); test_boundary_ranges( model, corner_uuids, line_uuids, surface_uuids, block_uuids ); test_incidence_ranges( model, corner_uuids, line_uuids, surface_uuids, block_uuids ); test_item_ranges( model, surface_uuids, model_boundary_uuids ); test_clone( model ); const auto file_io = absl::StrCat( "test.", model.native_extension() ); geode::save_brep( model, file_io ); auto model2 = geode::load_brep( file_io ); test_reloaded_brep( model2 ); geode::BRep model3{ std::move( model2 ) }; test_moved_brep( model3 ); } OPENGEODE_TEST( "brep" )
43.967045
80
0.638055
[ "mesh", "geometry", "model" ]
7cb1353bfe7eab7e790ff2229beaa55d612c0f0c
815
hpp
C++
src/Tools/Math/Galois.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
src/Tools/Math/Galois.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
src/Tools/Math/Galois.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
#ifndef GALOIS_HPP #define GALOIS_HPP #include <vector> namespace aff3ct { namespace tools { class Galois { protected: const int K; const int N; // number of non-nul elements in the field : N = 2^m - 1 const int m; // order of the Galois Field std::vector<int> alpha_to; // log table of GF(2**m) std::vector<int> index_of; // antilog table of GF(2**m) std::vector<int> p; // coefficients of a primitive polynomial used to generate GF(2**m) public: Galois(const int& K, const int& N); virtual ~Galois(); int get_K() const; int get_N() const; int get_m() const; const std::vector<int>& get_alpha_to() const; const std::vector<int>& get_index_of() const; const std::vector<int>& get_p () const; private: void Select_Polynomial(); void Generate_GF(); }; } } #endif /* GALOIS_HPP */
19.878049
95
0.674847
[ "vector" ]
7cc1524168c6f0a48d5ba6af3b44cc855b7bfeab
10,059
cc
C++
src/catkin_ws/src/obstacles/src/cv_sphere.cc
JakobThumm/safe_rl_manipulators
1724aee2ec4cbbd8fecfbf1653991e182d4ca48b
[ "MIT" ]
null
null
null
src/catkin_ws/src/obstacles/src/cv_sphere.cc
JakobThumm/safe_rl_manipulators
1724aee2ec4cbbd8fecfbf1653991e182d4ca48b
[ "MIT" ]
null
null
null
src/catkin_ws/src/obstacles/src/cv_sphere.cc
JakobThumm/safe_rl_manipulators
1724aee2ec4cbbd8fecfbf1653991e182d4ca48b
[ "MIT" ]
null
null
null
#ifndef _VELODYNE_PLUGIN_HH_ #define _VELODYNE_PLUGIN_HH_ #include <random> #include <gazebo/gazebo.hh> #include <gazebo/common/common.hh> #include <gazebo/physics/physics.hh> #include <gazebo/transport/transport.hh> #include <gazebo/msgs/msgs.hh> #include <thread> #include "ros/ros.h" #include "ros/callback_queue.h" #include "ros/subscribe_options.h" #include "std_msgs/Float32.h" #include "geometry_msgs/Pose.h" #include <geometry_msgs/Point.h> #include <obstacles/cv_model.h> #include <Eigen/Dense> namespace gazebo { /// \brief A plugin to control a Velodyne sensor. class CV_Sphere : public ModelPlugin { /// \brief Constructor public: CV_Sphere() {} /// \brief The load function is called by Gazebo when the plugin is /// inserted into simulation /// \param[in] _model A pointer to the model that this plugin is /// attached to. /// \param[in] _sdf A pointer to the plugin's SDF element. public: virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf) { // Store the model pointer for convenience. this->model = _model; // Check that the velocity element exists, then read the value this->desired_y_velo = 0; if (_sdf->HasElement("velocity")) this->desired_y_velo = _sdf->Get<double>("velocity"); ignition::math::Vector3d start_vel = ignition::math::Vector3d(0, this->desired_y_velo, 0); this->SetVelocity(start_vel); this->sigma_model_noise = 0.001; if (_sdf->HasElement("sigma_model_noise")) this->sigma_model_noise = _sdf->Get<double>("sigma_model_noise"); this->sigma_sensor_noise = 0.01; if (_sdf->HasElement("sigma_sensor_noise")) this->sigma_sensor_noise = _sdf->Get<double>("sigma_sensor_noise"); // Define random generator with Gaussian distribution const double mean = 0.0; this->model_noise = std::normal_distribution<double>(mean, this->sigma_model_noise); this->sensor_noise = std::normal_distribution<double>(mean, this->sigma_sensor_noise); // Set up tracking with cv model this->cv_model = CVModel(1, this->sigma_model_noise, this->sigma_sensor_noise); Eigen::Vector3d start_pos; start_pos << this->model->WorldPose().X()+this->sensor_noise(this->generator), this->model->WorldPose().Y()+this->sensor_noise(this->generator), this->model->WorldPose().Z()+this->sensor_noise(this->generator); Eigen::Vector3d s_v; s_v << 0.0, this->desired_y_velo, 0.0; this->cv_model.init_target(start_pos, s_v, this->sigma_model_noise, this->sigma_sensor_noise); // Create the node this->node = transport::NodePtr(new transport::Node()); #if GAZEBO_MAJOR_VERSION < 8 this->node->Init(this->model->GetWorld()->GetName()); #else this->node->Init(this->model->GetWorld()->Name()); #endif // Listen to the update event. This event is broadcast every // simulation iteration. this->updateConnection = event::Events::ConnectWorldUpdateBegin( std::bind(&CV_Sphere::OnUpdate, this)); // Initialize ros, if it has not already bee initialized. if (!ros::isInitialized()) { int argc = 0; char **argv = NULL; ros::init(argc, argv, "gazebo_client", ros::init_options::NoSigintHandler); } // Create our ROS node. This acts in a similar manner to // the Gazebo node this->rosNode.reset(new ros::NodeHandle("gazebo_client")); // Create a named topic, and subscribe to it. ros::SubscribeOptions so_vel = ros::SubscribeOptions::create<std_msgs::Float32>( "/" + this->model->GetName() + "/vel_cmd", 1, boost::bind(&CV_Sphere::OnRosVelMsg, this, _1), ros::VoidPtr(), &this->rosQueue); this->rosSub = this->rosNode->subscribe(so_vel); // Create a named topic, and subscribe to it. ros::SubscribeOptions so_pose = ros::SubscribeOptions::create<geometry_msgs::Pose>( "/" + this->model->GetName() + "/pose_cmd", 1, boost::bind(&CV_Sphere::OnRosPoseMsg, this, _1), ros::VoidPtr(), &this->rosQueue); this->rosSubPose = this->rosNode->subscribe(so_pose); std::string topic_name = "/" + this->model->GetName() + "/position"; publisher = this->rosNode->advertise<geometry_msgs::Point>(topic_name, 100); // Spin up the queue helper thread. this->rosQueueThread = std::thread(std::bind(&CV_Sphere::QueueThread, this)); std::cout << "Fyling sphere plugin connected."; ROS_INFO("Fyling sphere plugin connected."); } // Called by the world update start event public: void OnUpdate() { // Simulate a noisy measurement Eigen::Vector3d true_pos; true_pos << this->model->WorldPose().X(), this->model->WorldPose().Y(), this->model->WorldPose().Z(); Eigen::Vector3d meas; meas << true_pos(0)+this->sensor_noise(this->generator), true_pos(1)+this->sensor_noise(this->generator), true_pos(2)+this->sensor_noise(this->generator); // Use the CV KF to estimate the true position // Currently the KF uses quite a bit of performance, so we turned it off. /* this->cv_model.perform_prediction_update(meas); Eigen::Vector3d pos = this->cv_model.get_pos(); */ // Publish the filtered sphere position geometry_msgs::Point pos_msg; pos_msg.x = meas(0); pos_msg.y = meas(1); pos_msg.z = meas(2); publisher.publish(pos_msg); // Debugging // Difference between estimated pos and true pos should be lower than difference between measured pos and true pos on average. /* Eigen::Vector3d diff_est = (pos - true_pos).cwiseAbs(); Eigen::Vector3d diff_meas = (meas - true_pos).cwiseAbs(); Eigen::Vector3d best = diff_meas - diff_est; ROS_INFO_STREAM("Difference between erros diff_meas - diff_est, these should be positive most of the time. x: " << best(0) << ", y: " << best(1) << ", z: " << best(2) << "\n"); */ // Add model noise // Generate gaussian noise ignition::math::Vector3d current_vel = this->model->WorldLinearVel(); this->desired_y_velo += this->model_noise(this->generator); current_vel.Set( current_vel.X()+this->model_noise(this->generator), this->desired_y_velo, current_vel.Z()+this->model_noise(this->generator) ); // Apply a small linear velocity to the model. this->model->SetLinearVel(current_vel); } /// \brief Set the velocity of the Velodyne /// \param[in] _vel New target velocity public: void SetVelocity(const ignition::math::Vector3d &_vel) { // Set the joint's target velocity. this->model->SetLinearVel(_vel); } /// \brief Set the pose of the Velodyne /// \param[in] _pose New pose public: void SetPose(const ignition::math::Pose3d &_pose) { ignition::math::Pose3d curr_pose = this->model->WorldPose(); this->model->SetWorldPose(_pose); } /// \brief Handle an incoming message from ROS /// \param[in] _msg A float value that is used to set the y velocity /// of the sphere. public: void OnRosVelMsg(const std_msgs::Float32ConstPtr &_msg) { this->desired_y_velo = _msg->data; this->SetVelocity(ignition::math::Vector3d(0, this->desired_y_velo, 0)); } /// \brief Handle an incoming pose message from ROS /// \param[in] _msg A geometry_msgs::Pose public: void OnRosPoseMsg(const geometry_msgs::PoseConstPtr &_msg) { std::cerr << "Pose msg received."; ignition::math::Pose3d _pose = ignition::math::Pose3d( _msg->position.x, _msg->position.y, _msg->position.z, _msg->orientation.w, _msg->orientation.x, _msg->orientation.y, _msg->orientation.z ); std::cerr << "Pose created."; this->SetPose(_pose); } /// \brief ROS helper function that processes messages private: void QueueThread() { static const double timeout = 0.01; while (this->rosNode->ok()) { this->rosQueue.callAvailable(ros::WallDuration(timeout)); } } /// \brief Pointer to the model. private: physics::ModelPtr model; // Pointer to the update event connection private: event::ConnectionPtr updateConnection; /// \brief Gaussian noise of velocity noise private: double sigma_model_noise; /// \brief Gaussian noise of position sensor private: double sigma_sensor_noise; private: std::default_random_engine generator; private: std::normal_distribution<double> model_noise; private: std::normal_distribution<double> sensor_noise; /// \brief A node used for transport private: transport::NodePtr node; /// \brief A subscriber to a named topic. private: transport::SubscriberPtr sub; /// \brief A subscriber to a named topic. private: transport::SubscriberPtr pose_sub; /// \brief A node use for ROS transport private: std::unique_ptr<ros::NodeHandle> rosNode; /// \brief A ROS subscriber private: ros::Subscriber rosSub; /// \brief A ROS subscriber private: ros::Subscriber rosSubPose; /// \brief ROS publisher that publishes a gazebo collision private: ros::Publisher publisher; /// \brief A ROS callbackqueue that helps process messages private: ros::CallbackQueue rosQueue; /// \brief A thread the keeps running the rosQueue private: std::thread rosQueueThread; /// \brief Desired y velocity (needed for initial velo jump) private: double desired_y_velo; /// \brief CV KF tracker private: CVModel cv_model; }; // Tell Gazebo about this plugin, so that Gazebo can call Load on this plugin. GZ_REGISTER_MODEL_PLUGIN(CV_Sphere) } #endif
36.445652
132
0.642807
[ "model" ]
7cc5487bcbfbf5f62f337ee54cfdf2860ea1f943
1,020
hh
C++
examples/instance/instance.hh
BlurryLight/DiRenderLab
e07f2e5cbbb30511c9f610fc6e4c9d03c92ec3e3
[ "MIT" ]
2
2021-04-21T04:28:36.000Z
2022-03-04T07:55:11.000Z
examples/instance/instance.hh
BlurryLight/DiRenderLab
e07f2e5cbbb30511c9f610fc6e4c9d03c92ec3e3
[ "MIT" ]
null
null
null
examples/instance/instance.hh
BlurryLight/DiRenderLab
e07f2e5cbbb30511c9f610fc6e4c9d03c92ec3e3
[ "MIT" ]
2
2021-08-04T10:31:56.000Z
2021-11-20T09:22:24.000Z
// // Created by zhong on 2021/5/1. // #ifndef DIRENDERLAB_INSTANCE_HH #define DIRENDERLAB_INSTANCE_HH #include "GLwrapper/global.hh" #include "GLwrapper/glsupport.hh" #include "GLwrapper/texture.hh" #include "GLwrapper/vertex_array.hh" using DRL::RenderBase; class InstanceRender : public RenderBase { protected: DRL::ResourcePathSearcher resMgr; DRL::Program shader; DRL::Program InstanceShader; DRL::VertexArray asteroidsVAO; std::unique_ptr<DRL::Model> spot_ptr; int DrawNumbers = 1'00; int oldDrawNumbers = DrawNumbers; std::vector<glm::mat4> modelMatrics; // DRL::VertexBuffer modelMatricsVBO; unsigned int modelMatricsVBO = 0; DRL::Texture2D spotTexture; enum Mode { kDraw = 0, kInstance = 1, kIndirectInstance = 2 }; int mode_ = kInstance; void update_model_matrics(); public: InstanceRender() = default; explicit InstanceRender(const BaseInfo &info) : DRL::RenderBase(info) {} void setup_states() override; void render() override; }; #endif // DIRENDERLAB_INSTANCE_HH
26.842105
74
0.746078
[ "render", "vector", "model" ]
7cc5d3807068494374a4e60a0910f2b5cb215848
22,301
cpp
C++
Project2/Project2/Project2.cpp
jakemanning/cs2413
8c031fb285ed63dd08022fa99f2672022e969659
[ "MIT" ]
2
2019-04-24T03:33:30.000Z
2019-05-06T00:40:47.000Z
Project2/Project2/Project2.cpp
jakemanning/cs2413
8c031fb285ed63dd08022fa99f2672022e969659
[ "MIT" ]
null
null
null
Project2/Project2/Project2.cpp
jakemanning/cs2413
8c031fb285ed63dd08022fa99f2672022e969659
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Exception { }; // Generic, all exceptions derive from this class IncorrectTab : public Exception { }; // In case the user asked for a browser tab that doesn't exist yet class IncorrectAction : public Exception { }; // In case the user asked for an action that won't work class ArrayException : public Exception { }; // Genric array exception, all array exceptions derive from class ArrayMemoryException : public ArrayException { }; // In case the array created causes an error class ArrayBoundsException : public ArrayException { }; // In case the user asked for an index that was out of bounds #pragma region array // Purely virtual data type from which arrays derive template <class DataType> class AbstractArrayClass { public: virtual int size() const = 0; // Abstract template for size virtual DataType& operator[] (int k) = 0; // Abstract template for array index overloading }; template <class DataType> class ArrayClass : virtual public AbstractArrayClass<DataType> { // Encapsulation of a DataType array protected: DataType *paObject; // Pointer to an array of DataType int _size; // Capacity of the array void copy(const ArrayClass<DataType>& ac); // Allows for a copy constructor to take data from an external ArrayClass public: ArrayClass(); // Default constructor, creates a array of size 1 ArrayClass(int n); // Initializer, creates an array of size n ArrayClass(int n, const DataType& val); // Initializer, fills an array of size n with val ArrayClass(const ArrayClass<DataType>& ac); // Copy constructor, transfers data from an external ArrayClass, and copies data into self virtual ~ArrayClass(); // Destructor virtual int size() const; // Encapsulated method to access capacity virtual DataType& operator [] (int k); // Overloads bracket operator to access data at index of k void operator=(const ArrayClass<DataType>& ac); // Overloads equals operator to copy information from the given ArrayClass }; // Purely virtual vector template template <class DataType> class AbstractVector : virtual public AbstractArrayClass<DataType> { public: virtual void insert(const DataType& item, int index) = 0; // Insert a new object at position index in the vector virtual void remove(int index) = 0; // Removes the object at position index of the vector virtual void add(const DataType& item) = 0; // Adds item at end of the vector }; // Encapsulation of a DataType Vector, allows for dynamically sized array template <class DataType> class Vector : virtual public ArrayClass<DataType>, virtual public AbstractVector<DataType> { protected: int _currSize; // Active size of the array int _incFactor; // Index at which the size of the array will be doubled public: Vector(); // Default constructor, calls underlying ArrayClass' default constructor, and sets current size to 0 Vector(int n); // Initializer, calls underlying ArrayClass' initializer, and sets increment factor to default Vector(int n, DataType& val); // Initializer, calls underlying ArrayClass' initializer, and sets increment factor to default Vector(const Vector<DataType>& v); // Copy constructor, transfers data from an external Vector, and copies data into self Vector(const ArrayClass<DataType>& ac); // Copy constructor, transfers data from an external ArrayClass, and copies data into underlying Array virtual ~Vector(); // Destructor void operator= (const Vector<DataType>& v); // Overloads equals operator to copy information from the given Vector void operator= (const ArrayClass<DataType>& ac); // Overloads equals operator to copy information from the given ArrayClass virtual void insert(const DataType& item, int index); // Shifts all items up to the current array from the given index, and inserts item into given index virtual void remove(int index); // Removes item at given index, shifts down other objects, and decrements active array size virtual void add(const DataType& item); // Appends an object to the underlying Array virtual int size() const; // Returns size of underlying array virtual int capacity() const; // Returns capacity of underlying array virtual int incFactor() const; // Returns current increment factor virtual void setIncFactor(int f); // Resets the incedent factor to necessary size void setCapacity(int c); // Resizes underlying array to the specified capacity }; #pragma region array template <class DataType> ArrayClass<DataType>::ArrayClass() { _size = 0; paObject = new DataType[1]; if (paObject == NULL) { throw ArrayMemoryException(); } _size = 1; } template <class DataType> ArrayClass<DataType>::ArrayClass(int n) { _size = 0; // Default in case allocation fails paObject = new DataType[n]; if (paObject == NULL) { throw ArrayMemoryException(); } _size = n; } template <class DataType> ArrayClass<DataType>::ArrayClass(int n, const DataType& val) { _size = 0; // Default in case allocation fails paObject = new DataType[n]; if (paObject == NULL) { throw ArrayMemoryException(); } _size = n; for (int i = 0; i < n; ++i) { paObject[i] = val; } } template <class DataType> ArrayClass<DataType>::ArrayClass(const ArrayClass<DataType>& ac) { copy(ac); } template <class DataType> ArrayClass<DataType>::~ArrayClass() { if (paObject != NULL) { delete[] paObject; } paObject = NULL; } template <class DataType> void ArrayClass<DataType>::copy(const ArrayClass<DataType>& ac) { _size = 0; // Default in case allocation fails paObject = new DataType[ac._size]; if (paObject == NULL) { throw ArrayMemoryException(); } _size = ac._size; for (int i = 0; i < _size; ++i) { paObject[i] = ac.paObject[i]; } } template <class DataType> int ArrayClass<DataType>::size() const { return _size; } template <class DataType> DataType& ArrayClass<DataType>::operator[] (int k) { if ((k < 0) || (k >= size())) { throw ArrayBoundsException(); } return paObject[k]; } template <class DataType> void ArrayClass<DataType>::operator=(const ArrayClass<DataType>& ac) { if (paObject != NULL) { delete[] paObject; } // Existing array is deleted and copied in to the new array copy(ac); } template <class DataType> ostream& operator << (ostream& s, AbstractArrayClass<DataType>& ac) { s << "["; for (int i = 0; i < ac.size(); ++i) { if (i > 0) { s << ','; } s << ac[i]; } s << "]"; return s; } #pragma endregion Methods #pragma region Vector template <class DataType> Vector<DataType>::Vector() : ArrayClass<DataType>() { _currSize = 0; // Default values _incFactor = 5; } template <class DataType> Vector<DataType>::Vector(int n) : ArrayClass<DataType>(n) { _currSize = 0; _incFactor = (n + 1) / 2; // Arbitrary } template <class DataType> Vector<DataType>::Vector(int n, const DataType& val) : ArrayClass<DataType>(n, val) { _currSize = n; _incFactor = n / 2; // Arbitrary } template <class DataType> Vector<DataType>::Vector(const Vector<DataType>& v) : ArrayClass<DataType>(v) { _currSize = v._currSize; _incFactor = v.incFactor(); } template <class DataType> Vector<DataType>::Vector(const ArrayClass<DataType>& ac) : ArrayClass<DataType>(ac) { _currSize = ac.size(); _incFactor = (_currSize + 1) / 2; } template <class DataType> Vector<DataType>::~Vector() { _currSize = 0; setIncFactor(5); } template <class DataType> void Vector<DataType>::operator= (const Vector<DataType>& v) { ArrayClass<DataType>::copy(v); _currSize = v._currSize; _incFactor = v.incFactor(); } template <class DataType> void Vector<DataType>::operator= (const ArrayClass<DataType>& ac) { ArrayClass<DataType>::copy(ac); _currSize = ac.size(); _incFactor = (_currSize + 1) / 2; } template <class DataType> int Vector<DataType>::size() const { return _currSize; } template <class DataType> int Vector<DataType>::capacity() const { return _size; } template <class DataType> int Vector<DataType>::incFactor() const { return _incFactor; } template <class DataType> void Vector<DataType>::setIncFactor(int f) { if (f >= 0) { _incFactor = f; } } template <class DataType> void Vector<DataType>::setCapacity(int c) { int len = _currSize; if (len > c) { len = c; } DataType* paNew = new DataType[c]; if (paNew == NULL) { throw ArrayMemoryException(); } for (int i = 0; i < len; ++i) { paNew[i] = paObject[i]; } if (paObject != NULL) { delete[] paObject; } paObject = paNew; _size = c; if (_currSize > len) { _currSize = len; } } template <class DataType> void Vector<DataType>::insert(const DataType& item, int index) { if ((index < 0) || (index > _currSize)) { throw ArrayBoundsException(); } if (_currSize + 1 == _size) { setCapacity(_size + _incFactor); } ++_currSize; for (int i = _currSize - 1; i > index; --i) { (*this)[i] = (*this)[i - 1]; } (*this)[index] = item; } template <class DataType> void Vector<DataType>::add(const DataType& item) { insert(item, _currSize); } template <class DataType> void Vector<DataType>::remove(int index) { if ((index < 0) || (index >= _currSize)) { throw ArrayBoundsException(); } if (_currSize <= _size - _incFactor) { setCapacity(_size - _incFactor); } for (int i = index; i < _currSize - 1; ++i) { (*this)[i] = (*this)[i + 1]; } --_currSize; } #pragma endregion Methods #pragma endregion Classes // Encapsulation of a URL string class webAddressInfo { friend ostream& operator<< (ostream& s, webAddressInfo& info); // Overloaded cstream operator, signified as friend so is able to access the info's url private: Vector<char> *url; // Stores the contents of a URL public: webAddressInfo(); // Default constructor webAddressInfo(const Vector<char>& info); // Initializer constructor, copies contents of supplied vector into underlying vector webAddressInfo(const webAddressInfo& info); // Copy constructor, copies contents of info's underlying url into current vector virtual ~webAddressInfo(); void setWebAddressInfo(const Vector<char>& url); // Assigns url to given vector Vector<char>& getWebAddressInfo(); // Returns the box of the url void operator= (const webAddressInfo& info); // Overloaded equals operator, calls vector copy constructor }; // Contains any amount of webAddresses, allows output and transitions between urls, as well as removal and changing class browserTab { friend ostream& operator<< (ostream& s, browserTab& info); // Overloaded cstream operator, signified as friend so is able to access the underlying webAddress protected: int numAddress; // Current capacity of web addresses in this tab Vector<webAddressInfo> *webAddresses; // Web addresses in this tab int currentAddress; // index of current location in webAddresses int getNumAddress(); // Resets the current capacity integer int resetCurrentAddress(); // Resets the current address integer public: browserTab(); // Default constructor browserTab(const Vector<char>& inputString); // Initializer, creates a webAddressInfo object with a url, and adds it to vector browserTab(const browserTab& tab); // Copy constructor, copies contents of supplied tab to current tab virtual ~browserTab(); // Destructor webAddressInfo& forward(); // Returns 'box' for either the the next url, or the current one if on most recent url webAddressInfo& backward(); // Returns 'box' for either the previous url, or the current one if on least recent url void addAddress(const Vector<char>& inputString); // Instantiates a webAddressInfo object and adds it to the current webAddresses vector; sets current index to numAddress - 1, and resets capacity; prints added url void changeCurrentAddress(const Vector<char>& newAddress); // Changes the webAddressInfo object from newAddress to the current index of webAddresses void operator= (const browserTab& tab); // Overloaded equals operator, calls vector copy constructor }; #pragma region webAddressInfo webAddressInfo::webAddressInfo() { try { url = new Vector<char>(201); } catch (ArrayMemoryException memory) { cout << "Jinkies!" << endl; } } webAddressInfo::webAddressInfo(const Vector<char>& newUrl) { try { url = new Vector<char>(newUrl); } catch (ArrayMemoryException memory) { cout << "Gadzooks!" << endl; } } webAddressInfo::webAddressInfo(const webAddressInfo& info) { try { url = info.url; } catch (ArrayMemoryException memory) { cout << "Oh no!" << endl; } } webAddressInfo::~webAddressInfo() { if (url != NULL) {} } void webAddressInfo::setWebAddressInfo(const Vector<char>& newUrl) { try { if (url != NULL) { *url = newUrl; } } catch (ArrayMemoryException memory) { cout << "You've lost your marbles!" << endl; } } Vector<char>& webAddressInfo::getWebAddressInfo() { return *url; } void webAddressInfo::operator=(const webAddressInfo& info) { try { url = info.url; } catch (ArrayMemoryException memory) { cout << "Ruh-roh" << endl; } } ostream& operator<< (ostream& s, webAddressInfo& info) { try { for (int i = 0; i < info.getWebAddressInfo().size(); ++i) { s << info.getWebAddressInfo()[i]; } } catch (ArrayBoundsException bounds) { s << "You've crossed a line"; } return s; } #pragma endregion Methods #pragma region browserTab browserTab::browserTab() { try { webAddresses = new Vector<webAddressInfo>(20); numAddress = 0; currentAddress = -1; } catch (ArrayMemoryException memory) { cout << "Help, I need somebody" << endl; } } browserTab::browserTab(const Vector<char>& inputURL) { try { webAddresses = new Vector<webAddressInfo>(20); numAddress = 0; currentAddress = -1; addAddress(inputURL); } catch (ArrayException memory) { cout << "Now you've done it" << endl; } } browserTab::browserTab(const browserTab& info) { webAddresses = info.webAddresses; numAddress = (*info.webAddresses).capacity(); currentAddress = (*info.webAddresses).size() - 1; } browserTab::~browserTab() { if (webAddresses != NULL) { delete webAddresses; } numAddress = 0; currentAddress = -1; } int browserTab::resetCurrentAddress() { currentAddress = -1; if (webAddresses != NULL) { currentAddress = (*webAddresses).size() - 1; } else { throw ArrayMemoryException(); } return currentAddress; } int browserTab::getNumAddress() { numAddress = 0; if (webAddresses != NULL) { numAddress = (*webAddresses).capacity(); } else { throw ArrayMemoryException(); } return numAddress; } webAddressInfo& browserTab::forward() { if (currentAddress + 1 < (*webAddresses).size()) { ++currentAddress; return (*webAddresses)[currentAddress]; } else { resetCurrentAddress(); // In case current address index is somehow greater than or equal to numAddress index cout << "Already on the most recent url - "; } return (*webAddresses)[currentAddress]; } webAddressInfo& browserTab::backward() { if (currentAddress > 0) { --currentAddress; return (*webAddresses)[currentAddress]; } else { if (webAddresses == NULL) { throw ArrayBoundsException(); } cout << "Already moved back as far as possible - "; currentAddress = 0; // In case current address index is somehow less than zero } return (*webAddresses)[currentAddress]; } void browserTab::changeCurrentAddress(const Vector<char>& newAddress) { webAddressInfo *newUrl = new webAddressInfo(newAddress); cout << *newUrl; (*webAddresses)[currentAddress] = (*newUrl); } void browserTab::addAddress(const Vector<char>& inputURL) { webAddressInfo *url = new webAddressInfo(inputURL); (*webAddresses).add(*url); resetCurrentAddress(); getNumAddress(); cout << (*url) << endl; } ostream& operator<< (ostream& s, browserTab& info) { s << *info.webAddresses; return s; } void browserTab::operator= (const browserTab& tab) { try { *webAddresses = (*tab.webAddresses); resetCurrentAddress(); getNumAddress(); } catch (ArrayMemoryException memory) { cout << "Ruh-roh" << endl; } } #pragma endregion Methods // Removes all characters in a vector void strEmpty(Vector<char>& str) { for (int i = str.size() - 1; i >= 0; --i) { str.remove(i); } } int main() { char command; // Given command, e.g. New tab, forward, backward, or print char blank; // Offload variable, junk char aChar; // Reads in url to char, for safety Vector<char> *webAddress = new Vector<char>(201); // Vector web address to be wrapped into object Vector<browserTab> *myTabs = new Vector<browserTab>(20); // Creates a browserTab vector with capacity of 20 int tabNumber; // Tab number on whic the action will take place bool shouldTakeAction; // Check if the program should follow the command // While end of line is not reached // Skips blank space like Taylor Swift while (cin >> tabNumber) { cin.get(blank); cin.get(command); strEmpty(*webAddress); try { switch (command) { case 'N': { // New url cin.get(blank); shouldTakeAction = false; // Reads given url to the webAddress vector do { cin.get(aChar); if (aChar != '\n') { try { (*webAddress).add(aChar); shouldTakeAction = true; } catch (ArrayBoundsException bounds) { cout << "Pshhhh as if" << endl; } } } while ((aChar != '\n') && !cin.eof()); if (shouldTakeAction) { cout << "Adding address to tab #" << tabNumber << " - "; try { // Should create a new tab if (tabNumber - 1 == (*myTabs).size()) { browserTab *tab = new browserTab(*webAddress); (*myTabs).add(*tab); } // Should add a url to an existing tab else if (tabNumber - 1 < (*myTabs).size()) { (*myTabs)[tabNumber - 1].addAddress(*webAddress); } // Supplied tab number is out of bounds else { throw IncorrectTab(); } } catch (IncorrectTab) { cout << "Tab #" << tabNumber << " doesn't exist" << endl; } } break; } case 'F': { // Forward cout << "Attempting to move forwards in tab #" << tabNumber << " - "; try { // Should move forward if (tabNumber - 1 < (*myTabs).size()) { cout << (*myTabs)[tabNumber - 1].forward() << endl; } // Suplied tab number is out of bounds else { throw IncorrectTab(); } } catch (ArrayBoundsException) { cout << "Out of bounds" << endl; } catch (IncorrectTab) { cout << "Tab #" << tabNumber << " doesn't exist" << endl; } break; } case 'B': { // Backward cout << "Attempting to move backwards in tab #" << tabNumber << " - "; try { // Should move backward if (tabNumber - 1 < (*myTabs).size()) { cout << (*myTabs)[tabNumber - 1].backward() << endl; } // Supplied tab number is out of bounds else { throw IncorrectTab(); } } catch (IncorrectTab) { cout << "Tab #" << tabNumber << " doesn't exist" << endl; } break; } case 'P': { // Print current cout << "Printing contents of tab #" << tabNumber << " - "; try { // Should print tab contents if (tabNumber - 1 < (*myTabs).size()) { cout << (*myTabs)[tabNumber - 1] << endl; } // Supplied tab number is out of bounds else { throw IncorrectTab(); } } catch (IncorrectTab) { cout << "Tab #" << tabNumber << " doesn't exist" << endl; } break; } case 'M': { int otherTabNumber; // The second tab number cin >> otherTabNumber; try { cout << "Attempting to move tab #" << tabNumber << " before tab #" << otherTabNumber << " - "; // Should move tabNumber before otherTabNumber if (tabNumber > otherTabNumber) { browserTab info = (*myTabs)[1/*tabNumber -1*/]; cout << "BEFORE" << (*myTabs)[0] << " " << (*myTabs)[1/*otherTabNumber - 1*/] << endl; (*myTabs).insert(info, 0/*otherTabNumber - 1*/); cout << "AFTER" << (*myTabs)[0/*tabNumber - 1*/] << " " << (*myTabs)[1/*otherTabNumber - 1*/] << endl; } else { cout << "Tab is already before other tab"; } } catch (ArrayBoundsException) { cout << "Tab #" << tabNumber << " doesn't exist"; } cout << endl; break; } case 'R': { cout << "Attempting to remove tab #" << tabNumber << " - "; try { // Should remove tab if (tabNumber - 1 < (*myTabs).size()) { cout << (*myTabs)[tabNumber - 1]; (*myTabs).remove(tabNumber - 1); } // Supplied tab number is out of bounds else { throw IncorrectTab(); } } catch (IncorrectTab) { cout << "Tab #" << tabNumber << " doesn't exist"; } cout << endl; break; } case 'C': { cin.get(blank); shouldTakeAction = false; do { // Reads given url into the webAddressInfo vector cin.get(aChar); if (aChar != '\n') { try { shouldTakeAction = true; (*webAddress).add(aChar); } catch (ArrayBoundsException outOfBounds) { cout << "You so sillyyy" << endl; } } } while ((aChar != '\n') && !cin.eof()); if (shouldTakeAction) { cout << "Changing the current address in tab #" << tabNumber << " - "; try { // Should change currentAddress if (tabNumber - 1 < (*myTabs).size()) { (*myTabs)[tabNumber - 1].changeCurrentAddress(*webAddress); } // Supplied tab number is out of bounds else { throw IncorrectTab(); } } catch (IncorrectTab) { cout << "Tab #" << tabNumber << " doesn't exist"; } cout << endl; } break; } default: { // Illegal action // Move to end of line in case extra information do { cin.get(aChar); if (aChar != '\n') { try { (*webAddress).add(aChar); } catch (ArrayBoundsException bounds) { cout << "Alohamora" << endl; } } } while ((aChar != '\n') && !cin.eof()); throw IncorrectAction(); break; } } } catch (IncorrectAction incorrect) { cout << "Illegal Action" << endl; } } return 0; }
32.89233
217
0.653379
[ "object", "vector" ]
7cca822575258b5f65fd6070e6bc3dced69fc9bd
5,751
cpp
C++
src/map.cpp
LukaC256/termsweeper
295199139ca8785c5df51ab9cb837faff6efc7a1
[ "MIT" ]
null
null
null
src/map.cpp
LukaC256/termsweeper
295199139ca8785c5df51ab9cb837faff6efc7a1
[ "MIT" ]
null
null
null
src/map.cpp
LukaC256/termsweeper
295199139ca8785c5df51ab9cb837faff6efc7a1
[ "MIT" ]
null
null
null
#include "map.hpp" #include "characters.hpp" #include "vector.hpp" #include <cstdlib> #include <ctime> #include <random> #include <iostream> using namespace std; const CVector vDirs[] = { CVector(-1, -1), CVector(0, -1), CVector(1, -1), CVector(-1, 0), CVector(1, 0), CVector(-1, 1), CVector(0, 1), CVector(1, 1) }; CMap::CMap(const CVector size, const int mines) : m_size(size), m_mines(mines), m_staticMap(size), m_dynamicMap(size) { // Fill the Map with zeroes / ones for (size_t y = 0; y < m_size.y; y++) { for (size_t x = 0; x < m_size.x; x++) { m_staticMap.Set(CVector(x, y), 0); m_dynamicMap.Set(CVector(x, y), 1); } } // Place mines randomly, but if there's already one // at that place, try again random_device seed_ng; default_random_engine ran_ng(seed_ng()); // Seed generator uniform_int_distribution<int> x_pos(0, m_size.x - 1); uniform_int_distribution<int> y_pos(0, m_size.y - 1); for (size_t i = 0; i < m_mines; i++) { while (true) { int x = x_pos(ran_ng); int y = y_pos(ran_ng); //cout << "pos: " << x << " : " << y << m_staticMap[x][y] << endl; if (m_staticMap.Get(CVector(x, y)) != 9) { m_staticMap.Set(CVector(x, y), 9); break; } } } // Generate number fields for (size_t y = 0; y < m_size.y; y++) { for (size_t x = 0; x < m_size.x; x++) { CVector pos(x, y); if (m_staticMap.Get(pos) == 9) continue; int minecnt = 0; for (size_t d = 0; d < 8; d++) { if (m_staticMap.Get(pos + vDirs[d]) == 9) minecnt++; } m_staticMap.Set(pos, minecnt); } } } void CMap::printMap(bool showEntireField) { cerr << "\x1b[H\x1b[J "; for (size_t i = 0; i < m_size.x; i++) { cerr << (char) (65 + i); } cerr << endl; int num_flags = 0; for (size_t y = 0; y < m_size.y; y++) { cerr << y << ' '; for (size_t x = 0; x < m_size.x; x++) { uint8_t iDynamicField = m_dynamicMap.Get(CVector(x, y)); uint8_t iStaticField = m_staticMap.Get(CVector(x, y)); if (showEntireField && iDynamicField != 2) iDynamicField = 0; switch (iDynamicField) { case 0: { switch (iStaticField) { case 9: if (showEntireField) cerr << "\x1b[1;31m" << charMine << "\x1b[0m"; else cerr << "‽"; // This SHOULD be unreachable... break; case 0: if ((x + (y%2)) % 2) { cerr << "\x1b[1;30m" << charFree << "\x1b[0m"; } else cerr << charFree; break; default: cerr << "\x1b[" << numberColors[iStaticField-1] << "m" << (char) (48+iStaticField) << "\x1b[0m"; break; } break; } case 1: if ((x + (y%2)) % 2) { cerr << "\x1b[1;30m" << charHidden << "\x1b[0m"; } else cerr << charHidden; break; case 2: if (showEntireField && iStaticField == 9) cerr << "\x1b[1;32m" << charFlag << "\x1b[0m"; else if (showEntireField) cerr << "\x1b[1;31m" << charFlag << "\x1b[0m"; else cerr << charFlag; num_flags++; break; case 3: cerr << '?'; break; } } cerr << ' ' << y << endl; } cerr << " "; for (size_t i = 0; i < m_size.x; i++) { cerr << (char) (65 + i); } cerr << endl; cerr << "Flags: " << num_flags << "/" << m_mines << endl; } void CMap::printMessages() { while (!m_messageQueue.empty()) { cerr << m_messageQueue.front() << endl; m_messageQueue.pop(); } } bool CMap::Try(CVector pos) { if (pos.x >= m_size.x || pos.x < 0 || pos.y >= m_size.y || pos.y < 0) return true; if (m_dynamicMap.Get(pos) == 0) return true; m_dynamicMap.Set(pos, 0); switch (m_staticMap.Get(pos)) { case 0: for (size_t d = 0; d < 8; d++) { Try(pos + vDirs[d]); } break; case 9: return false; default: break; } return true; } bool CMap::TryAround(CVector pos) { if (m_staticMap.Get(pos) == 0) { m_messageQueue.push(string("This operation is not permitted!")); return true; } int flagcnt = 0; for (size_t d = 0; d < 8; d++) { if (m_dynamicMap.Get(pos + vDirs[d]) == 2) flagcnt++; } if (flagcnt < m_staticMap.Get(pos)) { m_messageQueue.push(string("This operation is not permitted!")); return true; } for (size_t d = 0; d < 8; d++) { if (m_dynamicMap.Get(pos + vDirs[d]) != 2) { if (!Try(pos+vDirs[d])) return false; } } return true; } void CMap::Flag(CVector pos) { if (pos.x >= m_size.x || pos.x < 0 || pos.y >= m_size.y || pos.y < 0) { m_messageQueue.push(string("This field is outside the range!")); return; } int field = m_dynamicMap.Get(pos); if (field == 0) { m_messageQueue.push(string("This field cannot be flagged!")); return; } if (field == 2) { m_dynamicMap.Set(pos, 1); m_messageQueue.push(string("Flag removed!")); } else { m_dynamicMap.Set(pos, 2); m_messageQueue.push(string("Field flagged!")); } } void CMap::Mark(CVector pos) { if (pos.x >= m_size.x || pos.x < 0 || pos.y >= m_size.y || pos.y < 0) { m_messageQueue.push(string("This field is outside the range!")); return; } int field = m_dynamicMap.Get(pos); if (field == 0) { m_messageQueue.push(string("This field cannot be marked!")); return; } if (field == 3) { m_dynamicMap.Set(pos, 1); m_messageQueue.push(string("Mark removed!")); } else { m_dynamicMap.Set(pos, 3); m_messageQueue.push(string("Field marked!")); } } bool CMap::GameWon() { for (size_t y = 0; y < m_size.y; y++) { for (size_t x = 0; x < m_size.x; x++) { if (m_staticMap.Get(CVector(x,y)) != 9 && m_dynamicMap.Get(CVector(x,y)) != 0) return false; } } // Game is won, set all mines under flags for (size_t y = 0; y < m_size.y; y++) { for (size_t x = 0; x < m_size.x; x++) { if (m_staticMap.Get(CVector(x,y)) == 9) m_dynamicMap.Set(CVector(x,y), 2); } } return true; }
20.321555
101
0.569814
[ "vector" ]
7cccfe4b4afe2fd2b31c01c14824f3d5c8857037
2,635
cpp
C++
src/Constellation.cpp
cooperhewitt/Planetary
03b152c255d191e3a0f6e90369126b8017ac60c0
[ "BSD-3-Clause" ]
43
2015-02-07T13:30:03.000Z
2021-08-02T02:58:57.000Z
src/Constellation.cpp
bobwol/Planetary
03b152c255d191e3a0f6e90369126b8017ac60c0
[ "BSD-3-Clause" ]
4
2015-01-04T23:54:22.000Z
2021-05-12T09:56:09.000Z
src/Constellation.cpp
bobwol/Planetary
03b152c255d191e3a0f6e90369126b8017ac60c0
[ "BSD-3-Clause" ]
23
2015-01-03T10:00:37.000Z
2021-04-16T18:57:52.000Z
// // Constellation.cpp // Kepler // // Created by Tom Carden on 6/14/11. // Copyright 2013 Smithsonian Institution. All rights reserved. // #include "Constellation.h" #include "cinder/gl/gl.h" #include "Globals.h" using std::vector; using namespace ci; void Constellation::setup(const vector<NodeArtist*> &filteredNodes) { mConstellation.clear(); //mConstellationColors.clear(); // CREATE DATA FOR CONSTELLATION vector<float> distances; // used for tex coords of the dotted line for( vector<NodeArtist*>::const_iterator it1 = filteredNodes.begin(); it1 != filteredNodes.end(); ++it1 ){ NodeArtist *child1 = *it1; float shortestDist = 5000.0f; NodeArtist *nearestChild; vector<NodeArtist*>::const_iterator it2 = it1; for( ++it2; it2 != filteredNodes.end(); ++it2 ) { NodeArtist *child2 = *it2; Vec3f dirBetweenChildren = child1->mPosDest - child2->mPosDest; float distBetweenChildren = dirBetweenChildren.length(); if( distBetweenChildren < shortestDist ){ shortestDist = distBetweenChildren; nearestChild = child2; } } distances.push_back( shortestDist ); mConstellation.push_back( child1->mPosDest ); mConstellation.push_back( nearestChild->mPosDest ); } mTotalConstellationVertices = mConstellation.size(); if (mTotalConstellationVertices != mPrevTotalConstellationVertices) { if (mConstellationVerts != NULL) delete[] mConstellationVerts; mConstellationVerts = new VertexData[mTotalConstellationVertices]; mPrevTotalConstellationVertices = mTotalConstellationVertices; } int vIndex = 0; int distancesIndex = 0; for( int i=0; i<mTotalConstellationVertices; i++ ){ Vec3f pos = mConstellation[i]; mConstellationVerts[vIndex].vertex = mConstellation[i]; if( i%2 == 0 ){ mConstellationVerts[vIndex].texture = Vec2f(0.0f, 0.5f); } else { mConstellationVerts[vIndex].texture = Vec2f(distances[distancesIndex], 0.5f); distancesIndex++; } vIndex++; } } void Constellation::draw( const float &alpha ) const { if( mTotalConstellationVertices > 2 ){ gl::color( ColorA( 0.12f, 0.25f, 0.85f, alpha ) ); glEnableClientState( GL_VERTEX_ARRAY ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); glVertexPointer( 3, GL_FLOAT, sizeof(VertexData), mConstellationVerts ); glTexCoordPointer( 2, GL_FLOAT, sizeof(VertexData), &mConstellationVerts[0].texture ); glDrawArrays( GL_LINES, 0, mTotalConstellationVertices ); glDisableClientState( GL_VERTEX_ARRAY ); glDisableClientState( GL_TEXTURE_COORD_ARRAY ); } }
30.639535
107
0.69981
[ "vector" ]
7ccf87bdb260d4ee963f3b7002621c4b5b9997a3
363
cpp
C++
problems/single_number.cpp
zZnghialamZz/CSLearning
315ad93c76add64e31e6ade182c7d1a3fdffcc18
[ "MIT" ]
null
null
null
problems/single_number.cpp
zZnghialamZz/CSLearning
315ad93c76add64e31e6ade182c7d1a3fdffcc18
[ "MIT" ]
null
null
null
problems/single_number.cpp
zZnghialamZz/CSLearning
315ad93c76add64e31e6ade182c7d1a3fdffcc18
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> class Solution { public: static int single_number(const std::vector<int>& input) { int unique = 0; for (const int& i : input) { unique ^= i; } return unique; } }; int main() { std::vector<int> input { 4, 1, 2, 1, 2 }; std::cout << Solution().single_number(input) << std::endl; return 0; }
17.285714
60
0.586777
[ "vector" ]
7ced491b97eb063e914c24ec662e8d3ff23b008c
1,908
cpp
C++
lightoj/nf wa 1353 - Paths in a Tree bfs dfs .cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
1
2021-11-22T02:26:43.000Z
2021-11-22T02:26:43.000Z
lightoj/nf wa 1353 - Paths in a Tree bfs dfs .cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
lightoj/nf wa 1353 - Paths in a Tree bfs dfs .cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long long ll; //int kk[111]; int vis[20100]; int par[20100]; vector<int> conn [20100]; // void dfs(int u, int par) { // printf("u %d\n", u); int len = conn[u].size(); vis[u]++; // printf("len %d\n"); // int ans=0; for(int i=0; i<len; i++) { if(vis[ conn[u][i] ] != par) { dfs(conn[u][i], u); } } // return 0; // return ans+ max( (int)conn[u].size()-1 , 0); } int t, n=0, u, v; int calc() { int ans=0; vector<int > vec; int x=0; for(int i=0; i<n; i++) { vec.push_back(i); if( par[i]== -1) { swap(vec[i], vec[x++]); // printf("root %d\n", i); } } int len = vec.size(); // printf("len_vec %d\n", len); for(int i=0; i<len; i++) { // if(!conn[i].size()) // { if(!vis[vec[i] ]) { // printf("leaf_u %d\n", vec[i]); ans ++; dfs(vec[i], -1); } } // printf("ans after dfs %d\n", ans); for(int i=0; i<n; i++) ans+= max( (int)conn[i].size()- vis[i], 0); return ans; } int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); std::ios_base::sync_with_stdio(false); cin.tie(0); memset(par, -1, sizeof par); scanf("%d", &t); for(int tc=1; tc<=t; tc++) { for(int i=0; i<=n; i++) { vis[i]=0; conn[i].clear(); par[i]= -1; } scanf("%d", &n); for(int i=1; i<n; i++) { scanf("%d %d",&u, &v); par[u] = v; conn[v].push_back(u); // par[v]++; } printf("Case %d: %d\n",tc, calc()); } return 0; }
18.891089
71
0.375262
[ "vector" ]
7cf6bd76e9ec52a7397093fdc9b1bc74cf778707
27,218
cc
C++
libs/quadwild/libs/CoMISo/NSolver/TAOSolver.cc
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
216
2018-09-09T11:53:56.000Z
2022-03-19T13:41:35.000Z
libs/quadwild/libs/CoMISo/NSolver/TAOSolver.cc
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
13
2018-10-23T08:29:09.000Z
2021-09-08T06:45:34.000Z
libs/quadwild/libs/CoMISo/NSolver/TAOSolver.cc
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
41
2018-09-13T08:50:41.000Z
2022-02-23T00:33:54.000Z
//============================================================================= // // CLASS TAOSolver - IMPLEMENTATION // //============================================================================= //== COMPILE-TIME PACKAGE REQUIREMENTS ======================================== #include <CoMISo/Config/config.hh> #if COMISO_TAO_AVAILABLE //== INCLUDES ================================================================= #include "TAOSolver.hh" //#include <dlfcn.h> //== NAMESPACES =============================================================== namespace COMISO { //== IMPLEMENTATION ========================================================== // static member initialization bool TAOSolver::initialized_ = false; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // interface of TAO was changed from version 1 to 2 !!! #if (TAO_VERSION_MAJOR < 2) int TAOSolver:: solve( NProblemGmmInterface* _base) { // // initialize (only once) // initialize(); // std::cerr << "tao 1\n"; // // MPI_Init(0,0); // char *libm="libmpi.so"; // dlopen(libm,RTLD_GLOBAL); if(!initialized_) { /* Initialize TAO,PETSc */ // non command line arguments necessary ... std::cerr << "Initialize MPI/Petsc/TAO "; static char help[] ="help\n"; int argc = 0; char **argv; // MPI_Init(&argc, &argv); PetscInitialize( &argc, &argv,(char *)0,help ); TaoInitialize ( &argc, &argv,(char *)0,help ); initialized_ = true; std::cerr << " done!!!\n"; } /* used to check for functions returning nonzeros */ int info; // check for single processor int size; MPI_Comm_size(MPI_COMM_WORLD,&size); if (size >1) { PetscPrintf(PETSC_COMM_SELF,"TAOSolver is intended for single processor use!\n"); SETERRQ(1,"Incorrect number of processors"); } /* Create TAO solver and set desired solution method */ // TaoMethod method="tao_cg"; /* minimization method */ TaoMethod method="tao_ntr"; /* minimization method */ // TaoMethod method="tao_nm"; /* minimization method */ TAO_SOLVER tao; /* TAO_SOLVER solver context */ TAO_APPLICATION testapp; /* The PETSc application */ info = TaoCreate(PETSC_COMM_SELF,method,&tao); CHKERRQ(info); info = TaoApplicationCreate(PETSC_COMM_SELF,&testapp); CHKERRQ(info); // initalize vector int n = _base->n_unknowns(); Vec x; info = VecCreateSeq(PETSC_COMM_SELF, n, &x); CHKERRQ(info); PetscScalar* X; info = VecGetArray(x,&X); CHKERRQ(info); _base->initial_x(X); info = VecRestoreArray(x,&X); CHKERRQ(info); // initialize matrix /* Create a matrix data structure to store the Hessian. This structure will be used by TAO */ Mat H; // ToDo: get nonzero_pattern // int nnz[1]; nnz[0] = 1; // info = MatCreateSeqAIJ(PETSC_COMM_SELF,n,n,0,nnz,&H); /* PETSc routine */ info = MatCreateSeqAIJ(PETSC_COMM_SELF,n,n,0,0,&H); /* PETSc routine */ info = MatSetOption(H,MAT_SYMMETRIC,PETSC_TRUE); CHKERRQ(info); /* PETSc flag */ info = TaoAppSetHessianMat(testapp,H,H); CHKERRQ(info); /* A TAO routine */ // initialize solution vector info = TaoAppSetInitialSolutionVec(testapp,x); CHKERRQ(info); /* Provide TAO routines for function evaluation */ info = TaoAppSetObjectiveRoutine(testapp, objective, (void*) _base); CHKERRQ(info); info = TaoAppSetGradientRoutine (testapp, gradient , (void*) _base); CHKERRQ(info); info = TaoAppSetHessianRoutine (testapp, hessian , (void*) _base); CHKERRQ(info); /* SOLVE THE APPLICATION */ info = TaoSolveApplication(testapp,tao); CHKERRQ(info); /* Get information on termination */ TaoTerminateReason reason; info = TaoGetTerminationReason(tao,&reason); CHKERRQ(info); if (reason <= 0) std::cerr << "Warning: TAO-Solver did not converge!!!\n"; else std::cerr << "TAO-Solver converged!!!\n"; // To View TAO solver information use info = TaoView(tao); CHKERRQ(info); // if successfull get and store result // if( reason) { info = TaoAppGetSolutionVec(testapp, &x); info = VecGetArray(x,&X); CHKERRQ(info); _base->store_result( X); info = VecRestoreArray(x,&X); CHKERRQ(info); } // VecView(x, PETSC_VIEWER_STDOUT_WORLD); // /* Free TAO data structures */ info = TaoDestroy(tao); CHKERRQ(info); info = TaoAppDestroy(testapp); CHKERRQ(info); return reason; } //----------------------------------------------------------------------------- int TAOSolver:: solve( NProblemInterface* _base) { // // initialize (only once) // initialize(); // std::cerr << "tao 1\n"; // // MPI_Init(0,0); // char *libm="libmpi.so"; // dlopen(libm,RTLD_GLOBAL); if(!initialized_) { /* Initialize TAO,PETSc */ // non command line arguments necessary ... std::cerr << "Initialize MPI/Petsc/TAO "; static char help[] ="help\n"; int argc = 0; char **argv; // MPI_Init(&argc, &argv); PetscInitialize( &argc, &argv,(char *)0,help ); TaoInitialize ( &argc, &argv,(char *)0,help ); initialized_ = true; std::cerr << " done!!!\n"; } /* used to check for functions returning nonzeros */ int info; // check for single processor int size; MPI_Comm_size(MPI_COMM_WORLD,&size); if (size >1) { PetscPrintf(PETSC_COMM_SELF,"TAOSolver is intended for single processor use!\n"); SETERRQ(1,"Incorrect number of processors"); } /* Create TAO solver and set desired solution method */ // TaoMethod method="tao_cg"; /* minimization method */ TaoMethod method="tao_ntr"; /* minimization method */ // TaoMethod method="tao_nm"; /* minimization method */ TAO_SOLVER tao; /* TAO_SOLVER solver context */ TAO_APPLICATION testapp; /* The PETSc application */ info = TaoCreate(PETSC_COMM_SELF,method,&tao); CHKERRQ(info); info = TaoApplicationCreate(PETSC_COMM_SELF,&testapp); CHKERRQ(info); // initalize vector int n = _base->n_unknowns(); Vec x; info = VecCreateSeq(PETSC_COMM_SELF, n, &x); CHKERRQ(info); PetscScalar* X; info = VecGetArray(x,&X); CHKERRQ(info); _base->initial_x(X); info = VecRestoreArray(x,&X); CHKERRQ(info); // initialize matrix /* Create a matrix data structure to store the Hessian. This structure will be used by TAO */ Mat H; // ToDo: get nonzero_pattern // int nnz[1]; nnz[0] = 1; // info = MatCreateSeqAIJ(PETSC_COMM_SELF,n,n,0,nnz,&H); /* PETSc routine */ info = MatCreateSeqAIJ(PETSC_COMM_SELF,n,n,0,0,&H); /* PETSc routine */ info = MatSetOption(H,MAT_SYMMETRIC,PETSC_TRUE); CHKERRQ(info); /* PETSc flag */ info = TaoAppSetHessianMat(testapp,H,H); CHKERRQ(info); /* A TAO routine */ // initialize solution vector info = TaoAppSetInitialSolutionVec(testapp,x); CHKERRQ(info); /* Provide TAO routines for function evaluation */ info = TaoAppSetObjectiveRoutine(testapp, objective2, (void*) _base); CHKERRQ(info); info = TaoAppSetGradientRoutine (testapp, gradient2 , (void*) _base); CHKERRQ(info); info = TaoAppSetHessianRoutine (testapp, hessian2 , (void*) _base); CHKERRQ(info); /* SOLVE THE APPLICATION */ info = TaoSolveApplication(testapp,tao); CHKERRQ(info); /* Get information on termination */ TaoTerminateReason reason; info = TaoGetTerminationReason(tao,&reason); CHKERRQ(info); if (reason <= 0) std::cerr << "Warning: TAO-Solver did not converge!!!\n"; else std::cerr << "TAO-Solver converged!!!\n"; // To View TAO solver information use info = TaoView(tao); CHKERRQ(info); // if successfull get and store result // if( reason) { info = TaoAppGetSolutionVec(testapp, &x); info = VecGetArray(x,&X); CHKERRQ(info); _base->store_result( X); info = VecRestoreArray(x,&X); CHKERRQ(info); } // VecView(x, PETSC_VIEWER_STDOUT_WORLD); // /* Free TAO data structures */ info = TaoDestroy(tao); CHKERRQ(info); info = TaoAppDestroy(testapp); CHKERRQ(info); return reason; } //----------------------------------------------------------------------------- int TAOSolver:: objective( TAO_APPLICATION _app, Vec _x, double* _result, void* _base) { NProblemGmmInterface* base = (NProblemGmmInterface*) _base; PetscScalar *x; /* Get pointers to vector data */ int info = VecGetArray(_x,&x); CHKERRQ(info); // evaluate function (*_result) = base->eval_f(x); /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- int TAOSolver:: gradient(TAO_APPLICATION _app, Vec _x, Vec _g, void* _base) { NProblemGmmInterface* base = (NProblemGmmInterface*) _base; PetscScalar *x, *g; int info; /* Get pointers to vector data */ info = VecGetArray(_x,&x); CHKERRQ(info); info = VecGetArray(_g,&g); CHKERRQ(info); // compute gradient base->eval_gradient( x, g); /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); info = VecRestoreArray(_g,&g); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- int TAOSolver:: hessian(TAO_APPLICATION _app, Vec _x, Mat* _H, Mat* _H_pre, MatStructure* _H_struct, void* _base) { NProblemGmmInterface* base = (NProblemGmmInterface*) _base; PetscScalar *x; /* Get pointers to vector data */ int info = VecGetArray(_x,&x); CHKERRQ(info); /* Initialize matrix entries to zero */ info = MatZeroEntries(*_H); CHKERRQ(info); // iterate over non-zero elements NProblemGmmInterface::SMatrixNP H; base->eval_hessian( x, H); for (unsigned int i = 0; i < gmm::mat_nrows(H); ++i) { typedef gmm::linalg_traits<NProblemGmmInterface::SMatrixNP>::const_sub_row_type CRow; CRow row = gmm::mat_const_row(H, i); gmm::linalg_traits<CRow>::const_iterator it = gmm::vect_const_begin(row); gmm::linalg_traits<CRow>::const_iterator ite = gmm::vect_const_end(row); int m = 1; int n = 1; int idxm[1]; idxm[0] = i; int idxn[1]; PetscScalar values[1]; for(; it != ite; ++it) { idxn[0] = it.index(); values[0] = *it; info = MatSetValues(*_H, m, idxm, n, idxn, values, INSERT_VALUES); } } /* Assemble the matrix */ info = MatAssemblyBegin(*_H,MAT_FINAL_ASSEMBLY); CHKERRQ(info); info = MatAssemblyEnd(*_H,MAT_FINAL_ASSEMBLY); CHKERRQ(info); *_H_struct = SAME_NONZERO_PATTERN; /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- int TAOSolver:: objective2( TAO_APPLICATION _app, Vec _x, double* _result, void* _base) { NProblemInterface* base = (NProblemInterface*) _base; PetscScalar *x; /* Get pointers to vector data */ int info = VecGetArray(_x,&x); CHKERRQ(info); // evaluate function (*_result) = base->eval_f(x); /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- int TAOSolver:: gradient2(TAO_APPLICATION _app, Vec _x, Vec _g, void* _base) { NProblemInterface* base = (NProblemInterface*) _base; PetscScalar *x, *g; int info; /* Get pointers to vector data */ info = VecGetArray(_x,&x); CHKERRQ(info); info = VecGetArray(_g,&g); CHKERRQ(info); // compute gradient base->eval_gradient( x, g); /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); info = VecRestoreArray(_g,&g); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- int TAOSolver:: hessian2(TAO_APPLICATION _app, Vec _x, Mat* _H, Mat* _H_pre, MatStructure* _H_struct, void* _base) { NProblemInterface* base = (NProblemInterface*) _base; PetscScalar *x; /* Get pointers to vector data */ int info = VecGetArray(_x,&x); CHKERRQ(info); /* Initialize matrix entries to zero */ info = MatZeroEntries(*_H); CHKERRQ(info); // iterate over non-zero elements NProblemInterface::SMatrixNP H; base->eval_hessian( x, H); for(int i=0; i<H.outerSize(); ++i) { int m = 1; int n = 1; int idxm[1]; idxm[0] = i; int idxn[1]; PetscScalar values[1]; for (NProblemInterface::SMatrixNP::InnerIterator it(H,i); it; ++it) { idxm[0] = it.row(); idxn[0] = it.col(); values[0] = it.value(); info = MatSetValues(*_H, m, idxm, n, idxn, values, INSERT_VALUES); } } /* Assemble the matrix */ info = MatAssemblyBegin(*_H,MAT_FINAL_ASSEMBLY); CHKERRQ(info); info = MatAssemblyEnd(*_H,MAT_FINAL_ASSEMBLY); CHKERRQ(info); *_H_struct = SAME_NONZERO_PATTERN; /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- void TAOSolver:: initialize() { if(!initialized_) { /* Initialize TAO,PETSc */ // non command line arguments necessary ... std::cerr << "Initialize MPI/Petsc/TAO "; static char help[] ="help\n"; static int argc = 0; static char **argv; // MPI_Init(&argc, &argv); PetscInitialize( &argc, &argv,(char *)0,help ); TaoInitialize ( &argc, &argv,(char *)0,help ); initialized_ = true; std::cerr << " done!!!\n"; } } //----------------------------------------------------------------------------- void TAOSolver:: cleanup() { /* Finalize TAO */ TaoFinalize(); PetscFinalize(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #else // (TAO_VERSION_MAJOR < 2) //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int TAOSolver:: solve( NProblemGmmInterface* _base) { // // initialize (only once) // initialize(); // std::cerr << "tao 1\n"; // // MPI_Init(0,0); // char *libm="libmpi.so"; // dlopen(libm,RTLD_GLOBAL); if(!initialized_) { /* Initialize TAO,PETSc */ // non command line arguments necessary ... std::cerr << "Initialize MPI/Petsc/TAO "; static char help[] ="help\n"; int argc = 0; char **argv; // MPI_Init(&argc, &argv); PetscInitialize( &argc, &argv,(char *)0,help ); TaoInitialize ( &argc, &argv,(char *)0,help ); initialized_ = true; std::cerr << " done!!!\n"; } /* used to check for functions returning nonzeros */ int info; // check for single processor int size; MPI_Comm_size(MPI_COMM_WORLD,&size); if (size >1) { PetscPrintf(PETSC_COMM_SELF,"TAOSolver is intended for single processor use!\n"); SETERRQ(PETSC_COMM_SELF,1,"Incorrect number of processors"); } /* Create TAO solver with desired solution method */ TaoSolver tao; /* TaoSolver solver context */ TaoCreate(PETSC_COMM_SELF,&tao); TaoSetType(tao,"tao_ntr"); /* Create TAO solver and set desired solution method */ // TaoMethod method="tao_cg"; /* minimization method */ // TaoMethod method="tao_ntr"; /* minimization method */ // TaoMethod method="tao_nm"; /* minimization method */ // TAO_SOLVER tao; /* TAO_SOLVER solver context */ // TAO_APPLICATION testapp; /* The PETSc application */ // info = TaoCreate(PETSC_COMM_SELF,method,&tao); CHKERRQ(info); // info = TaoApplicationCreate(PETSC_COMM_SELF,&testapp); CHKERRQ(info); // initalize vector int n = _base->n_unknowns(); Vec x; info = VecCreateSeq(PETSC_COMM_SELF, n, &x); CHKERRQ(info); PetscScalar* X; info = VecGetArray(x,&X); CHKERRQ(info); _base->initial_x(X); info = VecRestoreArray(x,&X); CHKERRQ(info); // initialize matrix /* Create a matrix data structure to store the Hessian. This structure will be used by TAO */ Mat H; // ToDo: get nonzero_pattern // int nnz[1]; nnz[0] = 1; // info = MatCreateSeqAIJ(PETSC_COMM_SELF,n,n,0,nnz,&H); /* PETSc routine */ info = MatCreateSeqAIJ(PETSC_COMM_SELF,n,n,0,0,&H); /* PETSc routine */ info = MatSetOption(H,MAT_SYMMETRIC,PETSC_TRUE); CHKERRQ(info); /* PETSc flag */ //info = TaoAppSetHessianMat(testapp,H,H); CHKERRQ(info); /* A TAO routine */ // initialize solution vector // info = TaoAppSetInitialSolutionVec(testapp,x); CHKERRQ(info); TaoSetInitialVector(tao,x); /* Provide TAO routines for function evaluation */ TaoSetObjectiveRoutine(tao, objective, (void*) _base); TaoSetGradientRoutine (tao, gradient , (void*) _base); TaoSetHessianRoutine (tao, H, H, hessian , (void*) _base); /* SOLVE */ TaoSolve(tao); /* Get information on termination */ TaoSolverTerminationReason reason; TaoGetTerminationReason(tao,&reason); if (reason <= 0) std::cerr << "Warning: TAO-Solver did not converge!!!\n"; else std::cerr << "TAO-Solver converged!!!\n"; // To View TAO solver information use info = TaoView(tao, PETSC_VIEWER_STDOUT_SELF); CHKERRQ(info); // if successfull get and store result // if( reason) { TaoGetSolutionVector(tao, &x); info = VecGetArray(x,&X); CHKERRQ(info); _base->store_result( X); info = VecRestoreArray(x,&X); CHKERRQ(info); } // VecView(x, PETSC_VIEWER_STDOUT_WORLD); // /* Free TAO data structures */ TaoDestroy(&tao); /* Free PETSc data structures */ VecDestroy(&x); MatDestroy(&H); TaoFinalize(); return reason; } //----------------------------------------------------------------------------- int TAOSolver:: solve( NProblemInterface* _base) { // // initialize (only once) // initialize(); // std::cerr << "tao 1\n"; // // MPI_Init(0,0); // char *libm="libmpi.so"; // dlopen(libm,RTLD_GLOBAL); if(!initialized_) { /* Initialize TAO,PETSc */ // non command line arguments necessary ... std::cerr << "Initialize MPI/Petsc/TAO "; static char help[] ="help\n"; int argc = 0; char **argv; // MPI_Init(&argc, &argv); PetscInitialize( &argc, &argv,(char *)0,help ); TaoInitialize ( &argc, &argv,(char *)0,help ); initialized_ = true; std::cerr << " done!!!\n"; } /* used to check for functions returning nonzeros */ int info; // check for single processor int size; MPI_Comm_size(MPI_COMM_WORLD,&size); if (size >1) { PetscPrintf(PETSC_COMM_SELF,"TAOSolver is intended for single processor use!\n"); SETERRQ(PETSC_COMM_SELF,1,"Incorrect number of processors"); } /* Create TAO solver with desired solution method */ TaoSolver tao; /* TaoSolver solver context */ TaoCreate(PETSC_COMM_SELF,&tao); TaoSetType(tao,"tao_ntr"); /* Create TAO solver and set desired solution method */ // TaoMethod method="tao_cg"; /* minimization method */ // TaoMethod method="tao_ntr"; /* minimization method */ // TaoMethod method="tao_nm"; /* minimization method */ // TAO_SOLVER tao; /* TAO_SOLVER solver context */ // TAO_APPLICATION testapp; /* The PETSc application */ // info = TaoCreate(PETSC_COMM_SELF,method,&tao); CHKERRQ(info); // info = TaoApplicationCreate(PETSC_COMM_SELF,&testapp); CHKERRQ(info); // initalize vector int n = _base->n_unknowns(); Vec x; info = VecCreateSeq(PETSC_COMM_SELF, n, &x); CHKERRQ(info); PetscScalar* X; info = VecGetArray(x,&X); CHKERRQ(info); _base->initial_x(X); info = VecRestoreArray(x,&X); CHKERRQ(info); // initialize matrix /* Create a matrix data structure to store the Hessian. This structure will be used by TAO */ Mat H; // ToDo: get nonzero_pattern // int nnz[1]; nnz[0] = 1; // info = MatCreateSeqAIJ(PETSC_COMM_SELF,n,n,0,nnz,&H); /* PETSc routine */ info = MatCreateSeqAIJ(PETSC_COMM_SELF,n,n,0,0,&H); /* PETSc routine */ info = MatSetOption(H,MAT_SYMMETRIC,PETSC_TRUE); CHKERRQ(info); /* PETSc flag */ //info = TaoAppSetHessianMat(testapp,H,H); CHKERRQ(info); /* A TAO routine */ // initialize solution vector // info = TaoAppSetInitialSolutionVec(testapp,x); CHKERRQ(info); TaoSetInitialVector(tao,x); /* Provide TAO routines for function evaluation */ TaoSetObjectiveRoutine(tao, objective2, (void*) _base); TaoSetGradientRoutine (tao, gradient2 , (void*) _base); TaoSetHessianRoutine (tao, H, H, hessian2 , (void*) _base); /* SOLVE */ TaoSolve(tao); /* Get information on termination */ TaoSolverTerminationReason reason; TaoGetTerminationReason(tao,&reason); if (reason <= 0) std::cerr << "Warning: TAO-Solver did not converge!!!\n"; else std::cerr << "TAO-Solver converged!!!\n"; // To View TAO solver information use info = TaoView(tao, PETSC_VIEWER_STDOUT_SELF); CHKERRQ(info); // if successfull get and store result // if( reason) { TaoGetSolutionVector(tao, &x); info = VecGetArray(x,&X); CHKERRQ(info); _base->store_result( X); info = VecRestoreArray(x,&X); CHKERRQ(info); } // VecView(x, PETSC_VIEWER_STDOUT_WORLD); // /* Free TAO data structures */ TaoDestroy(&tao); /* Free PETSc data structures */ VecDestroy(&x); MatDestroy(&H); TaoFinalize(); return reason; } //----------------------------------------------------------------------------- int TAOSolver:: objective( TaoSolver _tao, Vec _x, double* _result, void* _base) { NProblemGmmInterface* base = (NProblemGmmInterface*) _base; PetscScalar *x; /* Get pointers to vector data */ int info = VecGetArray(_x,&x); CHKERRQ(info); // evaluate function (*_result) = base->eval_f(x); /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- int TAOSolver:: gradient(TaoSolver _tao, Vec _x, Vec _g, void* _base) { NProblemGmmInterface* base = (NProblemGmmInterface*) _base; PetscScalar *x, *g; int info; /* Get pointers to vector data */ info = VecGetArray(_x,&x); CHKERRQ(info); info = VecGetArray(_g,&g); CHKERRQ(info); // compute gradient base->eval_gradient( x, g); /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); info = VecRestoreArray(_g,&g); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- int TAOSolver:: hessian(TaoSolver _tao, Vec _x, Mat* _H, Mat* _H_pre, MatStructure* _H_struct, void* _base) { NProblemGmmInterface* base = (NProblemGmmInterface*) _base; PetscScalar *x; /* Get pointers to vector data */ int info = VecGetArray(_x,&x); CHKERRQ(info); /* Initialize matrix entries to zero */ info = MatZeroEntries(*_H); CHKERRQ(info); // iterate over non-zero elements NProblemGmmInterface::SMatrixNP H; base->eval_hessian( x, H); for (unsigned int i = 0; i < gmm::mat_nrows(H); ++i) { typedef gmm::linalg_traits<NProblemGmmInterface::SMatrixNP>::const_sub_row_type CRow; CRow row = gmm::mat_const_row(H, i); gmm::linalg_traits<CRow>::const_iterator it = gmm::vect_const_begin(row); gmm::linalg_traits<CRow>::const_iterator ite = gmm::vect_const_end(row); int m = 1; int n = 1; int idxm[1]; idxm[0] = i; int idxn[1]; PetscScalar values[1]; for(; it != ite; ++it) { idxn[0] = it.index(); values[0] = *it; info = MatSetValues(*_H, m, idxm, n, idxn, values, INSERT_VALUES); } } /* Assemble the matrix */ info = MatAssemblyBegin(*_H,MAT_FINAL_ASSEMBLY); CHKERRQ(info); info = MatAssemblyEnd(*_H,MAT_FINAL_ASSEMBLY); CHKERRQ(info); *_H_struct = SAME_NONZERO_PATTERN; /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- int TAOSolver:: objective2( TaoSolver _tao, Vec _x, double* _result, void* _base) { NProblemInterface* base = (NProblemInterface*) _base; PetscScalar *x; /* Get pointers to vector data */ int info = VecGetArray(_x,&x); CHKERRQ(info); // evaluate function (*_result) = base->eval_f(x); /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- int TAOSolver:: gradient2(TaoSolver _tao, Vec _x, Vec _g, void* _base) { NProblemInterface* base = (NProblemInterface*) _base; PetscScalar *x, *g; int info; /* Get pointers to vector data */ info = VecGetArray(_x,&x); CHKERRQ(info); info = VecGetArray(_g,&g); CHKERRQ(info); // compute gradient base->eval_gradient( x, g); /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); info = VecRestoreArray(_g,&g); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- int TAOSolver:: hessian2(TaoSolver _tao, Vec _x, Mat* _H, Mat* _H_pre, MatStructure* _H_struct, void* _base) { NProblemInterface* base = (NProblemInterface*) _base; PetscScalar *x; /* Get pointers to vector data */ int info = VecGetArray(_x,&x); CHKERRQ(info); /* Initialize matrix entries to zero */ info = MatZeroEntries(*_H); CHKERRQ(info); // iterate over non-zero elements NProblemInterface::SMatrixNP H; base->eval_hessian( x, H); for(int i=0; i<H.outerSize(); ++i) { int m = 1; int n = 1; int idxm[1]; idxm[0] = i; int idxn[1]; PetscScalar values[1]; for (NProblemInterface::SMatrixNP::InnerIterator it(H,i); it; ++it) { idxm[0] = it.row(); idxn[0] = it.col(); values[0] = it.value(); info = MatSetValues(*_H, m, idxm, n, idxn, values, INSERT_VALUES); } } /* Assemble the matrix */ info = MatAssemblyBegin(*_H,MAT_FINAL_ASSEMBLY); CHKERRQ(info); info = MatAssemblyEnd(*_H,MAT_FINAL_ASSEMBLY); CHKERRQ(info); *_H_struct = SAME_NONZERO_PATTERN; /* Restore vectors */ info = VecRestoreArray(_x,&x); CHKERRQ(info); return 0; } //----------------------------------------------------------------------------- void TAOSolver:: initialize() { if(!initialized_) { /* Initialize TAO,PETSc */ // non command line arguments necessary ... std::cerr << "Initialize MPI/Petsc/TAO "; static char help[] ="help\n"; static int argc = 0; static char **argv; // MPI_Init(&argc, &argv); PetscInitialize( &argc, &argv,(char *)0,help ); TaoInitialize ( &argc, &argv,(char *)0,help ); initialized_ = true; std::cerr << " done!!!\n"; } } //----------------------------------------------------------------------------- void TAOSolver:: cleanup() { /* Finalize TAO */ TaoFinalize(); PetscFinalize(); } #endif //============================================================================= } // namespace COMISO //============================================================================= #endif // COMISO_TAO_AVAILABLE
27.218
98
0.587075
[ "vector" ]
cfb3053dfb88aa0a492d14c148d0d1f173f91452
1,030
cpp
C++
Languages/C++/median.cpp
Nandini2901/Hacktoberfest-1
ac5eff7c8678f3ce00041bdba20c63c416dac690
[ "MIT" ]
1
2020-10-03T03:17:03.000Z
2020-10-03T03:17:03.000Z
Languages/C++/median.cpp
Nandini2901/Hacktoberfest-1
ac5eff7c8678f3ce00041bdba20c63c416dac690
[ "MIT" ]
1
2020-10-01T18:03:45.000Z
2020-10-01T18:03:45.000Z
Languages/C++/median.cpp
Nandini2901/Hacktoberfest-1
ac5eff7c8678f3ce00041bdba20c63c416dac690
[ "MIT" ]
4
2020-10-07T14:58:50.000Z
2020-10-24T10:13:17.000Z
#include <iostream> #include <vector> #include <algorithm> using namespace std; int getMedian(vector<int> a, int n, int median) { sort(a.begin(),a.end()); int mid = a.at(n/2); int count = 0,i; if(mid == median) return 0; if(mid < median) { for(i = n/2; a.at(i) < median; i++) { while(a.at(i) < median) { a.at(i)++; count++; } } return count; } for(i = 0; i < n/2; i++) { while(a.at(i) > median) { a.at(i)--; count++; } } return count; } int main() { int t = 0; cin >> t ; while(t--) { int n = 0, median = 0; cin >> n >> median; vector<int> a; int ip = 0,i; for( i = 0; i < n; i++) { cin >> ip ; a.push_back(ip); } cout << getMedian(a,n,median) << endl; } return 0; }
18.727273
48
0.363107
[ "vector" ]
cfb39c4411a8c9c416c9f9284a0c6f98b566fe39
44,048
hpp
C++
hpx/runtime/actions/preprocessed/construct_continuation_functions_5.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/runtime/actions/preprocessed/construct_continuation_functions_5.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/runtime/actions/preprocessed/construct_continuation_functions_5.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2013 Hartmut Kaiser // Copyright (c) 2012-2013 Thomas Heller // // 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) // This file has been automatically generated using the Boost.Wave tool. // Do not edit manually. struct continuation_thread_object_function_void_0 { typedef threads::thread_state_enum result_type; template <typename Object > BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* func)(), Object* obj ) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object > BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* const func)( ) const, Component* obj ) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ > static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* func)(), Object* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_0(), cont, func, obj ); } template <typename Object, typename Arguments_ > static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* const func)() const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_0(), cont, func, obj ); } struct continuation_thread_object_function_0 { typedef threads::thread_state_enum result_type; template <typename Object > BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* func)(), Component* obj ) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)() )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object > BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* const func)( ) const, Component* obj ) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)() )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ > static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* func)(), Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_0(), cont, func, obj ); } template <typename Object, typename Arguments_ > static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* const func)() const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_0(), cont, func, obj ); } struct continuation_thread_object_function_void_1 { typedef threads::thread_state_enum result_type; template <typename Object , typename Arg0 , typename FArg0> BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* func)(FArg0 arg0), Object* obj , BOOST_FWD_REF(Arg0) arg0) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(boost::move(arg0)); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object , typename Arg0 , typename FArg0> BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* const func)( FArg0 arg0) const, Component* obj , BOOST_FWD_REF(Arg0) arg0) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(boost::move(arg0)); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ , typename FArg0> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* func)(FArg0), Object* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_1(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0)); } template <typename Object, typename Arguments_ , typename FArg0> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* const func)(FArg0) const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_1(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0)); } struct continuation_thread_object_function_1 { typedef threads::thread_state_enum result_type; template <typename Object , typename Arg0 , typename FArg0> BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* func)(FArg0 arg0), Component* obj , BOOST_FWD_REF(Arg0) arg0) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)(boost::move(arg0)) )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object , typename Arg0 , typename FArg0> BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* const func)( FArg0 arg0) const, Component* obj , BOOST_FWD_REF(Arg0) arg0) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)(boost::move(arg0)) )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ , typename FArg0> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* func)(FArg0), Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_1(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0)); } template <typename Object, typename Arguments_ , typename FArg0> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* const func)(FArg0) const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_1(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0)); } struct continuation_thread_object_function_void_2 { typedef threads::thread_state_enum result_type; template <typename Object , typename Arg0 , typename Arg1 , typename FArg0 , typename FArg1> BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* func)(FArg0 arg0 , FArg1 arg1), Object* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(boost::move(arg0) , boost::move(arg1)); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object , typename Arg0 , typename Arg1 , typename FArg0 , typename FArg1> BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* const func)( FArg0 arg0 , FArg1 arg1) const, Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(boost::move(arg0) , boost::move(arg1)); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* func)(FArg0 , FArg1), Object* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_2(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1)); } template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* const func)(FArg0 , FArg1) const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_2(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1)); } struct continuation_thread_object_function_2 { typedef threads::thread_state_enum result_type; template <typename Object , typename Arg0 , typename Arg1 , typename FArg0 , typename FArg1> BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* func)(FArg0 arg0 , FArg1 arg1), Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)(boost::move(arg0) , boost::move(arg1)) )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object , typename Arg0 , typename Arg1 , typename FArg0 , typename FArg1> BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* const func)( FArg0 arg0 , FArg1 arg1) const, Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)(boost::move(arg0) , boost::move(arg1)) )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* func)(FArg0 , FArg1), Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_2(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1)); } template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* const func)(FArg0 , FArg1) const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_2(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1)); } struct continuation_thread_object_function_void_3 { typedef threads::thread_state_enum result_type; template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename FArg0 , typename FArg1 , typename FArg2> BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* func)(FArg0 arg0 , FArg1 arg1 , FArg2 arg2), Object* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2)); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename FArg0 , typename FArg1 , typename FArg2> BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* const func)( FArg0 arg0 , FArg1 arg1 , FArg2 arg2) const, Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2)); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* func)(FArg0 , FArg1 , FArg2), Object* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_3(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2)); } template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* const func)(FArg0 , FArg1 , FArg2) const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_3(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2)); } struct continuation_thread_object_function_3 { typedef threads::thread_state_enum result_type; template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename FArg0 , typename FArg1 , typename FArg2> BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* func)(FArg0 arg0 , FArg1 arg1 , FArg2 arg2), Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2)) )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename FArg0 , typename FArg1 , typename FArg2> BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* const func)( FArg0 arg0 , FArg1 arg1 , FArg2 arg2) const, Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2)) )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* func)(FArg0 , FArg1 , FArg2), Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_3(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2)); } template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* const func)(FArg0 , FArg1 , FArg2) const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_3(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2)); } struct continuation_thread_object_function_void_4 { typedef threads::thread_state_enum result_type; template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename Arg3 , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3> BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* func)(FArg0 arg0 , FArg1 arg1 , FArg2 arg2 , FArg3 arg3), Object* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2 , BOOST_FWD_REF(Arg3) arg3) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2) , boost::move(arg3)); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename Arg3 , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3> BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* const func)( FArg0 arg0 , FArg1 arg1 , FArg2 arg2 , FArg3 arg3) const, Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2 , BOOST_FWD_REF(Arg3) arg3) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2) , boost::move(arg3)); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* func)(FArg0 , FArg1 , FArg2 , FArg3), Object* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_4(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type3>( args. a3)); } template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* const func)(FArg0 , FArg1 , FArg2 , FArg3) const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_4(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type3>( args. a3)); } struct continuation_thread_object_function_4 { typedef threads::thread_state_enum result_type; template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename Arg3 , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3> BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* func)(FArg0 arg0 , FArg1 arg1 , FArg2 arg2 , FArg3 arg3), Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2 , BOOST_FWD_REF(Arg3) arg3) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2) , boost::move(arg3)) )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename Arg3 , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3> BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* const func)( FArg0 arg0 , FArg1 arg1 , FArg2 arg2 , FArg3 arg3) const, Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2 , BOOST_FWD_REF(Arg3) arg3) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2) , boost::move(arg3)) )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* func)(FArg0 , FArg1 , FArg2 , FArg3), Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_4(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type3>( args. a3)); } template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* const func)(FArg0 , FArg1 , FArg2 , FArg3) const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_4(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type3>( args. a3)); } struct continuation_thread_object_function_void_5 { typedef threads::thread_state_enum result_type; template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename Arg3 , typename Arg4 , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3 , typename FArg4> BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* func)(FArg0 arg0 , FArg1 arg1 , FArg2 arg2 , FArg3 arg3 , FArg4 arg4), Object* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2 , BOOST_FWD_REF(Arg3) arg3 , BOOST_FWD_REF(Arg4) arg4) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2) , boost::move(arg3) , boost::move(arg4)); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename Arg3 , typename Arg4 , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3 , typename FArg4> BOOST_FORCEINLINE result_type operator()(continuation_type cont, void (Object::* const func)( FArg0 arg0 , FArg1 arg1 , FArg2 arg2 , FArg3 arg3 , FArg4 arg4) const, Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2 , BOOST_FWD_REF(Arg3) arg3 , BOOST_FWD_REF(Arg4) arg4) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2) , boost::move(arg3) , boost::move(arg4)); cont->trigger(); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3 , typename FArg4> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* func)(FArg0 , FArg1 , FArg2 , FArg3 , FArg4), Object* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_5(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type3>( args. a3) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type4>( args. a4)); } template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3 , typename FArg4> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function_void( continuation_type cont, void (Object::* const func)(FArg0 , FArg1 , FArg2 , FArg3 , FArg4) const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_void_5(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type3>( args. a3) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type4>( args. a4)); } struct continuation_thread_object_function_5 { typedef threads::thread_state_enum result_type; template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename Arg3 , typename Arg4 , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3 , typename FArg4> BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* func)(FArg0 arg0 , FArg1 arg1 , FArg2 arg2 , FArg3 arg3 , FArg4 arg4), Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2 , BOOST_FWD_REF(Arg3) arg3 , BOOST_FWD_REF(Arg4) arg4) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2) , boost::move(arg3) , boost::move(arg4)) )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } template <typename Object , typename Arg0 , typename Arg1 , typename Arg2 , typename Arg3 , typename Arg4 , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3 , typename FArg4> BOOST_FORCEINLINE result_type operator()(continuation_type cont, Result (Object::* const func)( FArg0 arg0 , FArg1 arg1 , FArg2 arg2 , FArg3 arg3 , FArg4 arg4) const, Component* obj , BOOST_FWD_REF(Arg0) arg0 , BOOST_FWD_REF(Arg1) arg1 , BOOST_FWD_REF(Arg2) arg2 , BOOST_FWD_REF(Arg3) arg3 , BOOST_FWD_REF(Arg4) arg4) const { try { LTM_(debug) << "Executing action(" << detail::get_action_name<derived_type>() << ") with continuation(" << cont->get_gid() << ")"; cont->trigger(boost::move( (obj->*func)(boost::move(arg0) , boost::move(arg1) , boost::move(arg2) , boost::move(arg3) , boost::move(arg4)) )); } catch (...) { cont->trigger_error(boost::current_exception()); } return threads::terminated; } }; template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3 , typename FArg4> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* func)(FArg0 , FArg1 , FArg2 , FArg3 , FArg4), Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_5(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type3>( args. a3) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type4>( args. a4)); } template <typename Object, typename Arguments_ , typename FArg0 , typename FArg1 , typename FArg2 , typename FArg3 , typename FArg4> static HPX_STD_FUNCTION<threads::thread_function_type> construct_continuation_thread_object_function( continuation_type cont, Result (Object::* const func)(FArg0 , FArg1 , FArg2 , FArg3 , FArg4) const, Component* obj, BOOST_FWD_REF(Arguments_) args) { return HPX_STD_BIND( continuation_thread_object_function_5(), cont, func, obj , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type0>( args. a0) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type1>( args. a1) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type2>( args. a2) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type3>( args. a3) , boost::forward< typename util::remove_reference<Arguments_>::type:: member_type4>( args. a4)); }
42.476374
490
0.558663
[ "object" ]
cfbf316a240bef76417455d6fa6f39f9acb46c75
1,828
cpp
C++
problems/encoding-decoding/PrintDecodedDigitSequence.cpp
rahulpawar1489/Algorithms
bdf26092f141526b7f3147772732bfbfb4fe1a17
[ "MIT" ]
1
2022-01-02T12:17:19.000Z
2022-01-02T12:17:19.000Z
problems/encoding-decoding/PrintDecodedDigitSequence.cpp
rahulpawar1489/Algorithms
bdf26092f141526b7f3147772732bfbfb4fe1a17
[ "MIT" ]
null
null
null
problems/encoding-decoding/PrintDecodedDigitSequence.cpp
rahulpawar1489/Algorithms
bdf26092f141526b7f3147772732bfbfb4fe1a17
[ "MIT" ]
1
2021-03-27T18:42:13.000Z
2021-03-27T18:42:13.000Z
// https://www.geeksforgeeks.org/print-all-possible-decodings-of-a-given-digit-sequence/ #include <iostream> #include <string> #include <vector> void printVector(std::vector<std::string>& vector) { for (auto str : vector) { std::cout << str << " "; } std::cout << "\n"; } char getChar(int digit) { return static_cast<char>(digit + 97); } std::vector<std::string> getDecoded(std::string str) { if (str.size() == 0) { std::vector<std::string> res; res.push_back(""); return res; } std::vector<std::string> output1 = getDecoded(str.substr(1)); std::vector<std::string> output2 (0); int firstDigit = (str[0] - '0'); int firstTwoDigits = 0; if (str.size() >= 2) { firstTwoDigits = (str[0] - '0') * 10 + str[1] - '0'; if (firstTwoDigits >= 10 && firstTwoDigits <= 26) { output2 = getDecoded(str.substr(2)); } } std::vector<std::string> output (output1.size() + output2.size()); int k = 0; char ch = getChar(firstDigit); for (int i = 0; i < output1.size(); ++i) { output[i] = ch + output1[i]; k++; } ch = getChar(firstTwoDigits); for (int i = 0; i < output2.size(); ++i) { output[k] = ch + output2[i]; k++; } return output; } int main() { std::string str = "1234"; std::cout << "str : " << str << "\n"; std::vector<std::string> output = getDecoded(str); printVector(output); std::cout << "=========================\n"; str = "12121"; std::cout << "str : " << str << "\n"; output = getDecoded(str); printVector(output); std::cout << "=========================\n"; str = "101"; std::cout << "str : " << str << "\n"; output = getDecoded(str); printVector(output); return 0; }
22.024096
88
0.515317
[ "vector" ]
cfbf40ea5be118c9497bce31e97e8d258acd778a
9,823
hpp
C++
byte_code.hpp
rcdomigan/atl
6a6777a2f714480366551a4462c986a2f9d7612f
[ "Apache-2.0" ]
null
null
null
byte_code.hpp
rcdomigan/atl
6a6777a2f714480366551a4462c986a2f9d7612f
[ "Apache-2.0" ]
42
2015-01-01T20:20:29.000Z
2017-05-31T02:02:58.000Z
byte_code.hpp
rcdomigan/atl
6a6777a2f714480366551a4462c986a2f9d7612f
[ "Apache-2.0" ]
null
null
null
#ifndef BYTE_CODE_HPP #define BYTE_CODE_HPP /** * @file /home/ryan/programming/atl/byte_code.hpp * @author Ryan Domigan <ryan_domigan@sutdents@uml.edu> * Created on Oct 01, 2015 * * Definition of the byte-code for my dumb assembler/linker */ #include <iostream> #include <map> #include <string> #include <vector> #include <cassert> #include <boost/preprocessor/seq/enum.hpp> #include <boost/preprocessor/seq/for_each.hpp> #include <boost/preprocessor/seq/for_each_i.hpp> #include <boost/preprocessor/punctuation/comma_if.hpp> #include <boost/preprocessor/stringize.hpp> #include "./type.hpp" #include "./utility.hpp" #include "./exception.hpp" // Stack layout the opcodes expect, bottom --> top: // if_ : [pc-of-alternate-branch][predicate-value] // fn_pntr : [arg1]...[argN][N][function-pointer] // std_function : [arg1]...[argN][N][function-object-pointer] // push : [word] // pop : [out-going] // jump : [destination address] // return_ : [return-value] // argument : [offset] // nested_argument : [offset][hops] // tail_call : [arg0]..[argN][N][procedure-address] // call_closure : [arg0]..[argN][closure-address] // closure_argument : [arg-offset] // make_closure : [arg1]...[argN][N] // finish : - // define : [closure-pointer][slot] // deref_slot : [slot] #define ATL_NORMAL_BYTE_CODES (nop)(push)(pop)(if_)(std_function)(jump)(return_)(argument)(nested_argument)(tail_call)(call_closure)(closure_argument)(make_closure)(deref_slot)(define) #define ATL_BYTE_CODES (finish)(push_word)ATL_NORMAL_BYTE_CODES #define ATL_VM_SPECIAL_BYTE_CODES (finish) // Have to be interpreted specially by the run/switch statement #define ATL_VM_NORMAL_BYTE_CODES ATL_NORMAL_BYTE_CODES #define ATL_ASSEMBLER_SPECIAL_BYTE_CODES (push) // overloads the no argument version #define ATL_ASSEMBLER_NORMAL_BYTE_CODES (finish)ATL_NORMAL_BYTE_CODES namespace atl { namespace vm_codes { template<class T> struct Name; template<class T> struct Tag; const size_t number_of_instructions = BOOST_PP_SEQ_SIZE(ATL_BYTE_CODES); namespace values { enum code { BOOST_PP_SEQ_ENUM(ATL_BYTE_CODES) }; } #define M(r, data, i, instruction) \ struct instruction; \ template<> struct Tag<instruction> { static const tag_t value = i; }; \ template<> struct Name<instruction> { constexpr static const char* value = BOOST_PP_STRINGIZE(instruction); }; BOOST_PP_SEQ_FOR_EACH_I(M, _, ATL_BYTE_CODES) #undef M #define M(r, data, i, instruction) BOOST_PP_COMMA_IF(i) Name<instruction>::value static const char *instruction_names[] = { BOOST_PP_SEQ_FOR_EACH_I(M, _, ATL_BYTE_CODES) }; #undef M static const char* name(tag_t instruction) { if(instruction >= number_of_instructions) return "<CODE UNDEFINED>"; return instruction_names[instruction]; } static const char* name_or_null(tag_t instruction) { if(instruction >= number_of_instructions) return nullptr; return instruction_names[instruction]; } } struct OffsetTable { typedef std::unordered_map<std::string, size_t> Table; typedef std::unordered_multimap<size_t, std::string> ReverseTable; Table table; ReverseTable reverse_table; /*** Create or update an entry in the offset tables * @param name: name of the symbol referencing this piece of code * @param pos: position in the code being referenced */ void set(std::string const& name, size_t pos) { auto old = table.find(name); if(old != table.end()) { auto range = reverse_table.equal_range(old->second); for(auto itr = range.first; itr != range.second; ++itr) { if(itr->second == name) { reverse_table.erase(itr); break; } } } table[name] = pos; reverse_table.emplace(std::make_pair(pos, name)); } Range<typename ReverseTable::const_iterator> symbols_at(size_t pos) const { auto range = reverse_table.equal_range(pos); return make_range(range.first, range.second); } size_t operator[](std::string const& name) { return table[name]; } }; /** The "AssembleCode" helper class just needs a working push_back. Add an abstract base so I can wrap byte-code in a way that either extends the container or over-writes existing code. */ typedef std::vector<pcode::value_type> CodeBacker; struct Code { typedef typename pcode::value_type value_type; typedef typename CodeBacker::iterator iterator; typedef typename CodeBacker::const_iterator const_iterator; OffsetTable offset_table; size_t num_slots; CodeBacker code; Code() : num_slots(0) {}; Code(size_t initial_size) : num_slots(0), code(initial_size) {} iterator begin() { return code.begin(); } iterator end() { return code.end(); } const_iterator begin() const { return code.begin(); } const_iterator end() const { return code.end(); } void push_back(uintptr_t cc) { code.push_back(cc); } size_t size() const { return code.size(); } void pop_back() { code.pop_back(); } void resize(size_t n) { code.resize(n); } bool operator==(Code const& other) const { return code == other.code; } bool operator==(Code& other) { return code == other.code; } }; struct CodePrinter { typedef CodeBacker::iterator iterator; typedef CodeBacker::value_type value_type; Code& code; int pushing; size_t pos; value_type vv; CodePrinter(Code& code_) : code(code_) , pushing(0) , pos(0) {} std::ostream& line(std::ostream &out) { auto vname = vm_codes::name_or_null(vv); out << " " << pos << ": "; if(pushing) { --pushing; out << "@" << vv; } else { if(vv == vm_codes::Tag<vm_codes::push>::value) ++pushing; out << vname; } auto sym_names = code.offset_table.symbols_at(pos); if(!sym_names.empty()) { out << "\t\t# " << sym_names.begin()->second; for(auto name : make_range(++sym_names.begin(), sym_names.end())) out << ", " << name.second; } return out; } void print(std::ostream &out) { pos = 0; pushing = 0; for(auto& vv_ : code) { vv = vv_; line(out) << std::endl; ++pos; } } void dbg() { print(std::cout); } }; struct AssembleCode { typedef uintptr_t value_type; typedef Code::const_iterator const_iterator; Code *code; AssembleCode() = default; AssembleCode(Code *code_) : code(code_) {} #define M(r, data, instruction) AssembleCode& instruction() { \ _push_back(vm_codes::Tag<vm_codes::instruction>::value); \ return *this; \ } BOOST_PP_SEQ_FOR_EACH(M, _, ATL_ASSEMBLER_NORMAL_BYTE_CODES) #undef M void _push_back(uintptr_t cc) { code->push_back(cc); } AssembleCode& patch(pcode::Offset offset, pcode::value_type value) { *(code->begin() + offset) = value; return *this; } AssembleCode& constant(uintptr_t cc) { push(); _push_back(cc); return *this; } AssembleCode& pointer(void const* cc) { return constant(reinterpret_cast<value_type>(cc)); } AssembleCode& push_tagged(const Any& aa) { constant(aa._tag); return pointer(aa.value); } pcode::Offset pos_last() { return code->size() - 1;} pcode::Offset pos_end() { return code->size(); } /* The `offset`th element from the end. Last element is 0. */ AssembleCode& closure_argument(size_t offset) { constant(offset); return closure_argument(); } AssembleCode& define(size_t slot) { constant(slot); if(slot + 1 > code->num_slots) { code->num_slots = slot + 1; } _push_back(vm_codes::Tag<vm_codes::define>::value); return *this; } AssembleCode& deref_slot(size_t slot) { constant(slot); _push_back(vm_codes::Tag<vm_codes::deref_slot>::value); return *this; } AssembleCode& make_closure(size_t formals, size_t captured) { constant(formals); constant(captured); return make_closure(); } /* Counts back from the function. Offset 0 is the first argument. */ AssembleCode& argument(uintptr_t offset) { constant(offset); return argument(); } AssembleCode& nested_argument(uintptr_t offset, uintptr_t hops) { constant(offset); constant(hops); return nested_argument(); } AssembleCode& std_function(CxxFunctor::value_type* fn, size_t arity) { constant(arity); pointer(reinterpret_cast<void*>(fn)); return std_function(); } value_type& operator[](off_t pos) { return *(code->begin() + pos); } size_t label_pos(std::string const& name) { return code->offset_table[name]; } /* Add a label to the current pos_last. */ AssembleCode& add_label(std::string const& name) { code->offset_table.set(name, pos_end()); return *this; } /* Insert the current pos_last + `offset` at the location indicated by `name`. */ AssembleCode& constant_patch_label(std::string const& name) { patch(code->offset_table[name] + 1, pos_end()); return *this; } /* Insert label's value as a constant */ AssembleCode& get_label(std::string const& name) { return constant(code->offset_table[name]); } void dbg(); }; // define out here to avoid inlining void AssembleCode::dbg() { CodePrinter printer(*code); printer.dbg(); } } // Set the flag to compile this as an app that just prints the byte // code numbers (in hex) and the corrosponding name #ifdef VM_PRINT_BYTE_CODES int main() { using namespace std; using namespace atl::vm_codes; #define M(r, data, instruction) cout << setw(15) << BOOST_PP_STRINGIZE(instruction) ": " << Tag<instruction>::value << endl; BOOST_PP_SEQ_FOR_EACH(M, _, ATL_BYTE_CODES); #undef M return 0; } #endif #endif
25.251928
184
0.664054
[ "object", "vector" ]