code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2014 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "Form/Panel.hpp" #include "Look/DialogLook.hpp" PanelControl::PanelControl(ContainerWindow &parent, const DialogLook &look, const PixelRect &rc, const WindowStyle style) { Create(parent, rc, #ifdef HAVE_CLIPPING look.background_color, #endif style); }
CnZoom/XcSoarWork
src/Form/Panel.cpp
C++
gpl-2.0
1,236
/***************************************************************************** Copyright (c) 1994, 2016, Oracle and/or its affiliates. All Rights Reserved. Copyright (c) 2012, Facebook Inc. Copyright (c) 2014, 2016, MariaDB Corporation 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, Suite 500, Boston, MA 02110-1335 USA *****************************************************************************/ /**************************************************//** @file btr/btr0btr.cc The B-tree Created 6/2/1994 Heikki Tuuri *******************************************************/ #include "btr0btr.h" #ifdef UNIV_NONINL #include "btr0btr.ic" #endif #include "fsp0fsp.h" #include "page0page.h" #include "page0zip.h" #ifndef UNIV_HOTBACKUP #include "btr0cur.h" #include "btr0sea.h" #include "btr0pcur.h" #include "btr0defragment.h" #include "rem0cmp.h" #include "lock0lock.h" #include "ibuf0ibuf.h" #include "trx0trx.h" #include "srv0mon.h" /**************************************************************//** Checks if the page in the cursor can be merged with given page. If necessary, re-organize the merge_page. @return TRUE if possible to merge. */ UNIV_INTERN ibool btr_can_merge_with_page( /*====================*/ btr_cur_t* cursor, /*!< in: cursor on the page to merge */ ulint page_no, /*!< in: a sibling page */ buf_block_t** merge_block, /*!< out: the merge block */ mtr_t* mtr); /*!< in: mini-transaction */ #endif /* UNIV_HOTBACKUP */ /**************************************************************//** Report that an index page is corrupted. */ UNIV_INTERN void btr_corruption_report( /*==================*/ const buf_block_t* block, /*!< in: corrupted block */ const dict_index_t* index) /*!< in: index tree */ { fprintf(stderr, "InnoDB: flag mismatch in space %u page %u" " index %s of table %s\n", (unsigned) buf_block_get_space(block), (unsigned) buf_block_get_page_no(block), index->name, index->table_name); if (block->page.zip.data) { buf_page_print(block->page.zip.data, buf_block_get_zip_size(block), BUF_PAGE_PRINT_NO_CRASH); } buf_page_print(buf_block_get_frame(block), 0, 0); } #ifndef UNIV_HOTBACKUP #ifdef UNIV_BLOB_DEBUG # include "srv0srv.h" # include "ut0rbt.h" /** TRUE when messages about index->blobs modification are enabled. */ static ibool btr_blob_dbg_msg; /** Issue a message about an operation on index->blobs. @param op operation @param b the entry being subjected to the operation @param ctx the context of the operation */ #define btr_blob_dbg_msg_issue(op, b, ctx) \ fprintf(stderr, op " %u:%u:%u->%u %s(%u,%u,%u)\n", \ (b)->ref_page_no, (b)->ref_heap_no, \ (b)->ref_field_no, (b)->blob_page_no, ctx, \ (b)->owner, (b)->always_owner, (b)->del) /** Insert to index->blobs a reference to an off-page column. @param index the index tree @param b the reference @param ctx context (for logging) */ UNIV_INTERN void btr_blob_dbg_rbt_insert( /*====================*/ dict_index_t* index, /*!< in/out: index tree */ const btr_blob_dbg_t* b, /*!< in: the reference */ const char* ctx) /*!< in: context (for logging) */ { if (btr_blob_dbg_msg) { btr_blob_dbg_msg_issue("insert", b, ctx); } mutex_enter(&index->blobs_mutex); rbt_insert(index->blobs, b, b); mutex_exit(&index->blobs_mutex); } /** Remove from index->blobs a reference to an off-page column. @param index the index tree @param b the reference @param ctx context (for logging) */ UNIV_INTERN void btr_blob_dbg_rbt_delete( /*====================*/ dict_index_t* index, /*!< in/out: index tree */ const btr_blob_dbg_t* b, /*!< in: the reference */ const char* ctx) /*!< in: context (for logging) */ { if (btr_blob_dbg_msg) { btr_blob_dbg_msg_issue("delete", b, ctx); } mutex_enter(&index->blobs_mutex); ut_a(rbt_delete(index->blobs, b)); mutex_exit(&index->blobs_mutex); } /**************************************************************//** Comparator for items (btr_blob_dbg_t) in index->blobs. The key in index->blobs is (ref_page_no, ref_heap_no, ref_field_no). @return negative, 0 or positive if *a<*b, *a=*b, *a>*b */ static int btr_blob_dbg_cmp( /*=============*/ const void* a, /*!< in: first btr_blob_dbg_t to compare */ const void* b) /*!< in: second btr_blob_dbg_t to compare */ { const btr_blob_dbg_t* aa = static_cast<const btr_blob_dbg_t*>(a); const btr_blob_dbg_t* bb = static_cast<const btr_blob_dbg_t*>(b); ut_ad(aa != NULL); ut_ad(bb != NULL); if (aa->ref_page_no != bb->ref_page_no) { return(aa->ref_page_no < bb->ref_page_no ? -1 : 1); } if (aa->ref_heap_no != bb->ref_heap_no) { return(aa->ref_heap_no < bb->ref_heap_no ? -1 : 1); } if (aa->ref_field_no != bb->ref_field_no) { return(aa->ref_field_no < bb->ref_field_no ? -1 : 1); } return(0); } /**************************************************************//** Add a reference to an off-page column to the index->blobs map. */ UNIV_INTERN void btr_blob_dbg_add_blob( /*==================*/ const rec_t* rec, /*!< in: clustered index record */ ulint field_no, /*!< in: off-page column number */ ulint page_no, /*!< in: start page of the column */ dict_index_t* index, /*!< in/out: index tree */ const char* ctx) /*!< in: context (for logging) */ { btr_blob_dbg_t b; const page_t* page = page_align(rec); ut_a(index->blobs); b.blob_page_no = page_no; b.ref_page_no = page_get_page_no(page); b.ref_heap_no = page_rec_get_heap_no(rec); b.ref_field_no = field_no; ut_a(b.ref_field_no >= index->n_uniq); b.always_owner = b.owner = TRUE; b.del = FALSE; ut_a(!rec_get_deleted_flag(rec, page_is_comp(page))); btr_blob_dbg_rbt_insert(index, &b, ctx); } /**************************************************************//** Add to index->blobs any references to off-page columns from a record. @return number of references added */ UNIV_INTERN ulint btr_blob_dbg_add_rec( /*=================*/ const rec_t* rec, /*!< in: record */ dict_index_t* index, /*!< in/out: index */ const ulint* offsets,/*!< in: offsets */ const char* ctx) /*!< in: context (for logging) */ { ulint count = 0; ulint i; btr_blob_dbg_t b; ibool del; ut_ad(rec_offs_validate(rec, index, offsets)); if (!rec_offs_any_extern(offsets)) { return(0); } b.ref_page_no = page_get_page_no(page_align(rec)); b.ref_heap_no = page_rec_get_heap_no(rec); del = (rec_get_deleted_flag(rec, rec_offs_comp(offsets)) != 0); for (i = 0; i < rec_offs_n_fields(offsets); i++) { if (rec_offs_nth_extern(offsets, i)) { ulint len; const byte* field_ref = rec_get_nth_field( rec, offsets, i, &len); ut_a(len != UNIV_SQL_NULL); ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE); field_ref += len - BTR_EXTERN_FIELD_REF_SIZE; if (!memcmp(field_ref, field_ref_zero, BTR_EXTERN_FIELD_REF_SIZE)) { /* the column has not been stored yet */ continue; } b.ref_field_no = i; b.blob_page_no = mach_read_from_4( field_ref + BTR_EXTERN_PAGE_NO); ut_a(b.ref_field_no >= index->n_uniq); b.always_owner = b.owner = !(field_ref[BTR_EXTERN_LEN] & BTR_EXTERN_OWNER_FLAG); b.del = del; btr_blob_dbg_rbt_insert(index, &b, ctx); count++; } } return(count); } /**************************************************************//** Display the references to off-page columns. This function is to be called from a debugger, for example when a breakpoint on ut_dbg_assertion_failed is hit. */ UNIV_INTERN void btr_blob_dbg_print( /*===============*/ const dict_index_t* index) /*!< in: index tree */ { const ib_rbt_node_t* node; if (!index->blobs) { return; } /* We intentionally do not acquire index->blobs_mutex here. This function is to be called from a debugger, and the caller should make sure that the index->blobs_mutex is held. */ for (node = rbt_first(index->blobs); node != NULL; node = rbt_next(index->blobs, node)) { const btr_blob_dbg_t* b = rbt_value(btr_blob_dbg_t, node); fprintf(stderr, "%u:%u:%u->%u%s%s%s\n", b->ref_page_no, b->ref_heap_no, b->ref_field_no, b->blob_page_no, b->owner ? "" : "(disowned)", b->always_owner ? "" : "(has disowned)", b->del ? "(deleted)" : ""); } } /**************************************************************//** Remove from index->blobs any references to off-page columns from a record. @return number of references removed */ UNIV_INTERN ulint btr_blob_dbg_remove_rec( /*====================*/ const rec_t* rec, /*!< in: record */ dict_index_t* index, /*!< in/out: index */ const ulint* offsets,/*!< in: offsets */ const char* ctx) /*!< in: context (for logging) */ { ulint i; ulint count = 0; btr_blob_dbg_t b; ut_ad(rec_offs_validate(rec, index, offsets)); if (!rec_offs_any_extern(offsets)) { return(0); } b.ref_page_no = page_get_page_no(page_align(rec)); b.ref_heap_no = page_rec_get_heap_no(rec); for (i = 0; i < rec_offs_n_fields(offsets); i++) { if (rec_offs_nth_extern(offsets, i)) { ulint len; const byte* field_ref = rec_get_nth_field( rec, offsets, i, &len); ut_a(len != UNIV_SQL_NULL); ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE); field_ref += len - BTR_EXTERN_FIELD_REF_SIZE; b.ref_field_no = i; b.blob_page_no = mach_read_from_4( field_ref + BTR_EXTERN_PAGE_NO); switch (b.blob_page_no) { case 0: /* The column has not been stored yet. The BLOB pointer must be all zero. There cannot be a BLOB starting at page 0, because page 0 is reserved for the tablespace header. */ ut_a(!memcmp(field_ref, field_ref_zero, BTR_EXTERN_FIELD_REF_SIZE)); /* fall through */ case FIL_NULL: /* the column has been freed already */ continue; } btr_blob_dbg_rbt_delete(index, &b, ctx); count++; } } return(count); } /**************************************************************//** Check that there are no references to off-page columns from or to the given page. Invoked when freeing or clearing a page. @return TRUE when no orphan references exist */ UNIV_INTERN ibool btr_blob_dbg_is_empty( /*==================*/ dict_index_t* index, /*!< in: index */ ulint page_no) /*!< in: page number */ { const ib_rbt_node_t* node; ibool success = TRUE; if (!index->blobs) { return(success); } mutex_enter(&index->blobs_mutex); for (node = rbt_first(index->blobs); node != NULL; node = rbt_next(index->blobs, node)) { const btr_blob_dbg_t* b = rbt_value(btr_blob_dbg_t, node); if (b->ref_page_no != page_no && b->blob_page_no != page_no) { continue; } fprintf(stderr, "InnoDB: orphan BLOB ref%s%s%s %u:%u:%u->%u\n", b->owner ? "" : "(disowned)", b->always_owner ? "" : "(has disowned)", b->del ? "(deleted)" : "", b->ref_page_no, b->ref_heap_no, b->ref_field_no, b->blob_page_no); if (b->blob_page_no != page_no || b->owner || !b->del) { success = FALSE; } } mutex_exit(&index->blobs_mutex); return(success); } /**************************************************************//** Count and process all references to off-page columns on a page. @return number of references processed */ UNIV_INTERN ulint btr_blob_dbg_op( /*============*/ const page_t* page, /*!< in: B-tree leaf page */ const rec_t* rec, /*!< in: record to start from (NULL to process the whole page) */ dict_index_t* index, /*!< in/out: index */ const char* ctx, /*!< in: context (for logging) */ const btr_blob_dbg_op_f op) /*!< in: operation on records */ { ulint count = 0; mem_heap_t* heap = NULL; ulint offsets_[REC_OFFS_NORMAL_SIZE]; ulint* offsets = offsets_; rec_offs_init(offsets_); ut_a(fil_page_get_type(page) == FIL_PAGE_INDEX); ut_a(!rec || page_align(rec) == page); if (!index->blobs || !page_is_leaf(page) || !dict_index_is_clust(index)) { return(0); } if (rec == NULL) { rec = page_get_infimum_rec(page); } do { offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); count += op(rec, index, offsets, ctx); rec = page_rec_get_next_const(rec); } while (!page_rec_is_supremum(rec)); if (heap) { mem_heap_free(heap); } return(count); } /**************************************************************//** Count and add to index->blobs any references to off-page columns from records on a page. @return number of references added */ UNIV_INTERN ulint btr_blob_dbg_add( /*=============*/ const page_t* page, /*!< in: rewritten page */ dict_index_t* index, /*!< in/out: index */ const char* ctx) /*!< in: context (for logging) */ { btr_blob_dbg_assert_empty(index, page_get_page_no(page)); return(btr_blob_dbg_op(page, NULL, index, ctx, btr_blob_dbg_add_rec)); } /**************************************************************//** Count and remove from index->blobs any references to off-page columns from records on a page. Used when reorganizing a page, before copying the records. @return number of references removed */ UNIV_INTERN ulint btr_blob_dbg_remove( /*================*/ const page_t* page, /*!< in: b-tree page */ dict_index_t* index, /*!< in/out: index */ const char* ctx) /*!< in: context (for logging) */ { ulint count; count = btr_blob_dbg_op(page, NULL, index, ctx, btr_blob_dbg_remove_rec); /* Check that no references exist. */ btr_blob_dbg_assert_empty(index, page_get_page_no(page)); return(count); } /**************************************************************//** Restore in index->blobs any references to off-page columns Used when page reorganize fails due to compressed page overflow. */ UNIV_INTERN void btr_blob_dbg_restore( /*=================*/ const page_t* npage, /*!< in: page that failed to compress */ const page_t* page, /*!< in: copy of original page */ dict_index_t* index, /*!< in/out: index */ const char* ctx) /*!< in: context (for logging) */ { ulint removed; ulint added; ut_a(page_get_page_no(npage) == page_get_page_no(page)); ut_a(page_get_space_id(npage) == page_get_space_id(page)); removed = btr_blob_dbg_remove(npage, index, ctx); added = btr_blob_dbg_add(page, index, ctx); ut_a(added == removed); } /**************************************************************//** Modify the 'deleted' flag of a record. */ UNIV_INTERN void btr_blob_dbg_set_deleted_flag( /*==========================*/ const rec_t* rec, /*!< in: record */ dict_index_t* index, /*!< in/out: index */ const ulint* offsets,/*!< in: rec_get_offs(rec, index) */ ibool del) /*!< in: TRUE=deleted, FALSE=exists */ { const ib_rbt_node_t* node; btr_blob_dbg_t b; btr_blob_dbg_t* c; ulint i; ut_ad(rec_offs_validate(rec, index, offsets)); ut_a(dict_index_is_clust(index)); ut_a(del == !!del);/* must be FALSE==0 or TRUE==1 */ if (!rec_offs_any_extern(offsets) || !index->blobs) { return; } b.ref_page_no = page_get_page_no(page_align(rec)); b.ref_heap_no = page_rec_get_heap_no(rec); for (i = 0; i < rec_offs_n_fields(offsets); i++) { if (rec_offs_nth_extern(offsets, i)) { ulint len; const byte* field_ref = rec_get_nth_field( rec, offsets, i, &len); ut_a(len != UNIV_SQL_NULL); ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE); field_ref += len - BTR_EXTERN_FIELD_REF_SIZE; b.ref_field_no = i; b.blob_page_no = mach_read_from_4( field_ref + BTR_EXTERN_PAGE_NO); switch (b.blob_page_no) { case 0: ut_a(memcmp(field_ref, field_ref_zero, BTR_EXTERN_FIELD_REF_SIZE)); /* page number 0 is for the page allocation bitmap */ case FIL_NULL: /* the column has been freed already */ ut_error; } mutex_enter(&index->blobs_mutex); node = rbt_lookup(index->blobs, &b); ut_a(node); c = rbt_value(btr_blob_dbg_t, node); /* The flag should be modified. */ c->del = del; if (btr_blob_dbg_msg) { b = *c; mutex_exit(&index->blobs_mutex); btr_blob_dbg_msg_issue("del_mk", &b, ""); } else { mutex_exit(&index->blobs_mutex); } } } } /**************************************************************//** Change the ownership of an off-page column. */ UNIV_INTERN void btr_blob_dbg_owner( /*===============*/ const rec_t* rec, /*!< in: record */ dict_index_t* index, /*!< in/out: index */ const ulint* offsets,/*!< in: rec_get_offs(rec, index) */ ulint i, /*!< in: ith field in rec */ ibool own) /*!< in: TRUE=owned, FALSE=disowned */ { const ib_rbt_node_t* node; btr_blob_dbg_t b; const byte* field_ref; ulint len; ut_ad(rec_offs_validate(rec, index, offsets)); ut_a(rec_offs_nth_extern(offsets, i)); field_ref = rec_get_nth_field(rec, offsets, i, &len); ut_a(len != UNIV_SQL_NULL); ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE); field_ref += len - BTR_EXTERN_FIELD_REF_SIZE; b.ref_page_no = page_get_page_no(page_align(rec)); b.ref_heap_no = page_rec_get_heap_no(rec); b.ref_field_no = i; b.owner = !(field_ref[BTR_EXTERN_LEN] & BTR_EXTERN_OWNER_FLAG); b.blob_page_no = mach_read_from_4(field_ref + BTR_EXTERN_PAGE_NO); ut_a(b.owner == own); mutex_enter(&index->blobs_mutex); node = rbt_lookup(index->blobs, &b); /* row_ins_clust_index_entry_by_modify() invokes btr_cur_unmark_extern_fields() also for the newly inserted references, which are all zero bytes until the columns are stored. The node lookup must fail if and only if that is the case. */ ut_a(!memcmp(field_ref, field_ref_zero, BTR_EXTERN_FIELD_REF_SIZE) == !node); if (node) { btr_blob_dbg_t* c = rbt_value(btr_blob_dbg_t, node); /* Some code sets ownership from TRUE to TRUE. We do not allow changing ownership from FALSE to FALSE. */ ut_a(own || c->owner); c->owner = own; if (!own) { c->always_owner = FALSE; } } mutex_exit(&index->blobs_mutex); } #endif /* UNIV_BLOB_DEBUG */ /* Latching strategy of the InnoDB B-tree -------------------------------------- A tree latch protects all non-leaf nodes of the tree. Each node of a tree also has a latch of its own. A B-tree operation normally first acquires an S-latch on the tree. It searches down the tree and releases the tree latch when it has the leaf node latch. To save CPU time we do not acquire any latch on non-leaf nodes of the tree during a search, those pages are only bufferfixed. If an operation needs to restructure the tree, it acquires an X-latch on the tree before searching to a leaf node. If it needs, for example, to split a leaf, (1) InnoDB decides the split point in the leaf, (2) allocates a new page, (3) inserts the appropriate node pointer to the first non-leaf level, (4) releases the tree X-latch, (5) and then moves records from the leaf to the new allocated page. Node pointers ------------- Leaf pages of a B-tree contain the index records stored in the tree. On levels n > 0 we store 'node pointers' to pages on level n - 1. For each page there is exactly one node pointer stored: thus the our tree is an ordinary B-tree, not a B-link tree. A node pointer contains a prefix P of an index record. The prefix is long enough so that it determines an index record uniquely. The file page number of the child page is added as the last field. To the child page we can store node pointers or index records which are >= P in the alphabetical order, but < P1 if there is a next node pointer on the level, and P1 is its prefix. If a node pointer with a prefix P points to a non-leaf child, then the leftmost record in the child must have the same prefix P. If it points to a leaf node, the child is not required to contain any record with a prefix equal to P. The leaf case is decided this way to allow arbitrary deletions in a leaf node without touching upper levels of the tree. We have predefined a special minimum record which we define as the smallest record in any alphabetical order. A minimum record is denoted by setting a bit in the record header. A minimum record acts as the prefix of a node pointer which points to a leftmost node on any level of the tree. File page allocation -------------------- In the root node of a B-tree there are two file segment headers. The leaf pages of a tree are allocated from one file segment, to make them consecutive on disk if possible. From the other file segment we allocate pages for the non-leaf levels of the tree. */ #ifdef UNIV_BTR_DEBUG /**************************************************************//** Checks a file segment header within a B-tree root page. @return TRUE if valid */ static ibool btr_root_fseg_validate( /*===================*/ const fseg_header_t* seg_header, /*!< in: segment header */ ulint space) /*!< in: tablespace identifier */ { ulint offset = mach_read_from_2(seg_header + FSEG_HDR_OFFSET); ut_a(mach_read_from_4(seg_header + FSEG_HDR_SPACE) == space); ut_a(offset >= FIL_PAGE_DATA); ut_a(offset <= UNIV_PAGE_SIZE - FIL_PAGE_DATA_END); return(TRUE); } #endif /* UNIV_BTR_DEBUG */ /**************************************************************//** Gets the root node of a tree and x- or s-latches it. @return root page, x- or s-latched */ static buf_block_t* btr_root_block_get( /*===============*/ const dict_index_t* index, /*!< in: index tree */ ulint mode, /*!< in: either RW_S_LATCH or RW_X_LATCH */ mtr_t* mtr) /*!< in: mtr */ { ulint space; ulint zip_size; ulint root_page_no; buf_block_t* block; space = dict_index_get_space(index); zip_size = dict_table_zip_size(index->table); root_page_no = dict_index_get_page(index); block = btr_block_get(space, zip_size, root_page_no, mode, (dict_index_t*)index, mtr); if (!block) { if (index && index->table) { index->table->is_encrypted = TRUE; index->table->corrupted = FALSE; ib_push_warning(index->table->thd, DB_DECRYPTION_FAILED, "Table %s in tablespace %lu is encrypted but encryption service or" " used key_id is not available. " " Can't continue reading table.", index->table->name, space); } return NULL; } btr_assert_not_corrupted(block, index); #ifdef UNIV_BTR_DEBUG if (!dict_index_is_ibuf(index)) { const page_t* root = buf_block_get_frame(block); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF + root, space)); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + root, space)); } #endif /* UNIV_BTR_DEBUG */ return(block); } /**************************************************************//** Gets the root node of a tree and x-latches it. @return root page, x-latched */ UNIV_INTERN page_t* btr_root_get( /*=========*/ const dict_index_t* index, /*!< in: index tree */ mtr_t* mtr) /*!< in: mtr */ { buf_block_t* root = btr_root_block_get(index, RW_X_LATCH, mtr); if (root && root->page.encrypted == true) { root = NULL; } return(root ? buf_block_get_frame(root) : NULL); } /**************************************************************//** Gets the height of the B-tree (the level of the root, when the leaf level is assumed to be 0). The caller must hold an S or X latch on the index. @return tree height (level of the root) */ UNIV_INTERN ulint btr_height_get( /*===========*/ dict_index_t* index, /*!< in: index tree */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint height=0; buf_block_t* root_block; ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_S_LOCK) || mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_X_LOCK)); /* S latches the page */ root_block = btr_root_block_get(index, RW_S_LATCH, mtr); if (root_block) { height = btr_page_get_level(buf_block_get_frame(root_block), mtr); /* Release the S latch on the root page. */ mtr_memo_release(mtr, root_block, MTR_MEMO_PAGE_S_FIX); #ifdef UNIV_SYNC_DEBUG sync_thread_reset_level(&root_block->lock); #endif /* UNIV_SYNC_DEBUG */ } return(height); } /**************************************************************//** Checks a file segment header within a B-tree root page and updates the segment header space id. @return TRUE if valid */ static bool btr_root_fseg_adjust_on_import( /*===========================*/ fseg_header_t* seg_header, /*!< in/out: segment header */ page_zip_des_t* page_zip, /*!< in/out: compressed page, or NULL */ ulint space, /*!< in: tablespace identifier */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint offset = mach_read_from_2(seg_header + FSEG_HDR_OFFSET); if (offset < FIL_PAGE_DATA || offset > UNIV_PAGE_SIZE - FIL_PAGE_DATA_END) { return(FALSE); } else if (page_zip) { mach_write_to_4(seg_header + FSEG_HDR_SPACE, space); page_zip_write_header(page_zip, seg_header + FSEG_HDR_SPACE, 4, mtr); } else { mlog_write_ulint(seg_header + FSEG_HDR_SPACE, space, MLOG_4BYTES, mtr); } return(TRUE); } /**************************************************************//** Checks and adjusts the root node of a tree during IMPORT TABLESPACE. @return error code, or DB_SUCCESS */ UNIV_INTERN dberr_t btr_root_adjust_on_import( /*======================*/ const dict_index_t* index) /*!< in: index tree */ { dberr_t err; mtr_t mtr; page_t* page; buf_block_t* block; page_zip_des_t* page_zip; dict_table_t* table = index->table; ulint space_id = dict_index_get_space(index); ulint zip_size = dict_table_zip_size(table); ulint root_page_no = dict_index_get_page(index); mtr_start(&mtr); mtr_set_log_mode(&mtr, MTR_LOG_NO_REDO); DBUG_EXECUTE_IF("ib_import_trigger_corruption_3", return(DB_CORRUPTION);); block = btr_block_get( space_id, zip_size, root_page_no, RW_X_LATCH, (dict_index_t*)index, &mtr); page = buf_block_get_frame(block); page_zip = buf_block_get_page_zip(block); /* Check that this is a B-tree page and both the PREV and NEXT pointers are FIL_NULL, because the root page does not have any siblings. */ if (fil_page_get_type(page) != FIL_PAGE_INDEX || fil_page_get_prev(page) != FIL_NULL || fil_page_get_next(page) != FIL_NULL) { err = DB_CORRUPTION; } else if (dict_index_is_clust(index)) { bool page_is_compact_format; page_is_compact_format = page_is_comp(page) > 0; /* Check if the page format and table format agree. */ if (page_is_compact_format != dict_table_is_comp(table)) { err = DB_CORRUPTION; } else { /* Check that the table flags and the tablespace flags match. */ ulint flags = fil_space_get_flags(table->space); if (flags && flags != dict_tf_to_fsp_flags(table->flags)) { err = DB_CORRUPTION; } else { err = DB_SUCCESS; } } } else { err = DB_SUCCESS; } /* Check and adjust the file segment headers, if all OK so far. */ if (err == DB_SUCCESS && (!btr_root_fseg_adjust_on_import( FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF + page, page_zip, space_id, &mtr) || !btr_root_fseg_adjust_on_import( FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + page, page_zip, space_id, &mtr))) { err = DB_CORRUPTION; } mtr_commit(&mtr); return(err); } /*************************************************************//** Gets pointer to the previous user record in the tree. It is assumed that the caller has appropriate latches on the page and its neighbor. @return previous user record, NULL if there is none */ UNIV_INTERN rec_t* btr_get_prev_user_rec( /*==================*/ rec_t* rec, /*!< in: record on leaf level */ mtr_t* mtr) /*!< in: mtr holding a latch on the page, and if needed, also to the previous page */ { page_t* page; page_t* prev_page; ulint prev_page_no; if (!page_rec_is_infimum(rec)) { rec_t* prev_rec = page_rec_get_prev(rec); if (!page_rec_is_infimum(prev_rec)) { return(prev_rec); } } page = page_align(rec); prev_page_no = btr_page_get_prev(page, mtr); if (prev_page_no != FIL_NULL) { ulint space; ulint zip_size; buf_block_t* prev_block; space = page_get_space_id(page); zip_size = fil_space_get_zip_size(space); prev_block = buf_page_get_with_no_latch(space, zip_size, prev_page_no, mtr); prev_page = buf_block_get_frame(prev_block); /* The caller must already have a latch to the brother */ ut_ad(mtr_memo_contains(mtr, prev_block, MTR_MEMO_PAGE_S_FIX) || mtr_memo_contains(mtr, prev_block, MTR_MEMO_PAGE_X_FIX)); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(prev_page) == page_is_comp(page)); ut_a(btr_page_get_next(prev_page, mtr) == page_get_page_no(page)); #endif /* UNIV_BTR_DEBUG */ return(page_rec_get_prev(page_get_supremum_rec(prev_page))); } return(NULL); } /*************************************************************//** Gets pointer to the next user record in the tree. It is assumed that the caller has appropriate latches on the page and its neighbor. @return next user record, NULL if there is none */ UNIV_INTERN rec_t* btr_get_next_user_rec( /*==================*/ rec_t* rec, /*!< in: record on leaf level */ mtr_t* mtr) /*!< in: mtr holding a latch on the page, and if needed, also to the next page */ { page_t* page; page_t* next_page; ulint next_page_no; if (!page_rec_is_supremum(rec)) { rec_t* next_rec = page_rec_get_next(rec); if (!page_rec_is_supremum(next_rec)) { return(next_rec); } } page = page_align(rec); next_page_no = btr_page_get_next(page, mtr); if (next_page_no != FIL_NULL) { ulint space; ulint zip_size; buf_block_t* next_block; space = page_get_space_id(page); zip_size = fil_space_get_zip_size(space); next_block = buf_page_get_with_no_latch(space, zip_size, next_page_no, mtr); next_page = buf_block_get_frame(next_block); /* The caller must already have a latch to the brother */ ut_ad(mtr_memo_contains(mtr, next_block, MTR_MEMO_PAGE_S_FIX) || mtr_memo_contains(mtr, next_block, MTR_MEMO_PAGE_X_FIX)); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(next_page) == page_is_comp(page)); ut_a(btr_page_get_prev(next_page, mtr) == page_get_page_no(page)); #endif /* UNIV_BTR_DEBUG */ return(page_rec_get_next(page_get_infimum_rec(next_page))); } return(NULL); } /**************************************************************//** Creates a new index page (not the root, and also not used in page reorganization). @see btr_page_empty(). */ static void btr_page_create( /*============*/ buf_block_t* block, /*!< in/out: page to be created */ page_zip_des_t* page_zip,/*!< in/out: compressed page, or NULL */ dict_index_t* index, /*!< in: index */ ulint level, /*!< in: the B-tree level of the page */ mtr_t* mtr) /*!< in: mtr */ { page_t* page = buf_block_get_frame(block); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); btr_blob_dbg_assert_empty(index, buf_block_get_page_no(block)); if (page_zip) { page_create_zip(block, index, level, 0, mtr); } else { page_create(block, mtr, dict_table_is_comp(index->table)); /* Set the level of the new index page */ btr_page_set_level(page, NULL, level, mtr); } block->check_index_page_at_flush = TRUE; btr_page_set_index_id(page, page_zip, index->id, mtr); } /**************************************************************//** Allocates a new file page to be used in an ibuf tree. Takes the page from the free list of the tree, which must contain pages! @return new allocated block, x-latched */ static buf_block_t* btr_page_alloc_for_ibuf( /*====================*/ dict_index_t* index, /*!< in: index tree */ mtr_t* mtr) /*!< in: mtr */ { fil_addr_t node_addr; page_t* root; page_t* new_page; buf_block_t* new_block; root = btr_root_get(index, mtr); node_addr = flst_get_first(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, mtr); ut_a(node_addr.page != FIL_NULL); new_block = buf_page_get(dict_index_get_space(index), dict_table_zip_size(index->table), node_addr.page, RW_X_LATCH, mtr); new_page = buf_block_get_frame(new_block); buf_block_dbg_add_level(new_block, SYNC_IBUF_TREE_NODE_NEW); flst_remove(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, new_page + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST_NODE, mtr); ut_ad(flst_validate(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, mtr)); return(new_block); } /**************************************************************//** Allocates a new file page to be used in an index tree. NOTE: we assume that the caller has made the reservation for free extents! @retval NULL if no page could be allocated @retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded (init_mtr == mtr, or the page was not previously freed in mtr) @retval block (not allocated or initialized) otherwise */ static MY_ATTRIBUTE((nonnull, warn_unused_result)) buf_block_t* btr_page_alloc_low( /*===============*/ dict_index_t* index, /*!< in: index */ ulint hint_page_no, /*!< in: hint of a good page */ byte file_direction, /*!< in: direction where a possible page split is made */ ulint level, /*!< in: level where the page is placed in the tree */ mtr_t* mtr, /*!< in/out: mini-transaction for the allocation */ mtr_t* init_mtr) /*!< in/out: mtr or another mini-transaction in which the page should be initialized. If init_mtr!=mtr, but the page is already X-latched in mtr, do not initialize the page. */ { fseg_header_t* seg_header; page_t* root; root = btr_root_get(index, mtr); if (level == 0) { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF; } else { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_TOP; } /* Parameter TRUE below states that the caller has made the reservation for free extents, and thus we know that a page can be allocated: */ buf_block_t* block = fseg_alloc_free_page_general( seg_header, hint_page_no, file_direction, TRUE, mtr, init_mtr); #ifdef UNIV_DEBUG_SCRUBBING if (block != NULL) { fprintf(stderr, "alloc %lu:%lu to index: %lu root: %lu\n", buf_block_get_page_no(block), buf_block_get_space(block), index->id, dict_index_get_page(index)); } else { fprintf(stderr, "failed alloc index: %lu root: %lu\n", index->id, dict_index_get_page(index)); } #endif /* UNIV_DEBUG_SCRUBBING */ return block; } /**************************************************************//** Allocates a new file page to be used in an index tree. NOTE: we assume that the caller has made the reservation for free extents! @retval NULL if no page could be allocated @retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded (init_mtr == mtr, or the page was not previously freed in mtr) @retval block (not allocated or initialized) otherwise */ UNIV_INTERN buf_block_t* btr_page_alloc( /*===========*/ dict_index_t* index, /*!< in: index */ ulint hint_page_no, /*!< in: hint of a good page */ byte file_direction, /*!< in: direction where a possible page split is made */ ulint level, /*!< in: level where the page is placed in the tree */ mtr_t* mtr, /*!< in/out: mini-transaction for the allocation */ mtr_t* init_mtr) /*!< in/out: mini-transaction for x-latching and initializing the page */ { buf_block_t* new_block; if (dict_index_is_ibuf(index)) { return(btr_page_alloc_for_ibuf(index, mtr)); } new_block = btr_page_alloc_low( index, hint_page_no, file_direction, level, mtr, init_mtr); if (new_block) { buf_block_dbg_add_level(new_block, SYNC_TREE_NODE_NEW); } return(new_block); } /**************************************************************//** Gets the number of pages in a B-tree. @return number of pages, or ULINT_UNDEFINED if the index is unavailable */ UNIV_INTERN ulint btr_get_size( /*=========*/ dict_index_t* index, /*!< in: index */ ulint flag, /*!< in: BTR_N_LEAF_PAGES or BTR_TOTAL_SIZE */ mtr_t* mtr) /*!< in/out: mini-transaction where index is s-latched */ { ulint used; if (flag == BTR_N_LEAF_PAGES) { btr_get_size_and_reserved(index, flag, &used, mtr); return used; } else if (flag == BTR_TOTAL_SIZE) { return btr_get_size_and_reserved(index, flag, &used, mtr); } else { ut_error; } return (ULINT_UNDEFINED); } /**************************************************************//** Gets the number of reserved and used pages in a B-tree. @return number of pages reserved, or ULINT_UNDEFINED if the index is unavailable */ UNIV_INTERN ulint btr_get_size_and_reserved( /*======================*/ dict_index_t* index, /*!< in: index */ ulint flag, /*!< in: BTR_N_LEAF_PAGES or BTR_TOTAL_SIZE */ ulint* used, /*!< out: number of pages used (<= reserved) */ mtr_t* mtr) /*!< in/out: mini-transaction where index is s-latched */ { fseg_header_t* seg_header; page_t* root; ulint n=ULINT_UNDEFINED; ulint dummy; ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_S_LOCK)); ut_a(flag == BTR_N_LEAF_PAGES || flag == BTR_TOTAL_SIZE); if (index->page == FIL_NULL || dict_index_is_online_ddl(index) || *index->name == TEMP_INDEX_PREFIX) { return(ULINT_UNDEFINED); } root = btr_root_get(index, mtr); *used = 0; if (root) { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF; n = fseg_n_reserved_pages(seg_header, used, mtr); if (flag == BTR_TOTAL_SIZE) { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_TOP; n += fseg_n_reserved_pages(seg_header, &dummy, mtr); *used += dummy; } } return(n); } /**************************************************************//** Frees a page used in an ibuf tree. Puts the page to the free list of the ibuf tree. */ static void btr_page_free_for_ibuf( /*===================*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: block to be freed, x-latched */ mtr_t* mtr) /*!< in: mtr */ { page_t* root; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); root = btr_root_get(index, mtr); flst_add_first(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, buf_block_get_frame(block) + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST_NODE, mtr); ut_ad(flst_validate(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, mtr)); } /**************************************************************//** Frees a file page used in an index tree. Can be used also to (BLOB) external storage pages, because the page level 0 can be given as an argument. */ UNIV_INTERN void btr_page_free_low( /*==============*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: block to be freed, x-latched */ ulint level, /*!< in: page level */ bool blob, /*!< in: blob page */ mtr_t* mtr) /*!< in: mtr */ { fseg_header_t* seg_header; page_t* root; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); /* The page gets invalid for optimistic searches: increment the frame modify clock */ buf_block_modify_clock_inc(block); btr_blob_dbg_assert_empty(index, buf_block_get_page_no(block)); if (blob) { ut_a(level == 0); } bool scrub = srv_immediate_scrub_data_uncompressed; /* scrub page */ if (scrub && blob) { /* blob page: scrub entire page */ // TODO(jonaso): scrub only what is actually needed page_t* page = buf_block_get_frame(block); memset(page + PAGE_HEADER, 0, UNIV_PAGE_SIZE - PAGE_HEADER); #ifdef UNIV_DEBUG_SCRUBBING fprintf(stderr, "btr_page_free_low: scrub blob page %lu/%lu\n", buf_block_get_space(block), buf_block_get_page_no(block)); #endif /* UNIV_DEBUG_SCRUBBING */ } else if (scrub) { /* scrub records on page */ /* TODO(jonaso): in theory we could clear full page * but, since page still remains in buffer pool, and * gets flushed etc. Lots of routines validates consistency * of it. And in order to remain structurally consistent * we clear each record by it own * * NOTE: The TODO below mentions removing page from buffer pool * and removing redo entries, once that is done, clearing full * pages should be possible */ uint cnt = 0; uint bytes = 0; page_t* page = buf_block_get_frame(block); mem_heap_t* heap = NULL; ulint* offsets = NULL; rec_t* rec = page_rec_get_next(page_get_infimum_rec(page)); while (!page_rec_is_supremum(rec)) { offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); uint size = rec_offs_data_size(offsets); memset(rec, 0, size); rec = page_rec_get_next(rec); cnt++; bytes += size; } #ifdef UNIV_DEBUG_SCRUBBING fprintf(stderr, "btr_page_free_low: scrub %lu/%lu - " "%u records %u bytes\n", buf_block_get_space(block), buf_block_get_page_no(block), cnt, bytes); #endif /* UNIV_DEBUG_SCRUBBING */ if (heap) { mem_heap_free(heap); } } #ifdef UNIV_DEBUG_SCRUBBING if (scrub == false) { fprintf(stderr, "btr_page_free_low %lu/%lu blob: %u\n", buf_block_get_space(block), buf_block_get_page_no(block), blob); } #endif /* UNIV_DEBUG_SCRUBBING */ if (dict_index_is_ibuf(index)) { btr_page_free_for_ibuf(index, block, mtr); return; } root = btr_root_get(index, mtr); if (level == 0) { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF; } else { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_TOP; } if (scrub) { /** * Reset page type so that scrub thread won't try to scrub it */ mlog_write_ulint(buf_block_get_frame(block) + FIL_PAGE_TYPE, FIL_PAGE_TYPE_ALLOCATED, MLOG_2BYTES, mtr); } fseg_free_page(seg_header, buf_block_get_space(block), buf_block_get_page_no(block), mtr); /* The page was marked free in the allocation bitmap, but it should remain buffer-fixed until mtr_commit(mtr) or until it is explicitly freed from the mini-transaction. */ ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); /* TODO: Discard any operations on the page from the redo log and remove the block from the flush list and the buffer pool. This would free up buffer pool earlier and reduce writes to both the tablespace and the redo log. */ } /**************************************************************//** Frees a file page used in an index tree. NOTE: cannot free field external storage pages because the page must contain info on its level. */ UNIV_INTERN void btr_page_free( /*==========*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: block to be freed, x-latched */ mtr_t* mtr) /*!< in: mtr */ { const page_t* page = buf_block_get_frame(block); ulint level = btr_page_get_level(page, mtr); ut_ad(fil_page_get_type(block->frame) == FIL_PAGE_INDEX); btr_page_free_low(index, block, level, false, mtr); } /**************************************************************//** Sets the child node file address in a node pointer. */ UNIV_INLINE void btr_node_ptr_set_child_page_no( /*===========================*/ rec_t* rec, /*!< in: node pointer record */ page_zip_des_t* page_zip,/*!< in/out: compressed page whose uncompressed part will be updated, or NULL */ const ulint* offsets,/*!< in: array returned by rec_get_offsets() */ ulint page_no,/*!< in: child node address */ mtr_t* mtr) /*!< in: mtr */ { byte* field; ulint len; ut_ad(rec_offs_validate(rec, NULL, offsets)); ut_ad(!page_is_leaf(page_align(rec))); ut_ad(!rec_offs_comp(offsets) || rec_get_node_ptr_flag(rec)); /* The child address is in the last field */ field = rec_get_nth_field(rec, offsets, rec_offs_n_fields(offsets) - 1, &len); ut_ad(len == REC_NODE_PTR_SIZE); if (page_zip) { page_zip_write_node_ptr(page_zip, rec, rec_offs_data_size(offsets), page_no, mtr); } else { mlog_write_ulint(field, page_no, MLOG_4BYTES, mtr); } } /************************************************************//** Returns the child page of a node pointer and x-latches it. @return child page, x-latched */ static buf_block_t* btr_node_ptr_get_child( /*===================*/ const rec_t* node_ptr,/*!< in: node pointer */ dict_index_t* index, /*!< in: index */ const ulint* offsets,/*!< in: array returned by rec_get_offsets() */ mtr_t* mtr) /*!< in: mtr */ { ulint page_no; ulint space; ut_ad(rec_offs_validate(node_ptr, index, offsets)); space = page_get_space_id(page_align(node_ptr)); page_no = btr_node_ptr_get_child_page_no(node_ptr, offsets); return(btr_block_get(space, dict_table_zip_size(index->table), page_no, RW_X_LATCH, index, mtr)); } /************************************************************//** Returns the upper level node pointer to a page. It is assumed that mtr holds an x-latch on the tree. @return rec_get_offsets() of the node pointer record */ static ulint* btr_page_get_father_node_ptr_func( /*==============================*/ ulint* offsets,/*!< in: work area for the return value */ mem_heap_t* heap, /*!< in: memory heap to use */ btr_cur_t* cursor, /*!< in: cursor pointing to user record, out: cursor on node pointer record, its page x-latched */ const char* file, /*!< in: file name */ ulint line, /*!< in: line where called */ mtr_t* mtr) /*!< in: mtr */ { dtuple_t* tuple; rec_t* user_rec; rec_t* node_ptr; ulint level; ulint page_no; dict_index_t* index; page_no = buf_block_get_page_no(btr_cur_get_block(cursor)); index = btr_cur_get_index(cursor); ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_X_LOCK)); ut_ad(dict_index_get_page(index) != page_no); level = btr_page_get_level(btr_cur_get_page(cursor), mtr); user_rec = btr_cur_get_rec(cursor); ut_a(page_rec_is_user_rec(user_rec)); tuple = dict_index_build_node_ptr(index, user_rec, 0, heap, level); btr_cur_search_to_nth_level(index, level + 1, tuple, PAGE_CUR_LE, BTR_CONT_MODIFY_TREE, cursor, 0, file, line, mtr); node_ptr = btr_cur_get_rec(cursor); ut_ad(!page_rec_is_comp(node_ptr) || rec_get_status(node_ptr) == REC_STATUS_NODE_PTR); offsets = rec_get_offsets(node_ptr, index, offsets, ULINT_UNDEFINED, &heap); if (btr_node_ptr_get_child_page_no(node_ptr, offsets) != page_no) { rec_t* print_rec; fputs("InnoDB: Dump of the child page:\n", stderr); buf_page_print(page_align(user_rec), 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: Dump of the parent page:\n", stderr); buf_page_print(page_align(node_ptr), 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: Corruption of an index tree: table ", stderr); ut_print_name(stderr, NULL, TRUE, index->table_name); fputs(", index ", stderr); ut_print_name(stderr, NULL, FALSE, index->name); fprintf(stderr, ",\n" "InnoDB: father ptr page no %lu, child page no %lu\n", (ulong) btr_node_ptr_get_child_page_no(node_ptr, offsets), (ulong) page_no); print_rec = page_rec_get_next( page_get_infimum_rec(page_align(user_rec))); offsets = rec_get_offsets(print_rec, index, offsets, ULINT_UNDEFINED, &heap); page_rec_print(print_rec, offsets); offsets = rec_get_offsets(node_ptr, index, offsets, ULINT_UNDEFINED, &heap); page_rec_print(node_ptr, offsets); fputs("InnoDB: You should dump + drop + reimport the table" " to fix the\n" "InnoDB: corruption. If the crash happens at " "the database startup, see\n" "InnoDB: " REFMAN "forcing-innodb-recovery.html about\n" "InnoDB: forcing recovery. " "Then dump + drop + reimport.\n", stderr); ut_error; } return(offsets); } #define btr_page_get_father_node_ptr(of,heap,cur,mtr) \ btr_page_get_father_node_ptr_func(of,heap,cur,__FILE__,__LINE__,mtr) /************************************************************//** Returns the upper level node pointer to a page. It is assumed that mtr holds an x-latch on the tree. @return rec_get_offsets() of the node pointer record */ static ulint* btr_page_get_father_block( /*======================*/ ulint* offsets,/*!< in: work area for the return value */ mem_heap_t* heap, /*!< in: memory heap to use */ dict_index_t* index, /*!< in: b-tree index */ buf_block_t* block, /*!< in: child page in the index */ mtr_t* mtr, /*!< in: mtr */ btr_cur_t* cursor) /*!< out: cursor on node pointer record, its page x-latched */ { rec_t* rec = page_rec_get_next(page_get_infimum_rec(buf_block_get_frame( block))); btr_cur_position(index, rec, block, cursor); return(btr_page_get_father_node_ptr(offsets, heap, cursor, mtr)); } /************************************************************//** Seeks to the upper level node pointer to a page. It is assumed that mtr holds an x-latch on the tree. */ static void btr_page_get_father( /*================*/ dict_index_t* index, /*!< in: b-tree index */ buf_block_t* block, /*!< in: child page in the index */ mtr_t* mtr, /*!< in: mtr */ btr_cur_t* cursor) /*!< out: cursor on node pointer record, its page x-latched */ { mem_heap_t* heap; rec_t* rec = page_rec_get_next(page_get_infimum_rec(buf_block_get_frame( block))); btr_cur_position(index, rec, block, cursor); heap = mem_heap_create(100); btr_page_get_father_node_ptr(NULL, heap, cursor, mtr); mem_heap_free(heap); } /************************************************************//** Creates the root node for a new index tree. @return page number of the created root, FIL_NULL if did not succeed */ UNIV_INTERN ulint btr_create( /*=======*/ ulint type, /*!< in: type of the index */ ulint space, /*!< in: space where created */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ index_id_t index_id,/*!< in: index id */ dict_index_t* index, /*!< in: index */ mtr_t* mtr) /*!< in: mini-transaction handle */ { ulint page_no; buf_block_t* block; buf_frame_t* frame; page_t* page; page_zip_des_t* page_zip; /* Create the two new segments (one, in the case of an ibuf tree) for the index tree; the segment headers are put on the allocated root page (for an ibuf tree, not in the root, but on a separate ibuf header page) */ if (type & DICT_IBUF) { /* Allocate first the ibuf header page */ buf_block_t* ibuf_hdr_block = fseg_create( space, 0, IBUF_HEADER + IBUF_TREE_SEG_HEADER, mtr); buf_block_dbg_add_level( ibuf_hdr_block, SYNC_IBUF_TREE_NODE_NEW); ut_ad(buf_block_get_page_no(ibuf_hdr_block) == IBUF_HEADER_PAGE_NO); /* Allocate then the next page to the segment: it will be the tree root page */ block = fseg_alloc_free_page( buf_block_get_frame(ibuf_hdr_block) + IBUF_HEADER + IBUF_TREE_SEG_HEADER, IBUF_TREE_ROOT_PAGE_NO, FSP_UP, mtr); ut_ad(buf_block_get_page_no(block) == IBUF_TREE_ROOT_PAGE_NO); } else { #ifdef UNIV_BLOB_DEBUG if ((type & DICT_CLUSTERED) && !index->blobs) { mutex_create(PFS_NOT_INSTRUMENTED, &index->blobs_mutex, SYNC_ANY_LATCH); index->blobs = rbt_create(sizeof(btr_blob_dbg_t), btr_blob_dbg_cmp); } #endif /* UNIV_BLOB_DEBUG */ block = fseg_create(space, 0, PAGE_HEADER + PAGE_BTR_SEG_TOP, mtr); } if (block == NULL) { return(FIL_NULL); } page_no = buf_block_get_page_no(block); frame = buf_block_get_frame(block); if (type & DICT_IBUF) { /* It is an insert buffer tree: initialize the free list */ buf_block_dbg_add_level(block, SYNC_IBUF_TREE_NODE_NEW); ut_ad(page_no == IBUF_TREE_ROOT_PAGE_NO); flst_init(frame + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, mtr); } else { /* It is a non-ibuf tree: create a file segment for leaf pages */ buf_block_dbg_add_level(block, SYNC_TREE_NODE_NEW); if (!fseg_create(space, page_no, PAGE_HEADER + PAGE_BTR_SEG_LEAF, mtr)) { /* Not enough space for new segment, free root segment before return. */ btr_free_root(space, zip_size, page_no, mtr); return(FIL_NULL); } /* The fseg create acquires a second latch on the page, therefore we must declare it: */ buf_block_dbg_add_level(block, SYNC_TREE_NODE_NEW); } /* Create a new index page on the allocated segment page */ page_zip = buf_block_get_page_zip(block); if (page_zip) { page = page_create_zip(block, index, 0, 0, mtr); } else { page = page_create(block, mtr, dict_table_is_comp(index->table)); /* Set the level of the new index page */ btr_page_set_level(page, NULL, 0, mtr); } block->check_index_page_at_flush = TRUE; /* Set the index id of the page */ btr_page_set_index_id(page, page_zip, index_id, mtr); /* Set the next node and previous node fields */ btr_page_set_next(page, page_zip, FIL_NULL, mtr); btr_page_set_prev(page, page_zip, FIL_NULL, mtr); /* We reset the free bits for the page to allow creation of several trees in the same mtr, otherwise the latch on a bitmap page would prevent it because of the latching order */ if (!(type & DICT_CLUSTERED)) { ibuf_reset_free_bits(block); } /* In the following assertion we test that two records of maximum allowed size fit on the root page: this fact is needed to ensure correctness of split algorithms */ ut_ad(page_get_max_insert_size(page, 2) > 2 * BTR_PAGE_MAX_REC_SIZE); return(page_no); } /************************************************************//** Frees a B-tree except the root page, which MUST be freed after this by calling btr_free_root. */ UNIV_INTERN void btr_free_but_not_root( /*==================*/ ulint space, /*!< in: space where created */ ulint zip_size, /*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint root_page_no) /*!< in: root page number */ { ibool finished; page_t* root; mtr_t mtr; leaf_loop: mtr_start(&mtr); root = btr_page_get(space, zip_size, root_page_no, RW_X_LATCH, NULL, &mtr); if (!root) { mtr_commit(&mtr); return; } #ifdef UNIV_BTR_DEBUG ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF + root, space)); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + root, space)); #endif /* UNIV_BTR_DEBUG */ /* NOTE: page hash indexes are dropped when a page is freed inside fsp0fsp. */ finished = fseg_free_step(root + PAGE_HEADER + PAGE_BTR_SEG_LEAF, &mtr); mtr_commit(&mtr); if (!finished) { goto leaf_loop; } top_loop: mtr_start(&mtr); root = btr_page_get(space, zip_size, root_page_no, RW_X_LATCH, NULL, &mtr); #ifdef UNIV_BTR_DEBUG ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + root, space)); #endif /* UNIV_BTR_DEBUG */ finished = fseg_free_step_not_header( root + PAGE_HEADER + PAGE_BTR_SEG_TOP, &mtr); mtr_commit(&mtr); if (!finished) { goto top_loop; } } /************************************************************//** Frees the B-tree root page. Other tree MUST already have been freed. */ UNIV_INTERN void btr_free_root( /*==========*/ ulint space, /*!< in: space where created */ ulint zip_size, /*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint root_page_no, /*!< in: root page number */ mtr_t* mtr) /*!< in/out: mini-transaction */ { buf_block_t* block; fseg_header_t* header; block = btr_block_get(space, zip_size, root_page_no, RW_X_LATCH, NULL, mtr); if (block) { btr_search_drop_page_hash_index(block); header = buf_block_get_frame(block) + PAGE_HEADER + PAGE_BTR_SEG_TOP; #ifdef UNIV_BTR_DEBUG ut_a(btr_root_fseg_validate(header, space)); #endif /* UNIV_BTR_DEBUG */ while (!fseg_free_step(header, mtr)) { /* Free the entire segment in small steps. */ } } } #endif /* !UNIV_HOTBACKUP */ /*************************************************************//** Reorganizes an index page. IMPORTANT: On success, the caller will have to update IBUF_BITMAP_FREE if this is a compressed leaf page in a secondary index. This has to be done either within the same mini-transaction, or by invoking ibuf_reset_free_bits() before mtr_commit(). On uncompressed pages, IBUF_BITMAP_FREE is unaffected by reorganization. @retval true if the operation was successful @retval false if it is a compressed page, and recompression failed */ UNIV_INTERN bool btr_page_reorganize_low( /*====================*/ bool recovery,/*!< in: true if called in recovery: locks should not be updated, i.e., there cannot exist locks on the page, and a hash index should not be dropped: it cannot exist */ ulint z_level,/*!< in: compression level to be used if dealing with compressed page */ page_cur_t* cursor, /*!< in/out: page cursor */ dict_index_t* index, /*!< in: the index tree of the page */ mtr_t* mtr) /*!< in/out: mini-transaction */ { buf_block_t* block = page_cur_get_block(cursor); #ifndef UNIV_HOTBACKUP buf_pool_t* buf_pool = buf_pool_from_bpage(&block->page); #endif /* !UNIV_HOTBACKUP */ page_t* page = buf_block_get_frame(block); page_zip_des_t* page_zip = buf_block_get_page_zip(block); buf_block_t* temp_block; page_t* temp_page; ulint log_mode; ulint data_size1; ulint data_size2; ulint max_ins_size1; ulint max_ins_size2; bool success = false; ulint pos; bool log_compressed; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); btr_assert_not_corrupted(block, index); #ifdef UNIV_ZIP_DEBUG ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ data_size1 = page_get_data_size(page); max_ins_size1 = page_get_max_insert_size_after_reorganize(page, 1); /* Turn logging off */ log_mode = mtr_set_log_mode(mtr, MTR_LOG_NONE); #ifndef UNIV_HOTBACKUP temp_block = buf_block_alloc(buf_pool); #else /* !UNIV_HOTBACKUP */ ut_ad(block == back_block1); temp_block = back_block2; #endif /* !UNIV_HOTBACKUP */ temp_page = temp_block->frame; MONITOR_INC(MONITOR_INDEX_REORG_ATTEMPTS); /* Copy the old page to temporary space */ buf_frame_copy(temp_page, page); #ifndef UNIV_HOTBACKUP if (!recovery) { btr_search_drop_page_hash_index(block); } block->check_index_page_at_flush = TRUE; #endif /* !UNIV_HOTBACKUP */ btr_blob_dbg_remove(page, index, "btr_page_reorganize"); /* Save the cursor position. */ pos = page_rec_get_n_recs_before(page_cur_get_rec(cursor)); /* Recreate the page: note that global data on page (possible segment headers, next page-field, etc.) is preserved intact */ page_create(block, mtr, dict_table_is_comp(index->table)); /* Copy the records from the temporary space to the recreated page; do not copy the lock bits yet */ page_copy_rec_list_end_no_locks(block, temp_block, page_get_infimum_rec(temp_page), index, mtr); if (dict_index_is_sec_or_ibuf(index) && page_is_leaf(page)) { /* Copy max trx id to recreated page */ trx_id_t max_trx_id = page_get_max_trx_id(temp_page); page_set_max_trx_id(block, NULL, max_trx_id, mtr); /* In crash recovery, dict_index_is_sec_or_ibuf() always holds, even for clustered indexes. max_trx_id is unused in clustered index pages. */ ut_ad(max_trx_id != 0 || recovery); } /* If innodb_log_compressed_pages is ON, page reorganize should log the compressed page image.*/ log_compressed = page_zip && page_zip_log_pages; if (log_compressed) { mtr_set_log_mode(mtr, log_mode); } if (page_zip && !page_zip_compress(page_zip, page, index, z_level, mtr)) { /* Restore the old page and exit. */ btr_blob_dbg_restore(page, temp_page, index, "btr_page_reorganize_compress_fail"); #if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG /* Check that the bytes that we skip are identical. */ ut_a(!memcmp(page, temp_page, PAGE_HEADER)); ut_a(!memcmp(PAGE_HEADER + PAGE_N_RECS + page, PAGE_HEADER + PAGE_N_RECS + temp_page, PAGE_DATA - (PAGE_HEADER + PAGE_N_RECS))); ut_a(!memcmp(UNIV_PAGE_SIZE - FIL_PAGE_DATA_END + page, UNIV_PAGE_SIZE - FIL_PAGE_DATA_END + temp_page, FIL_PAGE_DATA_END)); #endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */ memcpy(PAGE_HEADER + page, PAGE_HEADER + temp_page, PAGE_N_RECS - PAGE_N_DIR_SLOTS); memcpy(PAGE_DATA + page, PAGE_DATA + temp_page, UNIV_PAGE_SIZE - PAGE_DATA - FIL_PAGE_DATA_END); #if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG ut_a(!memcmp(page, temp_page, UNIV_PAGE_SIZE)); #endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */ goto func_exit; } #ifndef UNIV_HOTBACKUP if (!recovery) { /* Update the record lock bitmaps */ lock_move_reorganize_page(block, temp_block); } #endif /* !UNIV_HOTBACKUP */ data_size2 = page_get_data_size(page); max_ins_size2 = page_get_max_insert_size_after_reorganize(page, 1); if (data_size1 != data_size2 || max_ins_size1 != max_ins_size2) { buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(temp_page, 0, BUF_PAGE_PRINT_NO_CRASH); fprintf(stderr, "InnoDB: Error: page old data size %lu" " new data size %lu\n" "InnoDB: Error: page old max ins size %lu" " new max ins size %lu\n" "InnoDB: Submit a detailed bug report" " to http://bugs.mysql.com\n", (unsigned long) data_size1, (unsigned long) data_size2, (unsigned long) max_ins_size1, (unsigned long) max_ins_size2); ut_ad(0); } else { success = true; } /* Restore the cursor position. */ if (pos > 0) { cursor->rec = page_rec_get_nth(page, pos); } else { ut_ad(cursor->rec == page_get_infimum_rec(page)); } func_exit: #ifdef UNIV_ZIP_DEBUG ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ #ifndef UNIV_HOTBACKUP buf_block_free(temp_block); #endif /* !UNIV_HOTBACKUP */ /* Restore logging mode */ mtr_set_log_mode(mtr, log_mode); #ifndef UNIV_HOTBACKUP if (success) { byte type; byte* log_ptr; /* Write the log record */ if (page_zip) { ut_ad(page_is_comp(page)); type = MLOG_ZIP_PAGE_REORGANIZE; } else if (page_is_comp(page)) { type = MLOG_COMP_PAGE_REORGANIZE; } else { type = MLOG_PAGE_REORGANIZE; } log_ptr = log_compressed ? NULL : mlog_open_and_write_index( mtr, page, index, type, page_zip ? 1 : 0); /* For compressed pages write the compression level. */ if (log_ptr && page_zip) { mach_write_to_1(log_ptr, z_level); mlog_close(mtr, log_ptr + 1); } MONITOR_INC(MONITOR_INDEX_REORG_SUCCESSFUL); } #endif /* !UNIV_HOTBACKUP */ return(success); } /*************************************************************//** Reorganizes an index page. IMPORTANT: On success, the caller will have to update IBUF_BITMAP_FREE if this is a compressed leaf page in a secondary index. This has to be done either within the same mini-transaction, or by invoking ibuf_reset_free_bits() before mtr_commit(). On uncompressed pages, IBUF_BITMAP_FREE is unaffected by reorganization. @retval true if the operation was successful @retval false if it is a compressed page, and recompression failed */ UNIV_INTERN bool btr_page_reorganize_block( /*======================*/ bool recovery,/*!< in: true if called in recovery: locks should not be updated, i.e., there cannot exist locks on the page, and a hash index should not be dropped: it cannot exist */ ulint z_level,/*!< in: compression level to be used if dealing with compressed page */ buf_block_t* block, /*!< in/out: B-tree page */ dict_index_t* index, /*!< in: the index tree of the page */ mtr_t* mtr) /*!< in/out: mini-transaction */ { page_cur_t cur; page_cur_set_before_first(block, &cur); return(btr_page_reorganize_low(recovery, z_level, &cur, index, mtr)); } #ifndef UNIV_HOTBACKUP /*************************************************************//** Reorganizes an index page. IMPORTANT: On success, the caller will have to update IBUF_BITMAP_FREE if this is a compressed leaf page in a secondary index. This has to be done either within the same mini-transaction, or by invoking ibuf_reset_free_bits() before mtr_commit(). On uncompressed pages, IBUF_BITMAP_FREE is unaffected by reorganization. @retval true if the operation was successful @retval false if it is a compressed page, and recompression failed */ UNIV_INTERN bool btr_page_reorganize( /*================*/ page_cur_t* cursor, /*!< in/out: page cursor */ dict_index_t* index, /*!< in: the index tree of the page */ mtr_t* mtr) /*!< in/out: mini-transaction */ { return(btr_page_reorganize_low(false, page_zip_level, cursor, index, mtr)); } #endif /* !UNIV_HOTBACKUP */ /***********************************************************//** Parses a redo log record of reorganizing a page. @return end of log record or NULL */ UNIV_INTERN byte* btr_parse_page_reorganize( /*======================*/ byte* ptr, /*!< in: buffer */ byte* end_ptr,/*!< in: buffer end */ dict_index_t* index, /*!< in: record descriptor */ bool compressed,/*!< in: true if compressed page */ buf_block_t* block, /*!< in: page to be reorganized, or NULL */ mtr_t* mtr) /*!< in: mtr or NULL */ { ulint level = page_zip_level; ut_ad(ptr != NULL); ut_ad(end_ptr != NULL); /* If dealing with a compressed page the record has the compression level used during original compression written in one byte. Otherwise record is empty. */ if (compressed) { if (ptr == end_ptr) { return(NULL); } level = mach_read_from_1(ptr); ut_a(level <= 9); ++ptr; } else { level = page_zip_level; } if (block != NULL) { btr_page_reorganize_block(true, level, block, index, mtr); } return(ptr); } #ifndef UNIV_HOTBACKUP /*************************************************************//** Empties an index page. @see btr_page_create(). */ static void btr_page_empty( /*===========*/ buf_block_t* block, /*!< in: page to be emptied */ page_zip_des_t* page_zip,/*!< out: compressed page, or NULL */ dict_index_t* index, /*!< in: index of the page */ ulint level, /*!< in: the B-tree level of the page */ mtr_t* mtr) /*!< in: mtr */ { page_t* page = buf_block_get_frame(block); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); ut_ad(page_zip == buf_block_get_page_zip(block)); #ifdef UNIV_ZIP_DEBUG ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ btr_search_drop_page_hash_index(block); btr_blob_dbg_remove(page, index, "btr_page_empty"); /* Recreate the page: note that global data on page (possible segment headers, next page-field, etc.) is preserved intact */ if (page_zip) { page_create_zip(block, index, level, 0, mtr); } else { page_create(block, mtr, dict_table_is_comp(index->table)); btr_page_set_level(page, NULL, level, mtr); } block->check_index_page_at_flush = TRUE; } /*************************************************************//** Makes tree one level higher by splitting the root, and inserts the tuple. It is assumed that mtr contains an x-latch on the tree. NOTE that the operation of this function must always succeed, we cannot reverse it: therefore enough free disk space must be guaranteed to be available before this function is called. @return inserted record or NULL if run out of space */ UNIV_INTERN rec_t* btr_root_raise_and_insert( /*======================*/ ulint flags, /*!< in: undo logging and locking flags */ btr_cur_t* cursor, /*!< in: cursor at which to insert: must be on the root page; when the function returns, the cursor is positioned on the predecessor of the inserted record */ ulint** offsets,/*!< out: offsets on inserted record */ mem_heap_t** heap, /*!< in/out: pointer to memory heap, or NULL */ const dtuple_t* tuple, /*!< in: tuple to insert */ ulint n_ext, /*!< in: number of externally stored columns */ mtr_t* mtr) /*!< in: mtr */ { dict_index_t* index; page_t* root; page_t* new_page; ulint new_page_no; rec_t* rec; dtuple_t* node_ptr; ulint level; rec_t* node_ptr_rec; page_cur_t* page_cursor; page_zip_des_t* root_page_zip; page_zip_des_t* new_page_zip; buf_block_t* root_block; buf_block_t* new_block; root = btr_cur_get_page(cursor); root_block = btr_cur_get_block(cursor); root_page_zip = buf_block_get_page_zip(root_block); ut_ad(!page_is_empty(root)); index = btr_cur_get_index(cursor); #ifdef UNIV_ZIP_DEBUG ut_a(!root_page_zip || page_zip_validate(root_page_zip, root, index)); #endif /* UNIV_ZIP_DEBUG */ #ifdef UNIV_BTR_DEBUG if (!dict_index_is_ibuf(index)) { ulint space = dict_index_get_space(index); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF + root, space)); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + root, space)); } ut_a(dict_index_get_page(index) == page_get_page_no(root)); #endif /* UNIV_BTR_DEBUG */ ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_X_LOCK)); ut_ad(mtr_memo_contains(mtr, root_block, MTR_MEMO_PAGE_X_FIX)); /* Allocate a new page to the tree. Root splitting is done by first moving the root records to the new page, emptying the root, putting a node pointer to the new page, and then splitting the new page. */ level = btr_page_get_level(root, mtr); new_block = btr_page_alloc(index, 0, FSP_NO_DIR, level, mtr, mtr); if (new_block == NULL && os_has_said_disk_full) { return(NULL); } new_page = buf_block_get_frame(new_block); new_page_zip = buf_block_get_page_zip(new_block); ut_a(!new_page_zip == !root_page_zip); ut_a(!new_page_zip || page_zip_get_size(new_page_zip) == page_zip_get_size(root_page_zip)); btr_page_create(new_block, new_page_zip, index, level, mtr); /* Set the next node and previous node fields of new page */ btr_page_set_next(new_page, new_page_zip, FIL_NULL, mtr); btr_page_set_prev(new_page, new_page_zip, FIL_NULL, mtr); /* Copy the records from root to the new page one by one. */ if (0 #ifdef UNIV_ZIP_COPY || new_page_zip #endif /* UNIV_ZIP_COPY */ || !page_copy_rec_list_end(new_block, root_block, page_get_infimum_rec(root), index, mtr)) { ut_a(new_page_zip); /* Copy the page byte for byte. */ page_zip_copy_recs(new_page_zip, new_page, root_page_zip, root, index, mtr); /* Update the lock table and possible hash index. */ lock_move_rec_list_end(new_block, root_block, page_get_infimum_rec(root)); btr_search_move_or_delete_hash_entries(new_block, root_block, index); } /* If this is a pessimistic insert which is actually done to perform a pessimistic update then we have stored the lock information of the record to be inserted on the infimum of the root page: we cannot discard the lock structs on the root page */ lock_update_root_raise(new_block, root_block); /* Create a memory heap where the node pointer is stored */ if (!*heap) { *heap = mem_heap_create(1000); } rec = page_rec_get_next(page_get_infimum_rec(new_page)); new_page_no = buf_block_get_page_no(new_block); /* Build the node pointer (= node key and page address) for the child */ node_ptr = dict_index_build_node_ptr( index, rec, new_page_no, *heap, level); /* The node pointer must be marked as the predefined minimum record, as there is no lower alphabetical limit to records in the leftmost node of a level: */ dtuple_set_info_bits(node_ptr, dtuple_get_info_bits(node_ptr) | REC_INFO_MIN_REC_FLAG); /* Rebuild the root page to get free space */ btr_page_empty(root_block, root_page_zip, index, level + 1, mtr); /* Set the next node and previous node fields, although they should already have been set. The previous node field must be FIL_NULL if root_page_zip != NULL, because the REC_INFO_MIN_REC_FLAG (of the first user record) will be set if and only if btr_page_get_prev() == FIL_NULL. */ btr_page_set_next(root, root_page_zip, FIL_NULL, mtr); btr_page_set_prev(root, root_page_zip, FIL_NULL, mtr); page_cursor = btr_cur_get_page_cur(cursor); /* Insert node pointer to the root */ page_cur_set_before_first(root_block, page_cursor); node_ptr_rec = page_cur_tuple_insert(page_cursor, node_ptr, index, offsets, heap, 0, mtr); /* The root page should only contain the node pointer to new_page at this point. Thus, the data should fit. */ ut_a(node_ptr_rec); /* We play safe and reset the free bits for the new page */ #if 0 fprintf(stderr, "Root raise new page no %lu\n", new_page_no); #endif if (!dict_index_is_clust(index)) { ibuf_reset_free_bits(new_block); } if (tuple != NULL) { /* Reposition the cursor to the child node */ page_cur_search(new_block, index, tuple, PAGE_CUR_LE, page_cursor); } else { /* Set cursor to first record on child node */ page_cur_set_before_first(new_block, page_cursor); } /* Split the child and insert tuple */ return(btr_page_split_and_insert(flags, cursor, offsets, heap, tuple, n_ext, mtr)); } /*************************************************************//** Decides if the page should be split at the convergence point of inserts converging to the left. @return TRUE if split recommended */ UNIV_INTERN ibool btr_page_get_split_rec_to_left( /*===========================*/ btr_cur_t* cursor, /*!< in: cursor at which to insert */ rec_t** split_rec) /*!< out: if split recommended, the first record on upper half page, or NULL if tuple to be inserted should be first */ { page_t* page; rec_t* insert_point; rec_t* infimum; page = btr_cur_get_page(cursor); insert_point = btr_cur_get_rec(cursor); if (page_header_get_ptr(page, PAGE_LAST_INSERT) == page_rec_get_next(insert_point)) { infimum = page_get_infimum_rec(page); /* If the convergence is in the middle of a page, include also the record immediately before the new insert to the upper page. Otherwise, we could repeatedly move from page to page lots of records smaller than the convergence point. */ if (infimum != insert_point && page_rec_get_next(infimum) != insert_point) { *split_rec = insert_point; } else { *split_rec = page_rec_get_next(insert_point); } return(TRUE); } return(FALSE); } /*************************************************************//** Decides if the page should be split at the convergence point of inserts converging to the right. @return TRUE if split recommended */ UNIV_INTERN ibool btr_page_get_split_rec_to_right( /*============================*/ btr_cur_t* cursor, /*!< in: cursor at which to insert */ rec_t** split_rec) /*!< out: if split recommended, the first record on upper half page, or NULL if tuple to be inserted should be first */ { page_t* page; rec_t* insert_point; page = btr_cur_get_page(cursor); insert_point = btr_cur_get_rec(cursor); /* We use eager heuristics: if the new insert would be right after the previous insert on the same page, we assume that there is a pattern of sequential inserts here. */ if (page_header_get_ptr(page, PAGE_LAST_INSERT) == insert_point) { rec_t* next_rec; next_rec = page_rec_get_next(insert_point); if (page_rec_is_supremum(next_rec)) { split_at_new: /* Split at the new record to insert */ *split_rec = NULL; } else { rec_t* next_next_rec = page_rec_get_next(next_rec); if (page_rec_is_supremum(next_next_rec)) { goto split_at_new; } /* If there are >= 2 user records up from the insert point, split all but 1 off. We want to keep one because then sequential inserts can use the adaptive hash index, as they can do the necessary checks of the right search position just by looking at the records on this page. */ *split_rec = next_next_rec; } return(TRUE); } return(FALSE); } /*************************************************************//** Calculates a split record such that the tuple will certainly fit on its half-page when the split is performed. We assume in this function only that the cursor page has at least one user record. @return split record, or NULL if tuple will be the first record on the lower or upper half-page (determined by btr_page_tuple_smaller()) */ static rec_t* btr_page_get_split_rec( /*===================*/ btr_cur_t* cursor, /*!< in: cursor at which insert should be made */ const dtuple_t* tuple, /*!< in: tuple to insert */ ulint n_ext) /*!< in: number of externally stored columns */ { page_t* page; page_zip_des_t* page_zip; ulint insert_size; ulint free_space; ulint total_data; ulint total_n_recs; ulint total_space; ulint incl_data; rec_t* ins_rec; rec_t* rec; rec_t* next_rec; ulint n; mem_heap_t* heap; ulint* offsets; page = btr_cur_get_page(cursor); insert_size = rec_get_converted_size(cursor->index, tuple, n_ext); free_space = page_get_free_space_of_empty(page_is_comp(page)); page_zip = btr_cur_get_page_zip(cursor); if (page_zip) { /* Estimate the free space of an empty compressed page. */ ulint free_space_zip = page_zip_empty_size( cursor->index->n_fields, page_zip_get_size(page_zip)); if (free_space > (ulint) free_space_zip) { free_space = (ulint) free_space_zip; } } /* free_space is now the free space of a created new page */ total_data = page_get_data_size(page) + insert_size; total_n_recs = page_get_n_recs(page) + 1; ut_ad(total_n_recs >= 2); total_space = total_data + page_dir_calc_reserved_space(total_n_recs); n = 0; incl_data = 0; ins_rec = btr_cur_get_rec(cursor); rec = page_get_infimum_rec(page); heap = NULL; offsets = NULL; /* We start to include records to the left half, and when the space reserved by them exceeds half of total_space, then if the included records fit on the left page, they will be put there if something was left over also for the right page, otherwise the last included record will be the first on the right half page */ do { /* Decide the next record to include */ if (rec == ins_rec) { rec = NULL; /* NULL denotes that tuple is now included */ } else if (rec == NULL) { rec = page_rec_get_next(ins_rec); } else { rec = page_rec_get_next(rec); } if (rec == NULL) { /* Include tuple */ incl_data += insert_size; } else { offsets = rec_get_offsets(rec, cursor->index, offsets, ULINT_UNDEFINED, &heap); incl_data += rec_offs_size(offsets); } n++; } while (incl_data + page_dir_calc_reserved_space(n) < total_space / 2); if (incl_data + page_dir_calc_reserved_space(n) <= free_space) { /* The next record will be the first on the right half page if it is not the supremum record of page */ if (rec == ins_rec) { rec = NULL; goto func_exit; } else if (rec == NULL) { next_rec = page_rec_get_next(ins_rec); } else { next_rec = page_rec_get_next(rec); } ut_ad(next_rec); if (!page_rec_is_supremum(next_rec)) { rec = next_rec; } } func_exit: if (heap) { mem_heap_free(heap); } return(rec); } /*************************************************************//** Returns TRUE if the insert fits on the appropriate half-page with the chosen split_rec. @return true if fits */ static MY_ATTRIBUTE((nonnull(1,3,4,6), warn_unused_result)) bool btr_page_insert_fits( /*=================*/ btr_cur_t* cursor, /*!< in: cursor at which insert should be made */ const rec_t* split_rec,/*!< in: suggestion for first record on upper half-page, or NULL if tuple to be inserted should be first */ ulint** offsets,/*!< in: rec_get_offsets( split_rec, cursor->index); out: garbage */ const dtuple_t* tuple, /*!< in: tuple to insert */ ulint n_ext, /*!< in: number of externally stored columns */ mem_heap_t** heap) /*!< in: temporary memory heap */ { page_t* page; ulint insert_size; ulint free_space; ulint total_data; ulint total_n_recs; const rec_t* rec; const rec_t* end_rec; page = btr_cur_get_page(cursor); ut_ad(!split_rec || !page_is_comp(page) == !rec_offs_comp(*offsets)); ut_ad(!split_rec || rec_offs_validate(split_rec, cursor->index, *offsets)); insert_size = rec_get_converted_size(cursor->index, tuple, n_ext); free_space = page_get_free_space_of_empty(page_is_comp(page)); /* free_space is now the free space of a created new page */ total_data = page_get_data_size(page) + insert_size; total_n_recs = page_get_n_recs(page) + 1; /* We determine which records (from rec to end_rec, not including end_rec) will end up on the other half page from tuple when it is inserted. */ if (split_rec == NULL) { rec = page_rec_get_next(page_get_infimum_rec(page)); end_rec = page_rec_get_next(btr_cur_get_rec(cursor)); } else if (cmp_dtuple_rec(tuple, split_rec, *offsets) >= 0) { rec = page_rec_get_next(page_get_infimum_rec(page)); end_rec = split_rec; } else { rec = split_rec; end_rec = page_get_supremum_rec(page); } if (total_data + page_dir_calc_reserved_space(total_n_recs) <= free_space) { /* Ok, there will be enough available space on the half page where the tuple is inserted */ return(true); } while (rec != end_rec) { /* In this loop we calculate the amount of reserved space after rec is removed from page. */ *offsets = rec_get_offsets(rec, cursor->index, *offsets, ULINT_UNDEFINED, heap); total_data -= rec_offs_size(*offsets); total_n_recs--; if (total_data + page_dir_calc_reserved_space(total_n_recs) <= free_space) { /* Ok, there will be enough available space on the half page where the tuple is inserted */ return(true); } rec = page_rec_get_next_const(rec); } return(false); } /*******************************************************//** Inserts a data tuple to a tree on a non-leaf level. It is assumed that mtr holds an x-latch on the tree. */ UNIV_INTERN void btr_insert_on_non_leaf_level_func( /*==============================*/ ulint flags, /*!< in: undo logging and locking flags */ dict_index_t* index, /*!< in: index */ ulint level, /*!< in: level, must be > 0 */ dtuple_t* tuple, /*!< in: the record to be inserted */ const char* file, /*!< in: file name */ ulint line, /*!< in: line where called */ mtr_t* mtr) /*!< in: mtr */ { big_rec_t* dummy_big_rec; btr_cur_t cursor; dberr_t err; rec_t* rec; ulint* offsets = NULL; mem_heap_t* heap = NULL; ut_ad(level > 0); btr_cur_search_to_nth_level(index, level, tuple, PAGE_CUR_LE, BTR_CONT_MODIFY_TREE, &cursor, 0, file, line, mtr); ut_ad(cursor.flag == BTR_CUR_BINARY); err = btr_cur_optimistic_insert( flags | BTR_NO_LOCKING_FLAG | BTR_KEEP_SYS_FLAG | BTR_NO_UNDO_LOG_FLAG, &cursor, &offsets, &heap, tuple, &rec, &dummy_big_rec, 0, NULL, mtr); if (err == DB_FAIL) { err = btr_cur_pessimistic_insert(flags | BTR_NO_LOCKING_FLAG | BTR_KEEP_SYS_FLAG | BTR_NO_UNDO_LOG_FLAG, &cursor, &offsets, &heap, tuple, &rec, &dummy_big_rec, 0, NULL, mtr); ut_a(err == DB_SUCCESS); } mem_heap_free(heap); } /**************************************************************//** Attaches the halves of an index page on the appropriate level in an index tree. */ static MY_ATTRIBUTE((nonnull)) void btr_attach_half_pages( /*==================*/ ulint flags, /*!< in: undo logging and locking flags */ dict_index_t* index, /*!< in: the index tree */ buf_block_t* block, /*!< in/out: page to be split */ const rec_t* split_rec, /*!< in: first record on upper half page */ buf_block_t* new_block, /*!< in/out: the new half page */ ulint direction, /*!< in: FSP_UP or FSP_DOWN */ mtr_t* mtr) /*!< in: mtr */ { ulint space; ulint zip_size; ulint prev_page_no; ulint next_page_no; ulint level; page_t* page = buf_block_get_frame(block); page_t* lower_page; page_t* upper_page; ulint lower_page_no; ulint upper_page_no; page_zip_des_t* lower_page_zip; page_zip_des_t* upper_page_zip; dtuple_t* node_ptr_upper; mem_heap_t* heap; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); ut_ad(mtr_memo_contains(mtr, new_block, MTR_MEMO_PAGE_X_FIX)); /* Create a memory heap where the data tuple is stored */ heap = mem_heap_create(1024); /* Based on split direction, decide upper and lower pages */ if (direction == FSP_DOWN) { btr_cur_t cursor; ulint* offsets; lower_page = buf_block_get_frame(new_block); lower_page_no = buf_block_get_page_no(new_block); lower_page_zip = buf_block_get_page_zip(new_block); upper_page = buf_block_get_frame(block); upper_page_no = buf_block_get_page_no(block); upper_page_zip = buf_block_get_page_zip(block); /* Look up the index for the node pointer to page */ offsets = btr_page_get_father_block(NULL, heap, index, block, mtr, &cursor); /* Replace the address of the old child node (= page) with the address of the new lower half */ btr_node_ptr_set_child_page_no( btr_cur_get_rec(&cursor), btr_cur_get_page_zip(&cursor), offsets, lower_page_no, mtr); mem_heap_empty(heap); } else { lower_page = buf_block_get_frame(block); lower_page_no = buf_block_get_page_no(block); lower_page_zip = buf_block_get_page_zip(block); upper_page = buf_block_get_frame(new_block); upper_page_no = buf_block_get_page_no(new_block); upper_page_zip = buf_block_get_page_zip(new_block); } /* Get the level of the split pages */ level = btr_page_get_level(buf_block_get_frame(block), mtr); ut_ad(level == btr_page_get_level(buf_block_get_frame(new_block), mtr)); /* Build the node pointer (= node key and page address) for the upper half */ node_ptr_upper = dict_index_build_node_ptr(index, split_rec, upper_page_no, heap, level); /* Insert it next to the pointer to the lower half. Note that this may generate recursion leading to a split on the higher level. */ btr_insert_on_non_leaf_level(flags, index, level + 1, node_ptr_upper, mtr); /* Free the memory heap */ mem_heap_free(heap); /* Get the previous and next pages of page */ prev_page_no = btr_page_get_prev(page, mtr); next_page_no = btr_page_get_next(page, mtr); space = buf_block_get_space(block); zip_size = buf_block_get_zip_size(block); /* Update page links of the level */ if (prev_page_no != FIL_NULL) { buf_block_t* prev_block = btr_block_get( space, zip_size, prev_page_no, RW_X_LATCH, index, mtr); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(prev_block->frame) == page_is_comp(page)); ut_a(btr_page_get_next(prev_block->frame, mtr) == buf_block_get_page_no(block)); #endif /* UNIV_BTR_DEBUG */ btr_page_set_next(buf_block_get_frame(prev_block), buf_block_get_page_zip(prev_block), lower_page_no, mtr); } if (next_page_no != FIL_NULL) { buf_block_t* next_block = btr_block_get( space, zip_size, next_page_no, RW_X_LATCH, index, mtr); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(next_block->frame) == page_is_comp(page)); ut_a(btr_page_get_prev(next_block->frame, mtr) == page_get_page_no(page)); #endif /* UNIV_BTR_DEBUG */ btr_page_set_prev(buf_block_get_frame(next_block), buf_block_get_page_zip(next_block), upper_page_no, mtr); } btr_page_set_prev(lower_page, lower_page_zip, prev_page_no, mtr); btr_page_set_next(lower_page, lower_page_zip, upper_page_no, mtr); btr_page_set_prev(upper_page, upper_page_zip, lower_page_no, mtr); btr_page_set_next(upper_page, upper_page_zip, next_page_no, mtr); } /*************************************************************//** Determine if a tuple is smaller than any record on the page. @return TRUE if smaller */ static MY_ATTRIBUTE((nonnull, warn_unused_result)) bool btr_page_tuple_smaller( /*===================*/ btr_cur_t* cursor, /*!< in: b-tree cursor */ const dtuple_t* tuple, /*!< in: tuple to consider */ ulint** offsets,/*!< in/out: temporary storage */ ulint n_uniq, /*!< in: number of unique fields in the index page records */ mem_heap_t** heap) /*!< in/out: heap for offsets */ { buf_block_t* block; const rec_t* first_rec; page_cur_t pcur; /* Read the first user record in the page. */ block = btr_cur_get_block(cursor); page_cur_set_before_first(block, &pcur); page_cur_move_to_next(&pcur); first_rec = page_cur_get_rec(&pcur); *offsets = rec_get_offsets( first_rec, cursor->index, *offsets, n_uniq, heap); return(cmp_dtuple_rec(tuple, first_rec, *offsets) < 0); } /** Insert the tuple into the right sibling page, if the cursor is at the end of a page. @param[in] flags undo logging and locking flags @param[in,out] cursor cursor at which to insert; when the function succeeds, the cursor is positioned before the insert point. @param[out] offsets offsets on inserted record @param[in,out] heap memory heap for allocating offsets @param[in] tuple tuple to insert @param[in] n_ext number of externally stored columns @param[in,out] mtr mini-transaction @return inserted record (first record on the right sibling page); the cursor will be positioned on the page infimum @retval NULL if the operation was not performed */ static rec_t* btr_insert_into_right_sibling( ulint flags, btr_cur_t* cursor, ulint** offsets, mem_heap_t* heap, const dtuple_t* tuple, ulint n_ext, mtr_t* mtr) { buf_block_t* block = btr_cur_get_block(cursor); page_t* page = buf_block_get_frame(block); ulint next_page_no = btr_page_get_next(page, mtr); ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(cursor->index), MTR_MEMO_X_LOCK)); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); ut_ad(heap); if (next_page_no == FIL_NULL || !page_rec_is_supremum( page_rec_get_next(btr_cur_get_rec(cursor)))) { return(NULL); } page_cur_t next_page_cursor; buf_block_t* next_block; page_t* next_page; btr_cur_t next_father_cursor; rec_t* rec = NULL; ulint zip_size = buf_block_get_zip_size(block); ulint max_size; next_block = btr_block_get( buf_block_get_space(block), zip_size, next_page_no, RW_X_LATCH, cursor->index, mtr); next_page = buf_block_get_frame(next_block); bool is_leaf = page_is_leaf(next_page); btr_page_get_father( cursor->index, next_block, mtr, &next_father_cursor); page_cur_search( next_block, cursor->index, tuple, PAGE_CUR_LE, &next_page_cursor); max_size = page_get_max_insert_size_after_reorganize(next_page, 1); /* Extends gap lock for the next page */ lock_update_split_left(next_block, block); rec = page_cur_tuple_insert( &next_page_cursor, tuple, cursor->index, offsets, &heap, n_ext, mtr); if (rec == NULL) { if (zip_size && is_leaf && !dict_index_is_clust(cursor->index)) { /* Reset the IBUF_BITMAP_FREE bits, because page_cur_tuple_insert() will have attempted page reorganize before failing. */ ibuf_reset_free_bits(next_block); } return(NULL); } ibool compressed; dberr_t err; ulint level = btr_page_get_level(next_page, mtr); /* adjust cursor position */ *btr_cur_get_page_cur(cursor) = next_page_cursor; ut_ad(btr_cur_get_rec(cursor) == page_get_infimum_rec(next_page)); ut_ad(page_rec_get_next(page_get_infimum_rec(next_page)) == rec); /* We have to change the parent node pointer */ compressed = btr_cur_pessimistic_delete( &err, TRUE, &next_father_cursor, BTR_CREATE_FLAG, RB_NONE, mtr); ut_a(err == DB_SUCCESS); if (!compressed) { btr_cur_compress_if_useful(&next_father_cursor, FALSE, mtr); } dtuple_t* node_ptr = dict_index_build_node_ptr( cursor->index, rec, buf_block_get_page_no(next_block), heap, level); btr_insert_on_non_leaf_level( flags, cursor->index, level + 1, node_ptr, mtr); ut_ad(rec_offs_validate(rec, cursor->index, *offsets)); if (is_leaf && !dict_index_is_clust(cursor->index)) { /* Update the free bits of the B-tree page in the insert buffer bitmap. */ if (zip_size) { ibuf_update_free_bits_zip(next_block, mtr); } else { ibuf_update_free_bits_if_full( next_block, max_size, rec_offs_size(*offsets) + PAGE_DIR_SLOT_SIZE); } } return(rec); } /*************************************************************//** Splits an index page to halves and inserts the tuple. It is assumed that mtr holds an x-latch to the index tree. NOTE: the tree x-latch is released within this function! NOTE that the operation of this function must always succeed, we cannot reverse it: therefore enough free disk space (2 pages) must be guaranteed to be available before this function is called. NOTE: jonaso added support for calling function with tuple == NULL which cause it to only split a page. @return inserted record or NULL if run out of space */ UNIV_INTERN rec_t* btr_page_split_and_insert( /*======================*/ ulint flags, /*!< in: undo logging and locking flags */ btr_cur_t* cursor, /*!< in: cursor at which to insert; when the function returns, the cursor is positioned on the predecessor of the inserted record */ ulint** offsets,/*!< out: offsets on inserted record */ mem_heap_t** heap, /*!< in/out: pointer to memory heap, or NULL */ const dtuple_t* tuple, /*!< in: tuple to insert */ ulint n_ext, /*!< in: number of externally stored columns */ mtr_t* mtr) /*!< in: mtr */ { buf_block_t* block; page_t* page; page_zip_des_t* page_zip; ulint page_no; byte direction; ulint hint_page_no; buf_block_t* new_block; page_t* new_page; page_zip_des_t* new_page_zip; rec_t* split_rec; buf_block_t* left_block; buf_block_t* right_block; buf_block_t* insert_block; page_cur_t* page_cursor; rec_t* first_rec; byte* buf = 0; /* remove warning */ rec_t* move_limit; ibool insert_will_fit; ibool insert_left; ulint n_iterations = 0; rec_t* rec; ulint n_uniq; if (!*heap) { *heap = mem_heap_create(1024); } n_uniq = dict_index_get_n_unique_in_tree(cursor->index); func_start: mem_heap_empty(*heap); *offsets = NULL; ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(cursor->index), MTR_MEMO_X_LOCK)); ut_ad(!dict_index_is_online_ddl(cursor->index) || (flags & BTR_CREATE_FLAG) || dict_index_is_clust(cursor->index)); #ifdef UNIV_SYNC_DEBUG ut_ad(rw_lock_own(dict_index_get_lock(cursor->index), RW_LOCK_EX)); #endif /* UNIV_SYNC_DEBUG */ block = btr_cur_get_block(cursor); page = buf_block_get_frame(block); page_zip = buf_block_get_page_zip(block); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); ut_ad(!page_is_empty(page)); /* try to insert to the next page if possible before split */ rec = btr_insert_into_right_sibling( flags, cursor, offsets, *heap, tuple, n_ext, mtr); if (rec != NULL) { return(rec); } page_no = buf_block_get_page_no(block); /* 1. Decide the split record; split_rec == NULL means that the tuple to be inserted should be the first record on the upper half-page */ insert_left = FALSE; if (tuple != NULL && n_iterations > 0) { direction = FSP_UP; hint_page_no = page_no + 1; split_rec = btr_page_get_split_rec(cursor, tuple, n_ext); if (split_rec == NULL) { insert_left = btr_page_tuple_smaller( cursor, tuple, offsets, n_uniq, heap); } } else if (btr_page_get_split_rec_to_right(cursor, &split_rec)) { direction = FSP_UP; hint_page_no = page_no + 1; } else if (btr_page_get_split_rec_to_left(cursor, &split_rec)) { direction = FSP_DOWN; hint_page_no = page_no - 1; ut_ad(split_rec); } else { direction = FSP_UP; hint_page_no = page_no + 1; /* If there is only one record in the index page, we can't split the node in the middle by default. We need to determine whether the new record will be inserted to the left or right. */ if (page_get_n_recs(page) > 1) { split_rec = page_get_middle_rec(page); } else if (btr_page_tuple_smaller(cursor, tuple, offsets, n_uniq, heap)) { split_rec = page_rec_get_next( page_get_infimum_rec(page)); } else { split_rec = NULL; } } DBUG_EXECUTE_IF("disk_is_full", os_has_said_disk_full = true; return(NULL);); /* 2. Allocate a new page to the index */ new_block = btr_page_alloc(cursor->index, hint_page_no, direction, btr_page_get_level(page, mtr), mtr, mtr); if (new_block == NULL && os_has_said_disk_full) { return(NULL); } new_page = buf_block_get_frame(new_block); new_page_zip = buf_block_get_page_zip(new_block); btr_page_create(new_block, new_page_zip, cursor->index, btr_page_get_level(page, mtr), mtr); /* Only record the leaf level page splits. */ if (btr_page_get_level(page, mtr) == 0) { cursor->index->stat_defrag_n_page_split ++; cursor->index->stat_defrag_modified_counter ++; btr_defragment_save_defrag_stats_if_needed(cursor->index); } /* 3. Calculate the first record on the upper half-page, and the first record (move_limit) on original page which ends up on the upper half */ if (split_rec) { first_rec = move_limit = split_rec; *offsets = rec_get_offsets(split_rec, cursor->index, *offsets, n_uniq, heap); if (tuple != NULL) { insert_left = cmp_dtuple_rec( tuple, split_rec, *offsets) < 0; } else { insert_left = 1; } if (!insert_left && new_page_zip && n_iterations > 0) { /* If a compressed page has already been split, avoid further splits by inserting the record to an empty page. */ split_rec = NULL; goto insert_empty; } } else if (insert_left) { ut_a(n_iterations > 0); first_rec = page_rec_get_next(page_get_infimum_rec(page)); move_limit = page_rec_get_next(btr_cur_get_rec(cursor)); } else { insert_empty: ut_ad(!split_rec); ut_ad(!insert_left); buf = (byte*) mem_alloc(rec_get_converted_size(cursor->index, tuple, n_ext)); first_rec = rec_convert_dtuple_to_rec(buf, cursor->index, tuple, n_ext); move_limit = page_rec_get_next(btr_cur_get_rec(cursor)); } /* 4. Do first the modifications in the tree structure */ btr_attach_half_pages(flags, cursor->index, block, first_rec, new_block, direction, mtr); /* If the split is made on the leaf level and the insert will fit on the appropriate half-page, we may release the tree x-latch. We can then move the records after releasing the tree latch, thus reducing the tree latch contention. */ if (tuple == NULL) { insert_will_fit = 1; } else if (split_rec) { insert_will_fit = !new_page_zip && btr_page_insert_fits(cursor, split_rec, offsets, tuple, n_ext, heap); } else { if (!insert_left) { mem_free(buf); buf = NULL; } insert_will_fit = !new_page_zip && btr_page_insert_fits(cursor, NULL, offsets, tuple, n_ext, heap); } if (insert_will_fit && page_is_leaf(page) && !dict_index_is_online_ddl(cursor->index)) { mtr_memo_release(mtr, dict_index_get_lock(cursor->index), MTR_MEMO_X_LOCK); } /* 5. Move then the records to the new page */ if (direction == FSP_DOWN) { /* fputs("Split left\n", stderr); */ if (0 #ifdef UNIV_ZIP_COPY || page_zip #endif /* UNIV_ZIP_COPY */ || !page_move_rec_list_start(new_block, block, move_limit, cursor->index, mtr)) { /* For some reason, compressing new_page failed, even though it should contain fewer records than the original page. Copy the page byte for byte and then delete the records from both pages as appropriate. Deleting will always succeed. */ ut_a(new_page_zip); page_zip_copy_recs(new_page_zip, new_page, page_zip, page, cursor->index, mtr); page_delete_rec_list_end(move_limit - page + new_page, new_block, cursor->index, ULINT_UNDEFINED, ULINT_UNDEFINED, mtr); /* Update the lock table and possible hash index. */ lock_move_rec_list_start( new_block, block, move_limit, new_page + PAGE_NEW_INFIMUM); btr_search_move_or_delete_hash_entries( new_block, block, cursor->index); /* Delete the records from the source page. */ page_delete_rec_list_start(move_limit, block, cursor->index, mtr); } left_block = new_block; right_block = block; lock_update_split_left(right_block, left_block); } else { /* fputs("Split right\n", stderr); */ if (0 #ifdef UNIV_ZIP_COPY || page_zip #endif /* UNIV_ZIP_COPY */ || !page_move_rec_list_end(new_block, block, move_limit, cursor->index, mtr)) { /* For some reason, compressing new_page failed, even though it should contain fewer records than the original page. Copy the page byte for byte and then delete the records from both pages as appropriate. Deleting will always succeed. */ ut_a(new_page_zip); page_zip_copy_recs(new_page_zip, new_page, page_zip, page, cursor->index, mtr); page_delete_rec_list_start(move_limit - page + new_page, new_block, cursor->index, mtr); /* Update the lock table and possible hash index. */ lock_move_rec_list_end(new_block, block, move_limit); btr_search_move_or_delete_hash_entries( new_block, block, cursor->index); /* Delete the records from the source page. */ page_delete_rec_list_end(move_limit, block, cursor->index, ULINT_UNDEFINED, ULINT_UNDEFINED, mtr); } left_block = block; right_block = new_block; lock_update_split_right(right_block, left_block); } #ifdef UNIV_ZIP_DEBUG if (page_zip) { ut_a(page_zip_validate(page_zip, page, cursor->index)); ut_a(page_zip_validate(new_page_zip, new_page, cursor->index)); } #endif /* UNIV_ZIP_DEBUG */ /* At this point, split_rec, move_limit and first_rec may point to garbage on the old page. */ /* 6. The split and the tree modification is now completed. Decide the page where the tuple should be inserted */ if (tuple == NULL) { rec = NULL; goto func_exit; } if (insert_left) { insert_block = left_block; } else { insert_block = right_block; } /* 7. Reposition the cursor for insert and try insertion */ page_cursor = btr_cur_get_page_cur(cursor); page_cur_search(insert_block, cursor->index, tuple, PAGE_CUR_LE, page_cursor); rec = page_cur_tuple_insert(page_cursor, tuple, cursor->index, offsets, heap, n_ext, mtr); #ifdef UNIV_ZIP_DEBUG { page_t* insert_page = buf_block_get_frame(insert_block); page_zip_des_t* insert_page_zip = buf_block_get_page_zip(insert_block); ut_a(!insert_page_zip || page_zip_validate(insert_page_zip, insert_page, cursor->index)); } #endif /* UNIV_ZIP_DEBUG */ if (rec != NULL) { goto func_exit; } /* 8. If insert did not fit, try page reorganization. For compressed pages, page_cur_tuple_insert() will have attempted this already. */ if (page_cur_get_page_zip(page_cursor) || !btr_page_reorganize(page_cursor, cursor->index, mtr)) { goto insert_failed; } rec = page_cur_tuple_insert(page_cursor, tuple, cursor->index, offsets, heap, n_ext, mtr); if (rec == NULL) { /* The insert did not fit on the page: loop back to the start of the function for a new split */ insert_failed: /* We play safe and reset the free bits */ if (!dict_index_is_clust(cursor->index)) { ibuf_reset_free_bits(new_block); ibuf_reset_free_bits(block); } /* fprintf(stderr, "Split second round %lu\n", page_get_page_no(page)); */ n_iterations++; ut_ad(n_iterations < 2 || buf_block_get_page_zip(insert_block)); ut_ad(!insert_will_fit); goto func_start; } func_exit: /* Insert fit on the page: update the free bits for the left and right pages in the same mtr */ if (!dict_index_is_clust(cursor->index) && page_is_leaf(page)) { ibuf_update_free_bits_for_two_pages_low( buf_block_get_zip_size(left_block), left_block, right_block, mtr); } #if 0 fprintf(stderr, "Split and insert done %lu %lu\n", buf_block_get_page_no(left_block), buf_block_get_page_no(right_block)); #endif MONITOR_INC(MONITOR_INDEX_SPLIT); ut_ad(page_validate(buf_block_get_frame(left_block), cursor->index)); ut_ad(page_validate(buf_block_get_frame(right_block), cursor->index)); if (tuple == NULL) { ut_ad(rec == NULL); } ut_ad(!rec || rec_offs_validate(rec, cursor->index, *offsets)); return(rec); } /*************************************************************//** Removes a page from the level list of pages. */ UNIV_INTERN void btr_level_list_remove_func( /*=======================*/ ulint space, /*!< in: space where removed */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ page_t* page, /*!< in/out: page to remove */ dict_index_t* index, /*!< in: index tree */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint prev_page_no; ulint next_page_no; ut_ad(page != NULL); ut_ad(mtr != NULL); ut_ad(mtr_memo_contains_page(mtr, page, MTR_MEMO_PAGE_X_FIX)); ut_ad(space == page_get_space_id(page)); /* Get the previous and next page numbers of page */ prev_page_no = btr_page_get_prev(page, mtr); next_page_no = btr_page_get_next(page, mtr); /* Update page links of the level */ if (prev_page_no != FIL_NULL) { buf_block_t* prev_block = btr_block_get(space, zip_size, prev_page_no, RW_X_LATCH, index, mtr); page_t* prev_page = buf_block_get_frame(prev_block); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(prev_page) == page_is_comp(page)); ut_a(btr_page_get_next(prev_page, mtr) == page_get_page_no(page)); #endif /* UNIV_BTR_DEBUG */ btr_page_set_next(prev_page, buf_block_get_page_zip(prev_block), next_page_no, mtr); } if (next_page_no != FIL_NULL) { buf_block_t* next_block = btr_block_get(space, zip_size, next_page_no, RW_X_LATCH, index, mtr); page_t* next_page = buf_block_get_frame(next_block); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(next_page) == page_is_comp(page)); ut_a(btr_page_get_prev(next_page, mtr) == page_get_page_no(page)); #endif /* UNIV_BTR_DEBUG */ btr_page_set_prev(next_page, buf_block_get_page_zip(next_block), prev_page_no, mtr); } } /****************************************************************//** Writes the redo log record for setting an index record as the predefined minimum record. */ UNIV_INLINE void btr_set_min_rec_mark_log( /*=====================*/ rec_t* rec, /*!< in: record */ byte type, /*!< in: MLOG_COMP_REC_MIN_MARK or MLOG_REC_MIN_MARK */ mtr_t* mtr) /*!< in: mtr */ { mlog_write_initial_log_record(rec, type, mtr); /* Write rec offset as a 2-byte ulint */ mlog_catenate_ulint(mtr, page_offset(rec), MLOG_2BYTES); } #else /* !UNIV_HOTBACKUP */ # define btr_set_min_rec_mark_log(rec,comp,mtr) ((void) 0) #endif /* !UNIV_HOTBACKUP */ /****************************************************************//** Parses the redo log record for setting an index record as the predefined minimum record. @return end of log record or NULL */ UNIV_INTERN byte* btr_parse_set_min_rec_mark( /*=======================*/ byte* ptr, /*!< in: buffer */ byte* end_ptr,/*!< in: buffer end */ ulint comp, /*!< in: nonzero=compact page format */ page_t* page, /*!< in: page or NULL */ mtr_t* mtr) /*!< in: mtr or NULL */ { rec_t* rec; if (end_ptr < ptr + 2) { return(NULL); } if (page) { ut_a(!page_is_comp(page) == !comp); rec = page + mach_read_from_2(ptr); btr_set_min_rec_mark(rec, mtr); } return(ptr + 2); } /****************************************************************//** Sets a record as the predefined minimum record. */ UNIV_INTERN void btr_set_min_rec_mark( /*=================*/ rec_t* rec, /*!< in: record */ mtr_t* mtr) /*!< in: mtr */ { ulint info_bits; if (page_rec_is_comp(rec)) { info_bits = rec_get_info_bits(rec, TRUE); rec_set_info_bits_new(rec, info_bits | REC_INFO_MIN_REC_FLAG); btr_set_min_rec_mark_log(rec, MLOG_COMP_REC_MIN_MARK, mtr); } else { info_bits = rec_get_info_bits(rec, FALSE); rec_set_info_bits_old(rec, info_bits | REC_INFO_MIN_REC_FLAG); btr_set_min_rec_mark_log(rec, MLOG_REC_MIN_MARK, mtr); } } #ifndef UNIV_HOTBACKUP /*************************************************************//** Deletes on the upper level the node pointer to a page. */ UNIV_INTERN void btr_node_ptr_delete( /*================*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: page whose node pointer is deleted */ mtr_t* mtr) /*!< in: mtr */ { btr_cur_t cursor; ibool compressed; dberr_t err; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); /* Delete node pointer on father page */ btr_page_get_father(index, block, mtr, &cursor); compressed = btr_cur_pessimistic_delete(&err, TRUE, &cursor, BTR_CREATE_FLAG, RB_NONE, mtr); ut_a(err == DB_SUCCESS); if (!compressed) { btr_cur_compress_if_useful(&cursor, FALSE, mtr); } } /*************************************************************//** If page is the only on its level, this function moves its records to the father page, thus reducing the tree height. @return father block */ UNIV_INTERN buf_block_t* btr_lift_page_up( /*=============*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: page which is the only on its level; must not be empty: use btr_discard_only_page_on_level if the last record from the page should be removed */ mtr_t* mtr) /*!< in: mtr */ { buf_block_t* father_block; page_t* father_page; ulint page_level; page_zip_des_t* father_page_zip; page_t* page = buf_block_get_frame(block); ulint root_page_no; buf_block_t* blocks[BTR_MAX_LEVELS]; ulint n_blocks; /*!< last used index in blocks[] */ ulint i; bool lift_father_up; buf_block_t* block_orig = block; ut_ad(btr_page_get_prev(page, mtr) == FIL_NULL); ut_ad(btr_page_get_next(page, mtr) == FIL_NULL); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); page_level = btr_page_get_level(page, mtr); root_page_no = dict_index_get_page(index); { btr_cur_t cursor; ulint* offsets = NULL; mem_heap_t* heap = mem_heap_create( sizeof(*offsets) * (REC_OFFS_HEADER_SIZE + 1 + 1 + index->n_fields)); buf_block_t* b; offsets = btr_page_get_father_block(offsets, heap, index, block, mtr, &cursor); father_block = btr_cur_get_block(&cursor); father_page_zip = buf_block_get_page_zip(father_block); father_page = buf_block_get_frame(father_block); n_blocks = 0; /* Store all ancestor pages so we can reset their levels later on. We have to do all the searches on the tree now because later on, after we've replaced the first level, the tree is in an inconsistent state and can not be searched. */ for (b = father_block; buf_block_get_page_no(b) != root_page_no; ) { ut_a(n_blocks < BTR_MAX_LEVELS); offsets = btr_page_get_father_block(offsets, heap, index, b, mtr, &cursor); blocks[n_blocks++] = b = btr_cur_get_block(&cursor); } lift_father_up = (n_blocks && page_level == 0); if (lift_father_up) { /* The father page also should be the only on its level (not root). We should lift up the father page at first. Because the leaf page should be lifted up only for root page. The freeing page is based on page_level (==0 or !=0) to choose segment. If the page_level is changed ==0 from !=0, later freeing of the page doesn't find the page allocation to be freed.*/ block = father_block; page = buf_block_get_frame(block); page_level = btr_page_get_level(page, mtr); ut_ad(btr_page_get_prev(page, mtr) == FIL_NULL); ut_ad(btr_page_get_next(page, mtr) == FIL_NULL); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); father_block = blocks[0]; father_page_zip = buf_block_get_page_zip(father_block); father_page = buf_block_get_frame(father_block); } mem_heap_free(heap); } btr_search_drop_page_hash_index(block); /* Make the father empty */ btr_page_empty(father_block, father_page_zip, index, page_level, mtr); page_level++; /* Copy the records to the father page one by one. */ if (0 #ifdef UNIV_ZIP_COPY || father_page_zip #endif /* UNIV_ZIP_COPY */ || !page_copy_rec_list_end(father_block, block, page_get_infimum_rec(page), index, mtr)) { const page_zip_des_t* page_zip = buf_block_get_page_zip(block); ut_a(father_page_zip); ut_a(page_zip); /* Copy the page byte for byte. */ page_zip_copy_recs(father_page_zip, father_page, page_zip, page, index, mtr); /* Update the lock table and possible hash index. */ lock_move_rec_list_end(father_block, block, page_get_infimum_rec(page)); btr_search_move_or_delete_hash_entries(father_block, block, index); } btr_blob_dbg_remove(page, index, "btr_lift_page_up"); lock_update_copy_and_discard(father_block, block); /* Go upward to root page, decrementing levels by one. */ for (i = lift_father_up ? 1 : 0; i < n_blocks; i++, page_level++) { page_t* page = buf_block_get_frame(blocks[i]); page_zip_des_t* page_zip= buf_block_get_page_zip(blocks[i]); ut_ad(btr_page_get_level(page, mtr) == page_level + 1); btr_page_set_level(page, page_zip, page_level, mtr); #ifdef UNIV_ZIP_DEBUG ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ } /* Free the file page */ btr_page_free(index, block, mtr); /* We play it safe and reset the free bits for the father */ if (!dict_index_is_clust(index)) { ibuf_reset_free_bits(father_block); } ut_ad(page_validate(father_page, index)); ut_ad(btr_check_node_ptr(index, father_block, mtr)); return(lift_father_up ? block_orig : father_block); } /*************************************************************//** Tries to merge the page first to the left immediate brother if such a brother exists, and the node pointers to the current page and to the brother reside on the same page. If the left brother does not satisfy these conditions, looks at the right brother. If the page is the only one on that level lifts the records of the page to the father page, thus reducing the tree height. It is assumed that mtr holds an x-latch on the tree and on the page. If cursor is on the leaf level, mtr must also hold x-latches to the brothers, if they exist. @return TRUE on success */ UNIV_INTERN ibool btr_compress( /*=========*/ btr_cur_t* cursor, /*!< in/out: cursor on the page to merge or lift; the page must not be empty: when deleting records, use btr_discard_page() if the page would become empty */ ibool adjust, /*!< in: TRUE if should adjust the cursor position even if compression occurs */ mtr_t* mtr) /*!< in/out: mini-transaction */ { dict_index_t* index; ulint space; ulint zip_size; ulint left_page_no; ulint right_page_no; buf_block_t* merge_block; page_t* merge_page = NULL; page_zip_des_t* merge_page_zip; ibool is_left; buf_block_t* block; page_t* page; btr_cur_t father_cursor; mem_heap_t* heap; ulint* offsets; ulint nth_rec = 0; /* remove bogus warning */ DBUG_ENTER("btr_compress"); block = btr_cur_get_block(cursor); page = btr_cur_get_page(cursor); index = btr_cur_get_index(cursor); btr_assert_not_corrupted(block, index); ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_X_LOCK)); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); space = dict_index_get_space(index); zip_size = dict_table_zip_size(index->table); MONITOR_INC(MONITOR_INDEX_MERGE_ATTEMPTS); left_page_no = btr_page_get_prev(page, mtr); right_page_no = btr_page_get_next(page, mtr); #ifdef UNIV_DEBUG if (!page_is_leaf(page) && left_page_no == FIL_NULL) { ut_a(REC_INFO_MIN_REC_FLAG & rec_get_info_bits( page_rec_get_next(page_get_infimum_rec(page)), page_is_comp(page))); } #endif /* UNIV_DEBUG */ heap = mem_heap_create(100); offsets = btr_page_get_father_block(NULL, heap, index, block, mtr, &father_cursor); if (adjust) { nth_rec = page_rec_get_n_recs_before(btr_cur_get_rec(cursor)); ut_ad(nth_rec > 0); } if (left_page_no == FIL_NULL && right_page_no == FIL_NULL) { /* The page is the only one on the level, lift the records to the father */ merge_block = btr_lift_page_up(index, block, mtr); goto func_exit; } /* Decide the page to which we try to merge and which will inherit the locks */ is_left = btr_can_merge_with_page(cursor, left_page_no, &merge_block, mtr); DBUG_EXECUTE_IF("ib_always_merge_right", is_left = FALSE;); if(!is_left && !btr_can_merge_with_page(cursor, right_page_no, &merge_block, mtr)) { goto err_exit; } merge_page = buf_block_get_frame(merge_block); #ifdef UNIV_BTR_DEBUG if (is_left) { ut_a(btr_page_get_next(merge_page, mtr) == buf_block_get_page_no(block)); } else { ut_a(btr_page_get_prev(merge_page, mtr) == buf_block_get_page_no(block)); } #endif /* UNIV_BTR_DEBUG */ ut_ad(page_validate(merge_page, index)); merge_page_zip = buf_block_get_page_zip(merge_block); #ifdef UNIV_ZIP_DEBUG if (merge_page_zip) { const page_zip_des_t* page_zip = buf_block_get_page_zip(block); ut_a(page_zip); ut_a(page_zip_validate(merge_page_zip, merge_page, index)); ut_a(page_zip_validate(page_zip, page, index)); } #endif /* UNIV_ZIP_DEBUG */ /* Move records to the merge page */ if (is_left) { rec_t* orig_pred = page_copy_rec_list_start( merge_block, block, page_get_supremum_rec(page), index, mtr); if (!orig_pred) { goto err_exit; } btr_search_drop_page_hash_index(block); /* Remove the page from the level list */ btr_level_list_remove(space, zip_size, page, index, mtr); btr_node_ptr_delete(index, block, mtr); lock_update_merge_left(merge_block, orig_pred, block); if (adjust) { nth_rec += page_rec_get_n_recs_before(orig_pred); } } else { rec_t* orig_succ; ibool compressed; dberr_t err; btr_cur_t cursor2; /* father cursor pointing to node ptr of the right sibling */ #ifdef UNIV_BTR_DEBUG byte fil_page_prev[4]; #endif /* UNIV_BTR_DEBUG */ btr_page_get_father(index, merge_block, mtr, &cursor2); if (merge_page_zip && left_page_no == FIL_NULL) { /* The function page_zip_compress(), which will be invoked by page_copy_rec_list_end() below, requires that FIL_PAGE_PREV be FIL_NULL. Clear the field, but prepare to restore it. */ #ifdef UNIV_BTR_DEBUG memcpy(fil_page_prev, merge_page + FIL_PAGE_PREV, 4); #endif /* UNIV_BTR_DEBUG */ #if FIL_NULL != 0xffffffff # error "FIL_NULL != 0xffffffff" #endif memset(merge_page + FIL_PAGE_PREV, 0xff, 4); } orig_succ = page_copy_rec_list_end(merge_block, block, page_get_infimum_rec(page), cursor->index, mtr); if (!orig_succ) { ut_a(merge_page_zip); #ifdef UNIV_BTR_DEBUG if (left_page_no == FIL_NULL) { /* FIL_PAGE_PREV was restored from merge_page_zip. */ ut_a(!memcmp(fil_page_prev, merge_page + FIL_PAGE_PREV, 4)); } #endif /* UNIV_BTR_DEBUG */ goto err_exit; } btr_search_drop_page_hash_index(block); #ifdef UNIV_BTR_DEBUG if (merge_page_zip && left_page_no == FIL_NULL) { /* Restore FIL_PAGE_PREV in order to avoid an assertion failure in btr_level_list_remove(), which will set the field again to FIL_NULL. Even though this makes merge_page and merge_page_zip inconsistent for a split second, it is harmless, because the pages are X-latched. */ memcpy(merge_page + FIL_PAGE_PREV, fil_page_prev, 4); } #endif /* UNIV_BTR_DEBUG */ /* Remove the page from the level list */ btr_level_list_remove(space, zip_size, page, index, mtr); /* Replace the address of the old child node (= page) with the address of the merge page to the right */ btr_node_ptr_set_child_page_no( btr_cur_get_rec(&father_cursor), btr_cur_get_page_zip(&father_cursor), offsets, right_page_no, mtr); compressed = btr_cur_pessimistic_delete(&err, TRUE, &cursor2, BTR_CREATE_FLAG, RB_NONE, mtr); ut_a(err == DB_SUCCESS); if (!compressed) { btr_cur_compress_if_useful(&cursor2, FALSE, mtr); } lock_update_merge_right(merge_block, orig_succ, block); } btr_blob_dbg_remove(page, index, "btr_compress"); if (!dict_index_is_clust(index) && page_is_leaf(merge_page)) { /* Update the free bits of the B-tree page in the insert buffer bitmap. This has to be done in a separate mini-transaction that is committed before the main mini-transaction. We cannot update the insert buffer bitmap in this mini-transaction, because btr_compress() can be invoked recursively without committing the mini-transaction in between. Since insert buffer bitmap pages have a lower rank than B-tree pages, we must not access other pages in the same mini-transaction after accessing an insert buffer bitmap page. */ /* The free bits in the insert buffer bitmap must never exceed the free space on a page. It is safe to decrement or reset the bits in the bitmap in a mini-transaction that is committed before the mini-transaction that affects the free space. */ /* It is unsafe to increment the bits in a separately committed mini-transaction, because in crash recovery, the free bits could momentarily be set too high. */ if (zip_size) { /* Because the free bits may be incremented and we cannot update the insert buffer bitmap in the same mini-transaction, the only safe thing we can do here is the pessimistic approach: reset the free bits. */ ibuf_reset_free_bits(merge_block); } else { /* On uncompressed pages, the free bits will never increase here. Thus, it is safe to write the bits accurately in a separate mini-transaction. */ ibuf_update_free_bits_if_full(merge_block, UNIV_PAGE_SIZE, ULINT_UNDEFINED); } } ut_ad(page_validate(merge_page, index)); #ifdef UNIV_ZIP_DEBUG ut_a(!merge_page_zip || page_zip_validate(merge_page_zip, merge_page, index)); #endif /* UNIV_ZIP_DEBUG */ /* Free the file page */ btr_page_free(index, block, mtr); ut_ad(btr_check_node_ptr(index, merge_block, mtr)); func_exit: mem_heap_free(heap); if (adjust) { ut_ad(nth_rec > 0); btr_cur_position( index, page_rec_get_nth(merge_block->frame, nth_rec), merge_block, cursor); } MONITOR_INC(MONITOR_INDEX_MERGE_SUCCESSFUL); DBUG_RETURN(TRUE); err_exit: /* We play it safe and reset the free bits. */ if (zip_size && merge_page && page_is_leaf(merge_page) && !dict_index_is_clust(index)) { ibuf_reset_free_bits(merge_block); } mem_heap_free(heap); DBUG_RETURN(FALSE); } /*************************************************************//** Discards a page that is the only page on its level. This will empty the whole B-tree, leaving just an empty root page. This function should never be reached, because btr_compress(), which is invoked in delete operations, calls btr_lift_page_up() to flatten the B-tree. */ static void btr_discard_only_page_on_level( /*===========================*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: page which is the only on its level */ mtr_t* mtr) /*!< in: mtr */ { ulint page_level = 0; trx_id_t max_trx_id; /* Save the PAGE_MAX_TRX_ID from the leaf page. */ max_trx_id = page_get_max_trx_id(buf_block_get_frame(block)); while (buf_block_get_page_no(block) != dict_index_get_page(index)) { btr_cur_t cursor; buf_block_t* father; const page_t* page = buf_block_get_frame(block); ut_a(page_get_n_recs(page) == 1); ut_a(page_level == btr_page_get_level(page, mtr)); ut_a(btr_page_get_prev(page, mtr) == FIL_NULL); ut_a(btr_page_get_next(page, mtr) == FIL_NULL); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); btr_search_drop_page_hash_index(block); btr_page_get_father(index, block, mtr, &cursor); father = btr_cur_get_block(&cursor); lock_update_discard(father, PAGE_HEAP_NO_SUPREMUM, block); /* Free the file page */ btr_page_free(index, block, mtr); block = father; page_level++; } /* block is the root page, which must be empty, except for the node pointer to the (now discarded) block(s). */ #ifdef UNIV_BTR_DEBUG if (!dict_index_is_ibuf(index)) { const page_t* root = buf_block_get_frame(block); const ulint space = dict_index_get_space(index); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF + root, space)); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + root, space)); } #endif /* UNIV_BTR_DEBUG */ btr_page_empty(block, buf_block_get_page_zip(block), index, 0, mtr); ut_ad(page_is_leaf(buf_block_get_frame(block))); if (!dict_index_is_clust(index)) { /* We play it safe and reset the free bits for the root */ ibuf_reset_free_bits(block); ut_a(max_trx_id); page_set_max_trx_id(block, buf_block_get_page_zip(block), max_trx_id, mtr); } } /*************************************************************//** Discards a page from a B-tree. This is used to remove the last record from a B-tree page: the whole page must be removed at the same time. This cannot be used for the root page, which is allowed to be empty. */ UNIV_INTERN void btr_discard_page( /*=============*/ btr_cur_t* cursor, /*!< in: cursor on the page to discard: not on the root page */ mtr_t* mtr) /*!< in: mtr */ { dict_index_t* index; ulint space; ulint zip_size; ulint left_page_no; ulint right_page_no; buf_block_t* merge_block; page_t* merge_page; buf_block_t* block; page_t* page; rec_t* node_ptr; block = btr_cur_get_block(cursor); index = btr_cur_get_index(cursor); ut_ad(dict_index_get_page(index) != buf_block_get_page_no(block)); ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_X_LOCK)); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); space = dict_index_get_space(index); zip_size = dict_table_zip_size(index->table); MONITOR_INC(MONITOR_INDEX_DISCARD); /* Decide the page which will inherit the locks */ left_page_no = btr_page_get_prev(buf_block_get_frame(block), mtr); right_page_no = btr_page_get_next(buf_block_get_frame(block), mtr); if (left_page_no != FIL_NULL) { merge_block = btr_block_get(space, zip_size, left_page_no, RW_X_LATCH, index, mtr); merge_page = buf_block_get_frame(merge_block); #ifdef UNIV_BTR_DEBUG ut_a(btr_page_get_next(merge_page, mtr) == buf_block_get_page_no(block)); #endif /* UNIV_BTR_DEBUG */ } else if (right_page_no != FIL_NULL) { merge_block = btr_block_get(space, zip_size, right_page_no, RW_X_LATCH, index, mtr); merge_page = buf_block_get_frame(merge_block); #ifdef UNIV_BTR_DEBUG ut_a(btr_page_get_prev(merge_page, mtr) == buf_block_get_page_no(block)); #endif /* UNIV_BTR_DEBUG */ } else { btr_discard_only_page_on_level(index, block, mtr); return; } page = buf_block_get_frame(block); ut_a(page_is_comp(merge_page) == page_is_comp(page)); btr_search_drop_page_hash_index(block); if (left_page_no == FIL_NULL && !page_is_leaf(page)) { /* We have to mark the leftmost node pointer on the right side page as the predefined minimum record */ node_ptr = page_rec_get_next(page_get_infimum_rec(merge_page)); ut_ad(page_rec_is_user_rec(node_ptr)); /* This will make page_zip_validate() fail on merge_page until btr_level_list_remove() completes. This is harmless, because everything will take place within a single mini-transaction and because writing to the redo log is an atomic operation (performed by mtr_commit()). */ btr_set_min_rec_mark(node_ptr, mtr); } btr_node_ptr_delete(index, block, mtr); /* Remove the page from the level list */ btr_level_list_remove(space, zip_size, page, index, mtr); #ifdef UNIV_ZIP_DEBUG { page_zip_des_t* merge_page_zip = buf_block_get_page_zip(merge_block); ut_a(!merge_page_zip || page_zip_validate(merge_page_zip, merge_page, index)); } #endif /* UNIV_ZIP_DEBUG */ if (left_page_no != FIL_NULL) { lock_update_discard(merge_block, PAGE_HEAP_NO_SUPREMUM, block); } else { lock_update_discard(merge_block, lock_get_min_heap_no(merge_block), block); } btr_blob_dbg_remove(page, index, "btr_discard_page"); /* Free the file page */ btr_page_free(index, block, mtr); ut_ad(btr_check_node_ptr(index, merge_block, mtr)); } #ifdef UNIV_BTR_PRINT /*************************************************************//** Prints size info of a B-tree. */ UNIV_INTERN void btr_print_size( /*===========*/ dict_index_t* index) /*!< in: index tree */ { page_t* root; fseg_header_t* seg; mtr_t mtr; if (dict_index_is_ibuf(index)) { fputs("Sorry, cannot print info of an ibuf tree:" " use ibuf functions\n", stderr); return; } mtr_start(&mtr); root = btr_root_get(index, &mtr); seg = root + PAGE_HEADER + PAGE_BTR_SEG_TOP; fputs("INFO OF THE NON-LEAF PAGE SEGMENT\n", stderr); fseg_print(seg, &mtr); if (!dict_index_is_univ(index)) { seg = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF; fputs("INFO OF THE LEAF PAGE SEGMENT\n", stderr); fseg_print(seg, &mtr); } mtr_commit(&mtr); } /************************************************************//** Prints recursively index tree pages. */ static void btr_print_recursive( /*================*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: index page */ ulint width, /*!< in: print this many entries from start and end */ mem_heap_t** heap, /*!< in/out: heap for rec_get_offsets() */ ulint** offsets,/*!< in/out: buffer for rec_get_offsets() */ mtr_t* mtr) /*!< in: mtr */ { const page_t* page = buf_block_get_frame(block); page_cur_t cursor; ulint n_recs; ulint i = 0; mtr_t mtr2; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); fprintf(stderr, "NODE ON LEVEL %lu page number %lu\n", (ulong) btr_page_get_level(page, mtr), (ulong) buf_block_get_page_no(block)); page_print(block, index, width, width); n_recs = page_get_n_recs(page); page_cur_set_before_first(block, &cursor); page_cur_move_to_next(&cursor); while (!page_cur_is_after_last(&cursor)) { if (page_is_leaf(page)) { /* If this is the leaf level, do nothing */ } else if ((i <= width) || (i >= n_recs - width)) { const rec_t* node_ptr; mtr_start(&mtr2); node_ptr = page_cur_get_rec(&cursor); *offsets = rec_get_offsets(node_ptr, index, *offsets, ULINT_UNDEFINED, heap); btr_print_recursive(index, btr_node_ptr_get_child(node_ptr, index, *offsets, &mtr2), width, heap, offsets, &mtr2); mtr_commit(&mtr2); } page_cur_move_to_next(&cursor); i++; } } /**************************************************************//** Prints directories and other info of all nodes in the tree. */ UNIV_INTERN void btr_print_index( /*============*/ dict_index_t* index, /*!< in: index */ ulint width) /*!< in: print this many entries from start and end */ { mtr_t mtr; buf_block_t* root; mem_heap_t* heap = NULL; ulint offsets_[REC_OFFS_NORMAL_SIZE]; ulint* offsets = offsets_; rec_offs_init(offsets_); fputs("--------------------------\n" "INDEX TREE PRINT\n", stderr); mtr_start(&mtr); root = btr_root_block_get(index, RW_X_LATCH, &mtr); btr_print_recursive(index, root, width, &heap, &offsets, &mtr); if (heap) { mem_heap_free(heap); } mtr_commit(&mtr); btr_validate_index(index, 0); } #endif /* UNIV_BTR_PRINT */ #ifdef UNIV_DEBUG /************************************************************//** Checks that the node pointer to a page is appropriate. @return TRUE */ UNIV_INTERN ibool btr_check_node_ptr( /*===============*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: index page */ mtr_t* mtr) /*!< in: mtr */ { mem_heap_t* heap; dtuple_t* tuple; ulint* offsets; btr_cur_t cursor; page_t* page = buf_block_get_frame(block); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); if (dict_index_get_page(index) == buf_block_get_page_no(block)) { return(TRUE); } heap = mem_heap_create(256); offsets = btr_page_get_father_block(NULL, heap, index, block, mtr, &cursor); if (page_is_leaf(page)) { goto func_exit; } tuple = dict_index_build_node_ptr( index, page_rec_get_next(page_get_infimum_rec(page)), 0, heap, btr_page_get_level(page, mtr)); ut_a(!cmp_dtuple_rec(tuple, btr_cur_get_rec(&cursor), offsets)); func_exit: mem_heap_free(heap); return(TRUE); } #endif /* UNIV_DEBUG */ /************************************************************//** Display identification information for a record. */ static void btr_index_rec_validate_report( /*==========================*/ const page_t* page, /*!< in: index page */ const rec_t* rec, /*!< in: index record */ const dict_index_t* index) /*!< in: index */ { fputs("InnoDB: Record in ", stderr); dict_index_name_print(stderr, NULL, index); fprintf(stderr, ", page %lu, at offset %lu\n", page_get_page_no(page), (ulint) page_offset(rec)); } /************************************************************//** Checks the size and number of fields in a record based on the definition of the index. @return TRUE if ok */ UNIV_INTERN ibool btr_index_rec_validate( /*===================*/ const rec_t* rec, /*!< in: index record */ const dict_index_t* index, /*!< in: index */ ibool dump_on_error) /*!< in: TRUE if the function should print hex dump of record and page on error */ { ulint len; ulint n; ulint i; const page_t* page; mem_heap_t* heap = NULL; ulint offsets_[REC_OFFS_NORMAL_SIZE]; ulint* offsets = offsets_; rec_offs_init(offsets_); page = page_align(rec); if (dict_index_is_univ(index)) { /* The insert buffer index tree can contain records from any other index: we cannot check the number of fields or their length */ return(TRUE); } if ((ibool)!!page_is_comp(page) != dict_table_is_comp(index->table)) { btr_index_rec_validate_report(page, rec, index); fprintf(stderr, "InnoDB: compact flag=%lu, should be %lu\n", (ulong) !!page_is_comp(page), (ulong) dict_table_is_comp(index->table)); return(FALSE); } n = dict_index_get_n_fields(index); if (!page_is_comp(page) && rec_get_n_fields_old(rec) != n) { btr_index_rec_validate_report(page, rec, index); fprintf(stderr, "InnoDB: has %lu fields, should have %lu\n", (ulong) rec_get_n_fields_old(rec), (ulong) n); if (dump_on_error) { buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: corrupt record ", stderr); rec_print_old(stderr, rec); putc('\n', stderr); } return(FALSE); } offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); for (i = 0; i < n; i++) { ulint fixed_size = dict_col_get_fixed_size( dict_index_get_nth_col(index, i), page_is_comp(page)); rec_get_nth_field_offs(offsets, i, &len); /* Note that if fixed_size != 0, it equals the length of a fixed-size column in the clustered index. A prefix index of the column is of fixed, but different length. When fixed_size == 0, prefix_len is the maximum length of the prefix index column. */ if ((dict_index_get_nth_field(index, i)->prefix_len == 0 && len != UNIV_SQL_NULL && fixed_size && len != fixed_size) || (dict_index_get_nth_field(index, i)->prefix_len > 0 && len != UNIV_SQL_NULL && len > dict_index_get_nth_field(index, i)->prefix_len)) { btr_index_rec_validate_report(page, rec, index); fprintf(stderr, "InnoDB: field %lu len is %lu," " should be %lu\n", (ulong) i, (ulong) len, (ulong) fixed_size); if (dump_on_error) { buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: corrupt record ", stderr); rec_print_new(stderr, rec, offsets); putc('\n', stderr); } if (heap) { mem_heap_free(heap); } return(FALSE); } } if (heap) { mem_heap_free(heap); } return(TRUE); } /************************************************************//** Checks the size and number of fields in records based on the definition of the index. @return TRUE if ok */ static ibool btr_index_page_validate( /*====================*/ buf_block_t* block, /*!< in: index page */ dict_index_t* index) /*!< in: index */ { page_cur_t cur; ibool ret = TRUE; #ifndef DBUG_OFF ulint nth = 1; #endif /* !DBUG_OFF */ page_cur_set_before_first(block, &cur); /* Directory slot 0 should only contain the infimum record. */ DBUG_EXECUTE_IF("check_table_rec_next", ut_a(page_rec_get_nth_const( page_cur_get_page(&cur), 0) == cur.rec); ut_a(page_dir_slot_get_n_owned( page_dir_get_nth_slot( page_cur_get_page(&cur), 0)) == 1);); page_cur_move_to_next(&cur); for (;;) { if (page_cur_is_after_last(&cur)) { break; } if (!btr_index_rec_validate(cur.rec, index, TRUE)) { return(FALSE); } /* Verify that page_rec_get_nth_const() is correctly retrieving each record. */ DBUG_EXECUTE_IF("check_table_rec_next", ut_a(cur.rec == page_rec_get_nth_const( page_cur_get_page(&cur), page_rec_get_n_recs_before( cur.rec))); ut_a(nth++ == page_rec_get_n_recs_before( cur.rec));); page_cur_move_to_next(&cur); } return(ret); } /************************************************************//** Report an error on one page of an index tree. */ static void btr_validate_report1( /*=================*/ dict_index_t* index, /*!< in: index */ ulint level, /*!< in: B-tree level */ const buf_block_t* block) /*!< in: index page */ { fprintf(stderr, "InnoDB: Error in page %lu of ", buf_block_get_page_no(block)); dict_index_name_print(stderr, NULL, index); if (level) { fprintf(stderr, ", index tree level %lu", level); } putc('\n', stderr); } /************************************************************//** Report an error on two pages of an index tree. */ static void btr_validate_report2( /*=================*/ const dict_index_t* index, /*!< in: index */ ulint level, /*!< in: B-tree level */ const buf_block_t* block1, /*!< in: first index page */ const buf_block_t* block2) /*!< in: second index page */ { fprintf(stderr, "InnoDB: Error in pages %lu and %lu of ", buf_block_get_page_no(block1), buf_block_get_page_no(block2)); dict_index_name_print(stderr, NULL, index); if (level) { fprintf(stderr, ", index tree level %lu", level); } putc('\n', stderr); } /************************************************************//** Validates index tree level. @return TRUE if ok */ static bool btr_validate_level( /*===============*/ dict_index_t* index, /*!< in: index tree */ const trx_t* trx, /*!< in: transaction or NULL */ ulint level) /*!< in: level number */ { ulint space; ulint space_flags; ulint zip_size; buf_block_t* block; page_t* page; buf_block_t* right_block = 0; /* remove warning */ page_t* right_page = 0; /* remove warning */ page_t* father_page; btr_cur_t node_cur; btr_cur_t right_node_cur; rec_t* rec; ulint right_page_no; ulint left_page_no; page_cur_t cursor; dtuple_t* node_ptr_tuple; bool ret = true; mtr_t mtr; mem_heap_t* heap = mem_heap_create(256); fseg_header_t* seg; ulint* offsets = NULL; ulint* offsets2= NULL; #ifdef UNIV_ZIP_DEBUG page_zip_des_t* page_zip; #endif /* UNIV_ZIP_DEBUG */ mtr_start(&mtr); mtr_x_lock(dict_index_get_lock(index), &mtr); block = btr_root_block_get(index, RW_X_LATCH, &mtr); page = buf_block_get_frame(block); seg = page + PAGE_HEADER + PAGE_BTR_SEG_TOP; space = dict_index_get_space(index); zip_size = dict_table_zip_size(index->table); fil_space_get_latch(space, &space_flags); if (zip_size != dict_tf_get_zip_size(space_flags)) { ib_logf(IB_LOG_LEVEL_WARN, "Flags mismatch: table=%lu, tablespace=%lu", (ulint) index->table->flags, (ulint) space_flags); mtr_commit(&mtr); return(false); } while (level != btr_page_get_level(page, &mtr)) { const rec_t* node_ptr; if (fseg_page_is_free(seg, block->page.space, block->page.offset)) { btr_validate_report1(index, level, block); ib_logf(IB_LOG_LEVEL_WARN, "page is free"); ret = false; } ut_a(space == buf_block_get_space(block)); ut_a(space == page_get_space_id(page)); #ifdef UNIV_ZIP_DEBUG page_zip = buf_block_get_page_zip(block); ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ ut_a(!page_is_leaf(page)); page_cur_set_before_first(block, &cursor); page_cur_move_to_next(&cursor); node_ptr = page_cur_get_rec(&cursor); offsets = rec_get_offsets(node_ptr, index, offsets, ULINT_UNDEFINED, &heap); block = btr_node_ptr_get_child(node_ptr, index, offsets, &mtr); page = buf_block_get_frame(block); } /* Now we are on the desired level. Loop through the pages on that level. */ if (level == 0) { /* Leaf pages are managed in their own file segment. */ seg -= PAGE_BTR_SEG_TOP - PAGE_BTR_SEG_LEAF; } loop: mem_heap_empty(heap); offsets = offsets2 = NULL; mtr_x_lock(dict_index_get_lock(index), &mtr); #ifdef UNIV_ZIP_DEBUG page_zip = buf_block_get_page_zip(block); ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ ut_a(block->page.space == space); if (fseg_page_is_free(seg, block->page.space, block->page.offset)) { btr_validate_report1(index, level, block); ib_logf(IB_LOG_LEVEL_WARN, "Page is marked as free"); ret = false; } else if (btr_page_get_index_id(page) != index->id) { ib_logf(IB_LOG_LEVEL_ERROR, "Page index id " IB_ID_FMT " != data dictionary " "index id " IB_ID_FMT, btr_page_get_index_id(page), index->id); ret = false; } else if (!page_validate(page, index)) { btr_validate_report1(index, level, block); ret = false; } else if (level == 0 && !btr_index_page_validate(block, index)) { /* We are on level 0. Check that the records have the right number of fields, and field lengths are right. */ ret = false; } ut_a(btr_page_get_level(page, &mtr) == level); right_page_no = btr_page_get_next(page, &mtr); left_page_no = btr_page_get_prev(page, &mtr); ut_a(!page_is_empty(page) || (level == 0 && page_get_page_no(page) == dict_index_get_page(index))); if (right_page_no != FIL_NULL) { const rec_t* right_rec; right_block = btr_block_get(space, zip_size, right_page_no, RW_X_LATCH, index, &mtr); right_page = buf_block_get_frame(right_block); if (btr_page_get_prev(right_page, &mtr) != page_get_page_no(page)) { btr_validate_report2(index, level, block, right_block); fputs("InnoDB: broken FIL_PAGE_NEXT" " or FIL_PAGE_PREV links\n", stderr); buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(right_page, 0, BUF_PAGE_PRINT_NO_CRASH); ret = false; } if (page_is_comp(right_page) != page_is_comp(page)) { btr_validate_report2(index, level, block, right_block); fputs("InnoDB: 'compact' flag mismatch\n", stderr); buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(right_page, 0, BUF_PAGE_PRINT_NO_CRASH); ret = false; goto node_ptr_fails; } rec = page_rec_get_prev(page_get_supremum_rec(page)); right_rec = page_rec_get_next(page_get_infimum_rec( right_page)); offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); offsets2 = rec_get_offsets(right_rec, index, offsets2, ULINT_UNDEFINED, &heap); if (cmp_rec_rec(rec, right_rec, offsets, offsets2, index) >= 0) { btr_validate_report2(index, level, block, right_block); fputs("InnoDB: records in wrong order" " on adjacent pages\n", stderr); buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(right_page, 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: record ", stderr); rec = page_rec_get_prev(page_get_supremum_rec(page)); rec_print(stderr, rec, index); putc('\n', stderr); fputs("InnoDB: record ", stderr); rec = page_rec_get_next( page_get_infimum_rec(right_page)); rec_print(stderr, rec, index); putc('\n', stderr); ret = false; } } if (level > 0 && left_page_no == FIL_NULL) { ut_a(REC_INFO_MIN_REC_FLAG & rec_get_info_bits( page_rec_get_next(page_get_infimum_rec(page)), page_is_comp(page))); } if (buf_block_get_page_no(block) != dict_index_get_page(index)) { /* Check father node pointers */ rec_t* node_ptr; offsets = btr_page_get_father_block(offsets, heap, index, block, &mtr, &node_cur); father_page = btr_cur_get_page(&node_cur); node_ptr = btr_cur_get_rec(&node_cur); btr_cur_position( index, page_rec_get_prev(page_get_supremum_rec(page)), block, &node_cur); offsets = btr_page_get_father_node_ptr(offsets, heap, &node_cur, &mtr); if (node_ptr != btr_cur_get_rec(&node_cur) || btr_node_ptr_get_child_page_no(node_ptr, offsets) != buf_block_get_page_no(block)) { btr_validate_report1(index, level, block); fputs("InnoDB: node pointer to the page is wrong\n", stderr); buf_page_print(father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: node ptr ", stderr); rec_print(stderr, node_ptr, index); rec = btr_cur_get_rec(&node_cur); fprintf(stderr, "\n" "InnoDB: node ptr child page n:o %lu\n", (ulong) btr_node_ptr_get_child_page_no( rec, offsets)); fputs("InnoDB: record on page ", stderr); rec_print_new(stderr, rec, offsets); putc('\n', stderr); ret = false; goto node_ptr_fails; } if (!page_is_leaf(page)) { node_ptr_tuple = dict_index_build_node_ptr( index, page_rec_get_next(page_get_infimum_rec(page)), 0, heap, btr_page_get_level(page, &mtr)); if (cmp_dtuple_rec(node_ptr_tuple, node_ptr, offsets)) { const rec_t* first_rec = page_rec_get_next( page_get_infimum_rec(page)); btr_validate_report1(index, level, block); buf_page_print(father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: Error: node ptrs differ" " on levels > 0\n" "InnoDB: node ptr ", stderr); rec_print_new(stderr, node_ptr, offsets); fputs("InnoDB: first rec ", stderr); rec_print(stderr, first_rec, index); putc('\n', stderr); ret = false; goto node_ptr_fails; } } if (left_page_no == FIL_NULL) { ut_a(node_ptr == page_rec_get_next( page_get_infimum_rec(father_page))); ut_a(btr_page_get_prev(father_page, &mtr) == FIL_NULL); } if (right_page_no == FIL_NULL) { ut_a(node_ptr == page_rec_get_prev( page_get_supremum_rec(father_page))); ut_a(btr_page_get_next(father_page, &mtr) == FIL_NULL); } else { const rec_t* right_node_ptr = page_rec_get_next(node_ptr); offsets = btr_page_get_father_block( offsets, heap, index, right_block, &mtr, &right_node_cur); if (right_node_ptr != page_get_supremum_rec(father_page)) { if (btr_cur_get_rec(&right_node_cur) != right_node_ptr) { ret = false; fputs("InnoDB: node pointer to" " the right page is wrong\n", stderr); btr_validate_report1(index, level, block); buf_page_print( father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( right_page, 0, BUF_PAGE_PRINT_NO_CRASH); } } else { page_t* right_father_page = btr_cur_get_page(&right_node_cur); if (btr_cur_get_rec(&right_node_cur) != page_rec_get_next( page_get_infimum_rec( right_father_page))) { ret = false; fputs("InnoDB: node pointer 2 to" " the right page is wrong\n", stderr); btr_validate_report1(index, level, block); buf_page_print( father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( right_father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( right_page, 0, BUF_PAGE_PRINT_NO_CRASH); } if (page_get_page_no(right_father_page) != btr_page_get_next(father_page, &mtr)) { ret = false; fputs("InnoDB: node pointer 3 to" " the right page is wrong\n", stderr); btr_validate_report1(index, level, block); buf_page_print( father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( right_father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( right_page, 0, BUF_PAGE_PRINT_NO_CRASH); } } } } node_ptr_fails: /* Commit the mini-transaction to release the latch on 'page'. Re-acquire the latch on right_page, which will become 'page' on the next loop. The page has already been checked. */ mtr_commit(&mtr); if (trx_is_interrupted(trx)) { /* On interrupt, return the current status. */ } else if (right_page_no != FIL_NULL) { mtr_start(&mtr); block = btr_block_get( space, zip_size, right_page_no, RW_X_LATCH, index, &mtr); page = buf_block_get_frame(block); goto loop; } mem_heap_free(heap); return(ret); } /**************************************************************//** Checks the consistency of an index tree. @return DB_SUCCESS if ok, error code if not */ UNIV_INTERN dberr_t btr_validate_index( /*===============*/ dict_index_t* index, /*!< in: index */ const trx_t* trx) /*!< in: transaction or NULL */ { dberr_t err = DB_SUCCESS; /* Full Text index are implemented by auxiliary tables, not the B-tree */ if (dict_index_is_online_ddl(index) || (index->type & DICT_FTS)) { return(err); } mtr_t mtr; mtr_start(&mtr); mtr_x_lock(dict_index_get_lock(index), &mtr); page_t* root = btr_root_get(index, &mtr); if (root == NULL && index->table->is_encrypted) { err = DB_DECRYPTION_FAILED; mtr_commit(&mtr); return err; } ulint n = btr_page_get_level(root, &mtr); for (ulint i = 0; i <= n; ++i) { if (!btr_validate_level(index, trx, n - i)) { err = DB_CORRUPTION; break; } } mtr_commit(&mtr); return(err); } /**************************************************************//** Checks if the page in the cursor can be merged with given page. If necessary, re-organize the merge_page. @return TRUE if possible to merge. */ UNIV_INTERN ibool btr_can_merge_with_page( /*====================*/ btr_cur_t* cursor, /*!< in: cursor on the page to merge */ ulint page_no, /*!< in: a sibling page */ buf_block_t** merge_block, /*!< out: the merge block */ mtr_t* mtr) /*!< in: mini-transaction */ { dict_index_t* index; page_t* page; ulint space; ulint zip_size; ulint n_recs; ulint data_size; ulint max_ins_size_reorg; ulint max_ins_size; buf_block_t* mblock; page_t* mpage; DBUG_ENTER("btr_can_merge_with_page"); if (page_no == FIL_NULL) { goto error; } index = btr_cur_get_index(cursor); page = btr_cur_get_page(cursor); space = dict_index_get_space(index); zip_size = dict_table_zip_size(index->table); mblock = btr_block_get(space, zip_size, page_no, RW_X_LATCH, index, mtr); mpage = buf_block_get_frame(mblock); n_recs = page_get_n_recs(page); data_size = page_get_data_size(page); max_ins_size_reorg = page_get_max_insert_size_after_reorganize( mpage, n_recs); if (data_size > max_ins_size_reorg) { goto error; } /* If compression padding tells us that merging will result in too packed up page i.e.: which is likely to cause compression failure then don't merge the pages. */ if (zip_size && page_is_leaf(mpage) && (page_get_data_size(mpage) + data_size >= dict_index_zip_pad_optimal_page_size(index))) { goto error; } max_ins_size = page_get_max_insert_size(mpage, n_recs); if (data_size > max_ins_size) { /* We have to reorganize mpage */ if (!btr_page_reorganize_block( false, page_zip_level, mblock, index, mtr)) { goto error; } max_ins_size = page_get_max_insert_size(mpage, n_recs); ut_ad(page_validate(mpage, index)); ut_ad(max_ins_size == max_ins_size_reorg); if (data_size > max_ins_size) { /* Add fault tolerance, though this should never happen */ goto error; } } *merge_block = mblock; DBUG_RETURN(TRUE); error: *merge_block = NULL; DBUG_RETURN(FALSE); } #endif /* !UNIV_HOTBACKUP */
prohaska7/mariadb-server
storage/innobase/btr/btr0btr.cc
C++
gpl-2.0
151,788
// ========================================================== // fipImage class implementation // // Design and implementation by // - Hervé Drolon (drolon@infonie.fr) // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== #include "FreeImagePlus.h" /////////////////////////////////////////////////////////////////// // Protected functions BOOL fipImage::replace(FIBITMAP *new_dib) { if(new_dib == NULL) return FALSE; if(_dib) FreeImage_Unload(_dib); _dib = new_dib; _bHasChanged = TRUE; return TRUE; } /////////////////////////////////////////////////////////////////// // Creation & Destruction fipImage::fipImage(FREE_IMAGE_TYPE image_type, WORD width, WORD height, WORD bpp) { _dib = NULL; _bHasChanged = FALSE; if(width && height && bpp) setSize(image_type, width, height, bpp); } fipImage::~fipImage() { if(_dib) { FreeImage_Unload(_dib); _dib = NULL; } } BOOL fipImage::setSize(FREE_IMAGE_TYPE image_type, WORD width, WORD height, WORD bpp, unsigned red_mask, unsigned green_mask, unsigned blue_mask) { if(_dib) { FreeImage_Unload(_dib); } if((_dib = FreeImage_AllocateT(image_type, width, height, bpp, red_mask, green_mask, blue_mask)) == NULL) return FALSE; if(image_type == FIT_BITMAP) { // Create palette if needed switch(bpp) { case 1: case 4: case 8: RGBQUAD *pal = FreeImage_GetPalette(_dib); for(unsigned i = 0; i < FreeImage_GetColorsUsed(_dib); i++) { pal[i].rgbRed = i; pal[i].rgbGreen = i; pal[i].rgbBlue = i; } break; } } _bHasChanged = TRUE; return TRUE; } void fipImage::clear() { if(_dib) { FreeImage_Unload(_dib); _dib = NULL; } _bHasChanged = TRUE; } /////////////////////////////////////////////////////////////////// // Copying fipImage::fipImage(const fipImage& Image) { _dib = NULL; _fif = FIF_UNKNOWN; FIBITMAP *clone = FreeImage_Clone((FIBITMAP*)Image._dib); replace(clone); } fipImage& fipImage::operator=(const fipImage& Image) { if(this != &Image) { FIBITMAP *clone = FreeImage_Clone((FIBITMAP*)Image._dib); replace(clone); } return *this; } fipImage& fipImage::operator=(FIBITMAP *dib) { if(_dib != dib) { replace(dib); } return *this; } BOOL fipImage::copySubImage(fipImage& dst, int left, int top, int right, int bottom) const { if(_dib) { dst = FreeImage_Copy(_dib, left, top, right, bottom); return dst.isValid(); } return FALSE; } BOOL fipImage::pasteSubImage(fipImage& src, int left, int top, int alpha) { if(_dib) { BOOL bResult = FreeImage_Paste(_dib, src._dib, left, top, alpha); _bHasChanged = TRUE; return bResult; } return FALSE; } BOOL fipImage::crop(int left, int top, int right, int bottom) { if(_dib) { FIBITMAP *dst = FreeImage_Copy(_dib, left, top, right, bottom); return replace(dst); } return FALSE; } /////////////////////////////////////////////////////////////////// // Information functions FREE_IMAGE_TYPE fipImage::getImageType() const { return FreeImage_GetImageType(_dib); } WORD fipImage::getWidth() const { return FreeImage_GetWidth(_dib); } WORD fipImage::getHeight() const { return FreeImage_GetHeight(_dib); } WORD fipImage::getScanWidth() const { return FreeImage_GetPitch(_dib); } BOOL fipImage::isValid() const { return (_dib != NULL) ? TRUE:FALSE; } BITMAPINFO* fipImage::getInfo() const { return FreeImage_GetInfo(_dib); } BITMAPINFOHEADER* fipImage::getInfoHeader() const { return FreeImage_GetInfoHeader(_dib); } LONG fipImage::getImageSize() const { return FreeImage_GetDIBSize(_dib); } WORD fipImage::getBitsPerPixel() const { return FreeImage_GetBPP(_dib); } WORD fipImage::getLine() const { return FreeImage_GetLine(_dib); } double fipImage::getHorizontalResolution() const { return (FreeImage_GetDotsPerMeterX(_dib) / (double)100); } double fipImage::getVerticalResolution() const { return (FreeImage_GetDotsPerMeterY(_dib) / (double)100); } void fipImage::setHorizontalResolution(double value) { FreeImage_SetDotsPerMeterX(_dib, (unsigned)(value * 100 + 0.5)); } void fipImage::setVerticalResolution(double value) { FreeImage_SetDotsPerMeterY(_dib, (unsigned)(value * 100 + 0.5)); } /////////////////////////////////////////////////////////////////// // Palette operations RGBQUAD* fipImage::getPalette() const { return FreeImage_GetPalette(_dib); } WORD fipImage::getPaletteSize() const { return FreeImage_GetColorsUsed(_dib) * sizeof(RGBQUAD); } WORD fipImage::getColorsUsed() const { return FreeImage_GetColorsUsed(_dib); } FREE_IMAGE_COLOR_TYPE fipImage::getColorType() const { return FreeImage_GetColorType(_dib); } BOOL fipImage::isGrayscale() const { return ((FreeImage_GetBPP(_dib) == 8) && (FreeImage_GetColorType(_dib) != FIC_PALETTE)); } /////////////////////////////////////////////////////////////////// // Pixel access BYTE* fipImage::accessPixels() const { return FreeImage_GetBits(_dib); } BYTE* fipImage::getScanLine(WORD scanline) const { if(scanline < FreeImage_GetHeight(_dib)) { return FreeImage_GetScanLine(_dib, scanline); } return NULL; } BOOL fipImage::getPixelIndex(unsigned x, unsigned y, BYTE *value) const { return FreeImage_GetPixelIndex(_dib, x, y, value); } BOOL fipImage::getPixelColor(unsigned x, unsigned y, RGBQUAD *value) const { return FreeImage_GetPixelColor(_dib, x, y, value); } BOOL fipImage::setPixelIndex(unsigned x, unsigned y, BYTE *value) { _bHasChanged = TRUE; return FreeImage_SetPixelIndex(_dib, x, y, value); } BOOL fipImage::setPixelColor(unsigned x, unsigned y, RGBQUAD *value) { _bHasChanged = TRUE; return FreeImage_SetPixelColor(_dib, x, y, value); } /////////////////////////////////////////////////////////////////// // File type identification FREE_IMAGE_FORMAT fipImage::identifyFIF(const char* lpszPathName) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format // (the second argument is currently not used by FreeImage) fif = FreeImage_GetFileType(lpszPathName, 0); if(fif == FIF_UNKNOWN) { // no signature ? // try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilename(lpszPathName); } return fif; } FREE_IMAGE_FORMAT fipImage::identifyFIFU(const wchar_t* lpszPathName) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format // (the second argument is currently not used by FreeImage) fif = FreeImage_GetFileTypeU(lpszPathName, 0); if(fif == FIF_UNKNOWN) { // no signature ? // try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilenameU(lpszPathName); } return fif; } FREE_IMAGE_FORMAT fipImage::identifyFIFFromHandle(FreeImageIO *io, fi_handle handle) { if(io && handle) { // check the file signature and get its format return FreeImage_GetFileTypeFromHandle(io, handle, 16); } return FIF_UNKNOWN; } FREE_IMAGE_FORMAT fipImage::identifyFIFFromMemory(FIMEMORY *hmem) { if(hmem != NULL) { return FreeImage_GetFileTypeFromMemory(hmem, 0); } return FIF_UNKNOWN; } /////////////////////////////////////////////////////////////////// // Loading & Saving BOOL fipImage::load(const char* lpszPathName, int flag) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format // (the second argument is currently not used by FreeImage) fif = FreeImage_GetFileType(lpszPathName, 0); if(fif == FIF_UNKNOWN) { // no signature ? // try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilename(lpszPathName); } // check that the plugin has reading capabilities ... if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) { // Free the previous dib if(_dib) { FreeImage_Unload(_dib); } // Load the file _dib = FreeImage_Load(fif, lpszPathName, flag); _bHasChanged = TRUE; if(_dib == NULL) return FALSE; return TRUE; } return FALSE; } BOOL fipImage::loadU(const wchar_t* lpszPathName, int flag) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format // (the second argument is currently not used by FreeImage) fif = FreeImage_GetFileTypeU(lpszPathName, 0); if(fif == FIF_UNKNOWN) { // no signature ? // try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilenameU(lpszPathName); } // check that the plugin has reading capabilities ... if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) { // Free the previous dib if(_dib) { FreeImage_Unload(_dib); } // Load the file _dib = FreeImage_LoadU(fif, lpszPathName, flag); _bHasChanged = TRUE; if(_dib == NULL) return FALSE; return TRUE; } return FALSE; } BOOL fipImage::loadFromHandle(FreeImageIO *io, fi_handle handle, int flag) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format fif = FreeImage_GetFileTypeFromHandle(io, handle, 16); if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) { // Free the previous dib if(_dib) { FreeImage_Unload(_dib); } // Load the file _dib = FreeImage_LoadFromHandle(fif, io, handle, flag); _bHasChanged = TRUE; if(_dib == NULL) return FALSE; return TRUE; } return FALSE; } BOOL fipImage::loadFromMemory(fipMemoryIO& memIO, int flag) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format fif = memIO.getFileType(); if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) { // Free the previous dib if(_dib) { FreeImage_Unload(_dib); } // Load the file _dib = memIO.load(fif, flag); _bHasChanged = TRUE; if(_dib == NULL) return FALSE; return TRUE; } return FALSE; } BOOL fipImage::save(const char* lpszPathName, int flag) const { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; BOOL bSuccess = FALSE; // Try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilename(lpszPathName); if(fif != FIF_UNKNOWN ) { // Check that the dib can be saved in this format BOOL bCanSave; FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(_dib); if(image_type == FIT_BITMAP) { // standard bitmap type WORD bpp = FreeImage_GetBPP(_dib); bCanSave = (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)); } else { // special bitmap type bCanSave = FreeImage_FIFSupportsExportType(fif, image_type); } if(bCanSave) { bSuccess = FreeImage_Save(fif, _dib, lpszPathName, flag); return bSuccess; } } return bSuccess; } BOOL fipImage::saveU(const wchar_t* lpszPathName, int flag) const { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; BOOL bSuccess = FALSE; // Try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilenameU(lpszPathName); if(fif != FIF_UNKNOWN ) { // Check that the dib can be saved in this format BOOL bCanSave; FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(_dib); if(image_type == FIT_BITMAP) { // standard bitmap type WORD bpp = FreeImage_GetBPP(_dib); bCanSave = (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)); } else { // special bitmap type bCanSave = FreeImage_FIFSupportsExportType(fif, image_type); } if(bCanSave) { bSuccess = FreeImage_SaveU(fif, _dib, lpszPathName, flag); return bSuccess; } } return bSuccess; } BOOL fipImage::saveToHandle(FREE_IMAGE_FORMAT fif, FreeImageIO *io, fi_handle handle, int flag) const { BOOL bSuccess = FALSE; if(fif != FIF_UNKNOWN ) { // Check that the dib can be saved in this format BOOL bCanSave; FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(_dib); if(image_type == FIT_BITMAP) { // standard bitmap type WORD bpp = FreeImage_GetBPP(_dib); bCanSave = (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)); } else { // special bitmap type bCanSave = FreeImage_FIFSupportsExportType(fif, image_type); } if(bCanSave) { bSuccess = FreeImage_SaveToHandle(fif, _dib, io, handle, flag); return bSuccess; } } return bSuccess; } BOOL fipImage::saveToMemory(FREE_IMAGE_FORMAT fif, fipMemoryIO& memIO, int flag) const { BOOL bSuccess = FALSE; if(fif != FIF_UNKNOWN ) { // Check that the dib can be saved in this format BOOL bCanSave; FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(_dib); if(image_type == FIT_BITMAP) { // standard bitmap type WORD bpp = FreeImage_GetBPP(_dib); bCanSave = (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)); } else { // special bitmap type bCanSave = FreeImage_FIFSupportsExportType(fif, image_type); } if(bCanSave) { bSuccess = memIO.save(fif, _dib, flag); return bSuccess; } } return bSuccess; } /////////////////////////////////////////////////////////////////// // Conversion routines BOOL fipImage::convertToType(FREE_IMAGE_TYPE image_type, BOOL scale_linear) { if(_dib) { FIBITMAP *dib = FreeImage_ConvertToType(_dib, image_type, scale_linear); return replace(dib); } return FALSE; } BOOL fipImage::threshold(BYTE T) { if(_dib) { FIBITMAP *dib1 = FreeImage_Threshold(_dib, T); return replace(dib1); } return FALSE; } BOOL fipImage::convertTo4Bits() { if(_dib) { FIBITMAP *dib4 = FreeImage_ConvertTo4Bits(_dib); return replace(dib4); } return FALSE; } BOOL fipImage::convertTo8Bits() { if(_dib) { FIBITMAP *dib8 = FreeImage_ConvertTo8Bits(_dib); return replace(dib8); } return FALSE; } BOOL fipImage::convertTo16Bits555() { if(_dib) { FIBITMAP *dib16_555 = FreeImage_ConvertTo16Bits555(_dib); return replace(dib16_555); } return FALSE; } BOOL fipImage::convertTo16Bits565() { if(_dib) { FIBITMAP *dib16_565 = FreeImage_ConvertTo16Bits565(_dib); return replace(dib16_565); } return FALSE; } BOOL fipImage::convertTo24Bits() { if(_dib) { FIBITMAP *dibRGB = FreeImage_ConvertTo24Bits(_dib); return replace(dibRGB); } return FALSE; } BOOL fipImage::convertTo32Bits() { if(_dib) { FIBITMAP *dib32 = FreeImage_ConvertTo32Bits(_dib); return replace(dib32); } return FALSE; } BOOL fipImage::convertToGrayscale() { if(_dib) { FIBITMAP *dib8 = FreeImage_ConvertToGreyscale(_dib); return replace(dib8); } return FALSE; } BOOL fipImage::colorQuantize(FREE_IMAGE_QUANTIZE algorithm) { if(_dib) { FIBITMAP *dib8 = FreeImage_ColorQuantize(_dib, algorithm); return replace(dib8); } return FALSE; } BOOL fipImage::dither(FREE_IMAGE_DITHER algorithm) { if(_dib) { FIBITMAP *dib = FreeImage_Dither(_dib, algorithm); return replace(dib); } return FALSE; } BOOL fipImage::convertToRGBF() { if(_dib) { FIBITMAP *dib = FreeImage_ConvertToRGBF(_dib); return replace(dib); } return FALSE; } BOOL fipImage::toneMapping(FREE_IMAGE_TMO tmo, double first_param, double second_param, double third_param, double fourth_param) { if(_dib) { FIBITMAP *dst = NULL; // Apply a tone mapping algorithm and convert to 24-bit switch(tmo) { case FITMO_REINHARD05: dst = FreeImage_TmoReinhard05Ex(_dib, first_param, second_param, third_param, fourth_param); break; default: dst = FreeImage_ToneMapping(_dib, tmo, first_param, second_param); break; } return replace(dst); } return FALSE; } /////////////////////////////////////////////////////////////////// // Transparency support: background colour and alpha channel BOOL fipImage::isTransparent() const { return FreeImage_IsTransparent(_dib); } unsigned fipImage::getTransparencyCount() const { return FreeImage_GetTransparencyCount(_dib); } BYTE* fipImage::getTransparencyTable() const { return FreeImage_GetTransparencyTable(_dib); } void fipImage::setTransparencyTable(BYTE *table, int count) { FreeImage_SetTransparencyTable(_dib, table, count); _bHasChanged = TRUE; } BOOL fipImage::hasFileBkColor() const { return FreeImage_HasBackgroundColor(_dib); } BOOL fipImage::getFileBkColor(RGBQUAD *bkcolor) const { return FreeImage_GetBackgroundColor(_dib, bkcolor); } BOOL fipImage::setFileBkColor(RGBQUAD *bkcolor) { _bHasChanged = TRUE; return FreeImage_SetBackgroundColor(_dib, bkcolor); } /////////////////////////////////////////////////////////////////// // Channel processing support BOOL fipImage::getChannel(fipImage& image, FREE_IMAGE_COLOR_CHANNEL channel) const { if(_dib) { image = FreeImage_GetChannel(_dib, channel); return image.isValid(); } return FALSE; } BOOL fipImage::setChannel(fipImage& image, FREE_IMAGE_COLOR_CHANNEL channel) { if(_dib) { _bHasChanged = TRUE; return FreeImage_SetChannel(_dib, image._dib, channel); } return FALSE; } BOOL fipImage::splitChannels(fipImage& RedChannel, fipImage& GreenChannel, fipImage& BlueChannel) { if(_dib) { RedChannel = FreeImage_GetChannel(_dib, FICC_RED); GreenChannel = FreeImage_GetChannel(_dib, FICC_GREEN); BlueChannel = FreeImage_GetChannel(_dib, FICC_BLUE); return (RedChannel.isValid() && GreenChannel.isValid() && BlueChannel.isValid()); } return FALSE; } BOOL fipImage::combineChannels(fipImage& red, fipImage& green, fipImage& blue) { if(!_dib) { int width = red.getWidth(); int height = red.getHeight(); _dib = FreeImage_Allocate(width, height, 24, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK); } if(_dib) { BOOL bResult = TRUE; bResult &= FreeImage_SetChannel(_dib, red._dib, FICC_RED); bResult &= FreeImage_SetChannel(_dib, green._dib, FICC_GREEN); bResult &= FreeImage_SetChannel(_dib, blue._dib, FICC_BLUE); _bHasChanged = TRUE; return bResult; } return FALSE; } /////////////////////////////////////////////////////////////////// // Rotation and flipping BOOL fipImage::rotateEx(double angle, double x_shift, double y_shift, double x_origin, double y_origin, BOOL use_mask) { if(_dib) { if(FreeImage_GetBPP(_dib) >= 8) { FIBITMAP *rotated = FreeImage_RotateEx(_dib, angle, x_shift, y_shift, x_origin, y_origin, use_mask); return replace(rotated); } } return FALSE; } BOOL fipImage::rotate(double angle, const void *bkcolor) { if(_dib) { switch(FreeImage_GetImageType(_dib)) { case FIT_BITMAP: switch(FreeImage_GetBPP(_dib)) { case 1: case 8: case 24: case 32: break; default: return FALSE; } break; case FIT_UINT16: case FIT_RGB16: case FIT_RGBA16: case FIT_FLOAT: case FIT_RGBF: case FIT_RGBAF: break; default: return FALSE; break; } FIBITMAP *rotated = FreeImage_Rotate(_dib, angle, bkcolor); return replace(rotated); } return FALSE; } BOOL fipImage::flipVertical() { if(_dib) { _bHasChanged = TRUE; return FreeImage_FlipVertical(_dib); } return FALSE; } BOOL fipImage::flipHorizontal() { if(_dib) { _bHasChanged = TRUE; return FreeImage_FlipHorizontal(_dib); } return FALSE; } /////////////////////////////////////////////////////////////////// // Color manipulation routines BOOL fipImage::invert() { if(_dib) { _bHasChanged = TRUE; return FreeImage_Invert(_dib); } return FALSE; } BOOL fipImage::adjustCurve(BYTE *LUT, FREE_IMAGE_COLOR_CHANNEL channel) { if(_dib) { _bHasChanged = TRUE; return FreeImage_AdjustCurve(_dib, LUT, channel); } return FALSE; } BOOL fipImage::adjustGamma(double gamma) { if(_dib) { _bHasChanged = TRUE; return FreeImage_AdjustGamma(_dib, gamma); } return FALSE; } BOOL fipImage::adjustBrightness(double percentage) { if(_dib) { _bHasChanged = TRUE; return FreeImage_AdjustBrightness(_dib, percentage); } return FALSE; } BOOL fipImage::adjustContrast(double percentage) { if(_dib) { _bHasChanged = TRUE; return FreeImage_AdjustContrast(_dib, percentage); } return FALSE; } BOOL fipImage::adjustBrightnessContrastGamma(double brightness, double contrast, double gamma) { if(_dib) { _bHasChanged = TRUE; return FreeImage_AdjustColors(_dib, brightness, contrast, gamma, FALSE); } return FALSE; } BOOL fipImage::getHistogram(DWORD *histo, FREE_IMAGE_COLOR_CHANNEL channel) const { if(_dib) { return FreeImage_GetHistogram(_dib, histo, channel); } return FALSE; } /////////////////////////////////////////////////////////////////// // Upsampling / downsampling routine BOOL fipImage::rescale(WORD new_width, WORD new_height, FREE_IMAGE_FILTER filter) { if(_dib) { switch(FreeImage_GetImageType(_dib)) { case FIT_BITMAP: case FIT_UINT16: case FIT_RGB16: case FIT_RGBA16: case FIT_FLOAT: case FIT_RGBF: case FIT_RGBAF: break; default: return FALSE; break; } // Perform upsampling / downsampling FIBITMAP *dst = FreeImage_Rescale(_dib, new_width, new_height, filter); return replace(dst); } return FALSE; } BOOL fipImage::makeThumbnail(WORD max_size, BOOL convert) { if(_dib) { switch(FreeImage_GetImageType(_dib)) { case FIT_BITMAP: case FIT_UINT16: case FIT_RGB16: case FIT_RGBA16: case FIT_FLOAT: case FIT_RGBF: case FIT_RGBAF: break; default: return FALSE; break; } // Perform downsampling FIBITMAP *dst = FreeImage_MakeThumbnail(_dib, max_size, convert); return replace(dst); } return FALSE; } /////////////////////////////////////////////////////////////////// // Metadata unsigned fipImage::getMetadataCount(FREE_IMAGE_MDMODEL model) const { return FreeImage_GetMetadataCount(model, _dib); } BOOL fipImage::getMetadata(FREE_IMAGE_MDMODEL model, const char *key, fipTag& tag) const { FITAG *searchedTag = NULL; FreeImage_GetMetadata(model, _dib, key, &searchedTag); if(searchedTag != NULL) { tag = FreeImage_CloneTag(searchedTag); return TRUE; } else { // clear the tag tag = (FITAG*)NULL; } return FALSE; } BOOL fipImage::setMetadata(FREE_IMAGE_MDMODEL model, const char *key, fipTag& tag) { return FreeImage_SetMetadata(model, _dib, key, tag); }
bhargavkumar040/android-source-browsing.platform--external--free-image
Wrapper/FreeImagePlus/src/fipImage.cpp
C++
gpl-2.0
22,480
<?php /** * @package Warp Theme Framework * @author YOOtheme http://www.yootheme.com * @copyright Copyright (C) YOOtheme GmbH * @license http://www.gnu.org/licenses/gpl.html GNU/GPL */ defined('_JEXEC') or die; JHtml::_('behavior.framework'); JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html'); JHtml::stylesheet('com_finder/finder.css', false, true, false); ?> <div id="system"> <?php if ($this->params->get('show_page_heading', 1)) : ?> <h1 class="title"> <?php if ($this->escape($this->params->get('page_heading'))) : ?> <?php echo $this->escape($this->params->get('page_heading')); ?> <?php else : ?> <?php echo $this->escape($this->params->get('page_title')); ?> <?php endif; ?> </h1> <?php endif; ?> <?php if ($this->params->get('show_search_form', 1)) { echo $this->loadTemplate('form'); } ?> <?php if ($this->query->search === true) { echo $this->loadTemplate('results'); } ?> </div>
valodya-street/workroom
templates/yoo_sphere/warp/systems/joomla/layouts/com_finder/search/default.php
PHP
gpl-2.0
947
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Bundle * @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /* @var $installer Mage_Catalog_Model_Resource_Eav_Mysql4_Setup */ $installer = $this; $installer->run(" CREATE TABLE {$this->getTable('bundle/selection_price')} ( `selection_id` int(10) unsigned NOT NULL, `website_id` smallint(5) unsigned NOT NULL, `selection_price_type` tinyint(1) unsigned NOT NULL default '0', `selection_price_value` decimal(12,4) NOT NULL default '0.0000', PRIMARY KEY (`selection_id`, `website_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; "); $installer->getConnection()->addConstraint( 'FK_BUNDLE_PRICE_SELECTION_ID', $this->getTable('bundle/selection_price'), 'selection_id', $this->getTable('bundle/selection'), 'selection_id' ); $installer->getConnection()->addConstraint( 'FK_BUNDLE_PRICE_SELECTION_WEBSITE', $this->getTable('bundle/selection_price'), 'website_id', $this->getTable('core_website'), 'website_id' );
T0MM0R/magento
web/app/code/core/Mage/Bundle/sql/bundle_setup/mysql4-upgrade-0.1.12-0.1.13.php
PHP
gpl-2.0
1,852
/* * Copyright (C) 2013 Google 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. */ #if UNITY_ANDROID using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using GooglePlayGames.BasicApi; using GooglePlayGames.OurUtils; using GooglePlayGames.BasicApi.Multiplayer; namespace GooglePlayGames.Android { internal class AndroidRtmpClient : IRealTimeMultiplayerClient { AndroidClient mClient = null; AndroidJavaObject mRoom = null; RealTimeMultiplayerListener mRtmpListener = null; // whether rtmp is currently active (this becomes true when we begin setup, and // remains true while the room is active; when we leave the room, this goes back to // false. bool mRtmpActive = false; // whether we are invoking an external UI (which might cause us to get stopped) // we must know this because we will know to keep the reference to the Rtmp Listener // so that when we come back from that UI, we can continue the room setup bool mLaunchedExternalActivity = false; // whether we delivered OnRoomConnected callback; amongst other things, this // means that we also have to deliver the OnLeftRoom callback when leaving the room bool mDeliveredRoomConnected = false; // whether we have a pending request to leave the room (this will happen if the // developer calls LeaveRoom() when we are in a state where we can't service that // request immediately) bool mLeaveRoomRequested = false; // variant requested, 0 for ANY int mVariant = 0; // we use this lock when we access the lists of participants, or mSelf, // from either the UI thread or the game thread. object mParticipantListsLock = new object(); List<Participant> mConnectedParticipants = new List<Participant>(); List<Participant> mAllParticipants = new List<Participant>(); Participant mSelf = null; // accumulated "approximate progress" of the room setup process float mAccumulatedProgress = 0.0f; float mLastReportedProgress = 0.0f; public AndroidRtmpClient(AndroidClient client) { mClient = client; } // called from game thread public void CreateQuickGame(int minOpponents, int maxOpponents, int variant, RealTimeMultiplayerListener listener) { Logger.d(string.Format("AndroidRtmpClient.CreateQuickGame, opponents={0}-{1}, " + "variant={2}", minOpponents, maxOpponents, variant)); if (!PrepareToCreateRoom("CreateQuickGame", listener)) { return; } mRtmpListener = listener; mVariant = variant; mClient.CallClientApi("rtmp create quick game", () => { AndroidJavaClass rtmpUtil = JavaUtil.GetClass(JavaConsts.SupportRtmpUtilsClass); rtmpUtil.CallStatic("createQuickGame", mClient.GHManager.GetApiClient(), minOpponents, maxOpponents, variant, new RoomUpdateProxy(this), new RoomStatusUpdateProxy(this), new RealTimeMessageReceivedProxy(this)); }, (bool success) => { if (!success) { FailRoomSetup("Failed to create game because GoogleApiClient was disconnected"); } }); } // called from game thread public void CreateWithInvitationScreen(int minOpponents, int maxOpponents, int variant, RealTimeMultiplayerListener listener) { Logger.d(string.Format("AndroidRtmpClient.CreateWithInvitationScreen, " + "opponents={0}-{1}, variant={2}", minOpponents, maxOpponents, variant)); if (!PrepareToCreateRoom("CreateWithInvitationScreen", listener)) { return; } mRtmpListener = listener; mVariant = variant; mClient.CallClientApi("rtmp create with invitation screen", () => { AndroidJavaClass klass = JavaUtil.GetClass( JavaConsts.SupportSelectOpponentsHelperActivity); mLaunchedExternalActivity = true; klass.CallStatic("launch", true, mClient.GetActivity(), new SelectOpponentsProxy(this), Logger.DebugLogEnabled, minOpponents, maxOpponents); }, (bool success) => { if (!success) { FailRoomSetup("Failed to create game because GoogleApiClient was disconnected"); } }); } // called from game thread public void AcceptFromInbox(RealTimeMultiplayerListener listener) { Logger.d("AndroidRtmpClient.AcceptFromInbox."); if (!PrepareToCreateRoom("AcceptFromInbox", listener)) { return; } mRtmpListener = listener; mClient.CallClientApi("rtmp accept with inbox screen", () => { AndroidJavaClass klass = JavaUtil.GetClass( JavaConsts.SupportInvitationInboxHelperActivity); mLaunchedExternalActivity = true; klass.CallStatic("launch", true, mClient.GetActivity(), new InvitationInboxProxy(this), Logger.DebugLogEnabled); }, (bool success) => { if (!success) { FailRoomSetup("Failed to accept from inbox because GoogleApiClient was disconnected"); } }); } // called from the game thread public void AcceptInvitation(string invitationId, RealTimeMultiplayerListener listener) { Logger.d("AndroidRtmpClient.AcceptInvitation " + invitationId); if (!PrepareToCreateRoom("AcceptInvitation", listener)) { return; } mRtmpListener = listener; mClient.ClearInvitationIfFromNotification(invitationId); mClient.CallClientApi("rtmp accept invitation", () => { Logger.d("Accepting invite via support lib."); AndroidJavaClass rtmpUtil = JavaUtil.GetClass(JavaConsts.SupportRtmpUtilsClass); rtmpUtil.CallStatic("accept", mClient.GHManager.GetApiClient(), invitationId, new RoomUpdateProxy(this), new RoomStatusUpdateProxy(this), new RealTimeMessageReceivedProxy(this)); }, (bool success) => { if (!success) { FailRoomSetup("Failed to accept invitation because GoogleApiClient was disconnected"); } }); } // called from game thread public void SendMessage(bool reliable, string participantId, byte[] data) { SendMessage(reliable, participantId, data, 0, data.Length); } // called from game thread public void SendMessageToAll(bool reliable, byte[] data) { SendMessage(reliable, null, data, 0, data.Length); } // called from game thread public void SendMessageToAll(bool reliable, byte[] data, int offset, int length) { SendMessage(reliable, null, data, offset, length); } // called from game thread public void SendMessage(bool reliable, string participantId, byte[] data, int offset, int length) { Logger.d(string.Format("AndroidRtmpClient.SendMessage, reliable={0}, " + "participantId={1}, data[]={2} bytes, offset={3}, length={4}", reliable, participantId, data.Length, offset, length)); if (!CheckConnectedRoom("SendMessage")) { return; } if (mSelf != null && mSelf.ParticipantId.Equals(participantId)) { Logger.d("Ignoring request to send message to self, " + participantId); return; } // Since we don't yet have API support for buffer/offset/length, convert // to a regular byte[] buffer: byte[] dataToSend = Misc.GetSubsetBytes(data, offset, length); if (participantId == null) { // this means "send to all" List<Participant> participants = GetConnectedParticipants(); foreach (Participant p in participants) { if (p.ParticipantId != null && !p.Equals(mSelf)) { SendMessage(reliable, p.ParticipantId, dataToSend, 0, dataToSend.Length); } } return; } mClient.CallClientApi("send message to " + participantId, () => { if (mRoom != null) { string roomId = mRoom.Call<string>("getRoomId"); if (reliable) { mClient.GHManager.CallGmsApi<int>("games.Games", "RealTimeMultiplayer", "sendReliableMessage", null, dataToSend, roomId, participantId); } else { mClient.GHManager.CallGmsApi<int>("games.Games", "RealTimeMultiplayer", "sendUnreliableMessage", dataToSend, roomId, participantId); } } else { Logger.w("Not sending message because real-time room was torn down."); } }, null); } // called from game thread public List<Participant> GetConnectedParticipants() { Logger.d("AndroidRtmpClient.GetConnectedParticipants"); if (!CheckConnectedRoom("GetConnectedParticipants")) { return null; } List<Participant> participants; // lock it because this list is assigned to by the UI thread lock (mParticipantListsLock) { participants = mConnectedParticipants; } // Note: it's fine to return a reference to our internal list, because // we use it as an immutable list. When we get an update, we create a new list to // replace it. So the caller may just as well hold on to our copy. return participants; } // called from game thread public Participant GetParticipant(string id) { Logger.d("AndroidRtmpClient.GetParticipant: " + id); if (!CheckConnectedRoom("GetParticipant")) { return null; } List<Participant> allParticipants; lock (mParticipantListsLock) { allParticipants = mAllParticipants; } if (allParticipants == null) { Logger.e("RtmpGetParticipant called without a valid room!"); return null; } foreach (Participant p in allParticipants) { if (p.ParticipantId.Equals(id)) { return p; } } Logger.e("Participant not found in room! id: " + id); return null; } // called from game thread public Participant GetSelf() { Logger.d("AndroidRtmpClient.GetSelf"); if (!CheckConnectedRoom("GetSelf")) { return null; } Participant self; lock (mParticipantListsLock) { self = mSelf; } if (self == null) { Logger.e("Call to RtmpGetSelf() can only be made when in a room. Returning null."); } return self; } // called from game thread public void LeaveRoom() { Logger.d("AndroidRtmpClient.LeaveRoom"); // if we are setting up a room but haven't got the room yet, we can't // leave the room now, we have to defer it to a later time when we have the room if (mRtmpActive && mRoom == null) { Logger.w("AndroidRtmpClient.LeaveRoom: waiting for room; deferring leave request."); mLeaveRoomRequested = true; } else { mClient.CallClientApi("leave room", () => { Clear("LeaveRoom called"); }, null); } } // called from UI thread, on onStop public void OnStop() { // if we launched an external activity (like the "select opponents" UI) as part of // the process, we should NOT clear our RTMP state on OnStop because we will get // OnStop when that Activity launches. if (mLaunchedExternalActivity) { Logger.d("OnStop: EXTERNAL ACTIVITY is pending, so not clearing RTMP."); } else { Clear("leaving room because game is stopping."); } } // called from the game thread public bool IsRoomConnected() { return mRoom != null && mDeliveredRoomConnected; } // called from the game thread public void DeclineInvitation(string invitationId) { Logger.d("AndroidRtmpClient.DeclineInvitation " + invitationId); mClient.ClearInvitationIfFromNotification(invitationId); mClient.CallClientApi("rtmp decline invitation", () => { mClient.GHManager.CallGmsApi("games.Games", "RealTimeMultiplayer", "declineInvitation", invitationId); }, (bool success) => { if (!success) { Logger.w("Failed to decline invitation. GoogleApiClient was disconnected"); } }); } // prepares to create a room private bool PrepareToCreateRoom(string method, RealTimeMultiplayerListener listener) { if (mRtmpActive) { Logger.e("Cannot call " + method + " while a real-time game is active."); if (listener != null) { Logger.d("Notifying listener of failure to create room."); listener.OnRoomConnected(false); } return false; } mAccumulatedProgress = 0.0f; mLastReportedProgress = 0.0f; mRtmpListener = listener; mRtmpActive = true; return true; } // checks that the room is connected, and warn otherwise private bool CheckConnectedRoom(string method) { if (mRoom == null || !mDeliveredRoomConnected) { Logger.e("Method " + method + " called without a connected room. " + "You must create or join a room AND wait until you get the " + "OnRoomConnected(true) callback."); return false; } return true; } // called from UI thread private void Clear(string reason) { Logger.d("RtmpClear: clearing RTMP (reason: " + reason + ")."); // leave the room, if we have one if (mRoom != null) { Logger.d("RtmpClear: Room still active, so leaving room."); string roomId = mRoom.Call<string>("getRoomId"); Logger.d("RtmpClear: room id to leave is " + roomId); // TODO: we are not specifying the callback from this API call to get // notified of when we *actually* leave the room. Perhaps we should do that, // in order to prevent the case where the developer tries to create a room // too soon after leaving the previous room, resulting in errors. mClient.GHManager.CallGmsApi("games.Games" , "RealTimeMultiplayer", "leave", new NoopProxy(JavaConsts.RoomUpdateListenerClass), roomId); Logger.d("RtmpClear: left room."); mRoom = null; } else { Logger.d("RtmpClear: no room active."); } // call the OnLeftRoom() callback if needed if (mDeliveredRoomConnected) { Logger.d("RtmpClear: looks like we must call the OnLeftRoom() callback."); RealTimeMultiplayerListener listener = mRtmpListener; if (listener != null) { Logger.d("Calling OnLeftRoom() callback."); PlayGamesHelperObject.RunOnGameThread(() => { listener.OnLeftRoom(); }); } } else { Logger.d("RtmpClear: no need to call OnLeftRoom() callback."); } mLeaveRoomRequested = false; mDeliveredRoomConnected = false; mRoom = null; mConnectedParticipants = null; mAllParticipants = null; mSelf = null; mRtmpListener = null; mVariant = 0; mRtmpActive = false; mAccumulatedProgress = 0.0f; mLastReportedProgress = 0.0f; mLaunchedExternalActivity = false; Logger.d("RtmpClear: RTMP cleared."); } private string[] SubtractParticipants(List<Participant> a, List<Participant> b) { List<string> result = new List<string>(); if (a != null) { foreach (Participant p in a) { result.Add(p.ParticipantId); } } if (b != null) { foreach (Participant p in b) { if (result.Contains(p.ParticipantId)) { result.Remove(p.ParticipantId); } } } return result.ToArray(); } // called from UI thread private void UpdateRoom() { List<AndroidJavaObject> toDispose = new List<AndroidJavaObject>(); Logger.d("UpdateRoom: Updating our cached data about the room."); string roomId = mRoom.Call<string>("getRoomId"); Logger.d("UpdateRoom: room id: " + roomId); Logger.d("UpdateRoom: querying for my player ID."); string playerId = mClient.GHManager.CallGmsApi<string>("games.Games", "Players", "getCurrentPlayerId"); Logger.d("UpdateRoom: my player ID is: " + playerId); Logger.d("UpdateRoom: querying for my participant ID in the room."); string myPartId = mRoom.Call<string>("getParticipantId", playerId); Logger.d("UpdateRoom: my participant ID is: " + myPartId); AndroidJavaObject participantIds = mRoom.Call<AndroidJavaObject>("getParticipantIds"); toDispose.Add(participantIds); int participantCount = participantIds.Call<int>("size"); Logger.d("UpdateRoom: # participants: " + participantCount); List<Participant> connectedParticipants = new List<Participant>(); List<Participant> allParticipants = new List<Participant>(); mSelf = null; for (int i = 0; i < participantCount; i++) { Logger.d("UpdateRoom: querying participant #" + i); string thisId = participantIds.Call<string>("get", i); Logger.d("UpdateRoom: participant #" + i + " has id: " + thisId); AndroidJavaObject thisPart = mRoom.Call<AndroidJavaObject>("getParticipant", thisId); toDispose.Add(thisPart); Participant p = JavaUtil.ConvertParticipant(thisPart); allParticipants.Add(p); if (p.ParticipantId.Equals(myPartId)) { Logger.d("Participant is SELF."); mSelf = p; } if (p.IsConnectedToRoom) { connectedParticipants.Add(p); } } if (mSelf == null) { Logger.e("List of room participants did not include self, " + " participant id: " + myPartId + ", player id: " + playerId); // stopgap: mSelf = new Participant("?", myPartId, Participant.ParticipantStatus.Unknown, new Player("?", playerId), false); } connectedParticipants.Sort(); allParticipants.Sort(); string[] newlyConnected; string[] newlyDisconnected; // lock the list because it's read by the game thread lock (mParticipantListsLock) { newlyConnected = SubtractParticipants(connectedParticipants, mConnectedParticipants); newlyDisconnected = SubtractParticipants(mConnectedParticipants, connectedParticipants); // IMPORTANT: we treat mConnectedParticipants as an immutable list; we give // away references to it to the callers of our API, so anyone out there might // be holding a reference to it and reading it from any thread. // This is why, instead of modifying it in place, we assign a NEW list to it. mConnectedParticipants = connectedParticipants; mAllParticipants = allParticipants; Logger.d("UpdateRoom: participant list now has " + mConnectedParticipants.Count + " participants."); } // cleanup Logger.d("UpdateRoom: cleanup."); foreach (AndroidJavaObject obj in toDispose) { obj.Dispose(); } Logger.d("UpdateRoom: newly connected participants: " + newlyConnected.Length); Logger.d("UpdateRoom: newly disconnected participants: " + newlyDisconnected.Length); // only deliver peers connected/disconnected events if have delivered OnRoomConnected if (mDeliveredRoomConnected) { if (newlyConnected.Length > 0 && mRtmpListener != null) { Logger.d("UpdateRoom: calling OnPeersConnected callback"); mRtmpListener.OnPeersConnected(newlyConnected); } if (newlyDisconnected.Length > 0 && mRtmpListener != null) { Logger.d("UpdateRoom: calling OnPeersDisconnected callback"); mRtmpListener.OnPeersDisconnected(newlyDisconnected); } } // did the developer request to leave the room? if (mLeaveRoomRequested) { Clear("deferred leave-room request"); } // is it time to report progress during room setup? if (!mDeliveredRoomConnected) { DeliverRoomSetupProgressUpdate(); } } // called from UI thread private void FailRoomSetup(string reason) { Logger.d("Failing room setup: " + reason); RealTimeMultiplayerListener listener = mRtmpListener; Clear("Room setup failed: " + reason); if (listener != null) { Logger.d("Invoking callback OnRoomConnected(false) to signal failure."); PlayGamesHelperObject.RunOnGameThread(() => { listener.OnRoomConnected(false); }); } } private bool CheckRtmpActive(string method) { if (!mRtmpActive) { Logger.d("Got call to " + method + " with RTMP inactive. Ignoring."); return false; } return true; } private void OnJoinedRoom(int statusCode, AndroidJavaObject room) { Logger.d("AndroidClient.OnJoinedRoom, status " + statusCode); if (!CheckRtmpActive("OnJoinedRoom")) { return; } mRoom = room; mAccumulatedProgress += 20.0f; if (statusCode != 0) { FailRoomSetup("OnJoinedRoom error code " + statusCode); } } private void OnLeftRoom(int statusCode, AndroidJavaObject room) { Logger.d("AndroidClient.OnLeftRoom, status " + statusCode); if (!CheckRtmpActive("OnLeftRoom")) { return; } Clear("Got OnLeftRoom " + statusCode); } private void OnRoomConnected(int statusCode, AndroidJavaObject room) { Logger.d("AndroidClient.OnRoomConnected, status " + statusCode); if (!CheckRtmpActive("OnRoomConnected")) { return; } mRoom = room; UpdateRoom(); if (statusCode != 0) { FailRoomSetup("OnRoomConnected error code " + statusCode); } else { Logger.d("AndroidClient.OnRoomConnected: room setup succeeded!"); RealTimeMultiplayerListener listener = mRtmpListener; if (listener != null) { Logger.d("Invoking callback OnRoomConnected(true) to report success."); PlayGamesHelperObject.RunOnGameThread(() => { mDeliveredRoomConnected = true; listener.OnRoomConnected(true); }); } } } private void OnRoomCreated(int statusCode, AndroidJavaObject room) { Logger.d("AndroidClient.OnRoomCreated, status " + statusCode); if (!CheckRtmpActive("OnRoomCreated")) { return; } mRoom = room; mAccumulatedProgress += 20.0f; if (statusCode != 0) { FailRoomSetup("OnRoomCreated error code " + statusCode); } UpdateRoom(); } private void OnConnectedToRoom(AndroidJavaObject room) { Logger.d("AndroidClient.OnConnectedToRoom"); if (!CheckRtmpActive("OnConnectedToRoom")) { return; } mAccumulatedProgress += 10.0f; mRoom = room; UpdateRoom(); } private void OnDisconnectedFromRoom(AndroidJavaObject room) { Logger.d("AndroidClient.OnDisconnectedFromRoom"); if (!CheckRtmpActive("OnDisconnectedFromRoom")) { return; } Clear("Got OnDisconnectedFromRoom"); } private void OnP2PConnected(string participantId) { Logger.d("AndroidClient.OnP2PConnected: " + participantId); if (!CheckRtmpActive("OnP2PConnected")) { return; } UpdateRoom(); } private void OnP2PDisconnected(string participantId) { Logger.d("AndroidClient.OnP2PDisconnected: " + participantId); if (!CheckRtmpActive("OnP2PDisconnected")) { return; } UpdateRoom(); } private void OnPeerDeclined(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeerDeclined"); if (!CheckRtmpActive("OnPeerDeclined")) { return; } mRoom = room; UpdateRoom(); // In the current API implementation, if a peer declines, the room will never // subsequently get an onRoomConnected, so this match is doomed to failure. if (!mDeliveredRoomConnected) { FailRoomSetup("OnPeerDeclined received during setup"); } } private void OnPeerInvitedToRoom(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeerInvitedToRoom"); if (!CheckRtmpActive("OnPeerInvitedToRoom")) { return; } mRoom = room; UpdateRoom(); } private void OnPeerJoined(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeerJoined"); if (!CheckRtmpActive("OnPeerJoined")) { return; } mRoom = room; UpdateRoom(); } private void OnPeerLeft(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeerLeft"); if (!CheckRtmpActive("OnPeerLeft")) { return; } mRoom = room; UpdateRoom(); // In the current API implementation, if a peer leaves, the room will never // subsequently get an onRoomConnected, so this match is doomed to failure. if (!mDeliveredRoomConnected) { FailRoomSetup("OnPeerLeft received during setup"); } } private void OnPeersConnected(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeersConnected"); if (!CheckRtmpActive("OnPeersConnected")) { return; } mRoom = room; UpdateRoom(); } private void OnPeersDisconnected(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeersDisconnected."); if (!CheckRtmpActive("OnPeersDisconnected")) { return; } mRoom = room; UpdateRoom(); } private void OnRoomAutoMatching(AndroidJavaObject room) { Logger.d("AndroidClient.OnRoomAutoMatching"); if (!CheckRtmpActive("OnRoomAutomatching")) { return; } mRoom = room; UpdateRoom(); } private void OnRoomConnecting(AndroidJavaObject room) { Logger.d("AndroidClient.OnRoomConnecting."); if (!CheckRtmpActive("OnRoomConnecting")) { return; } mRoom = room; UpdateRoom(); } private void OnRealTimeMessageReceived(AndroidJavaObject message) { Logger.d("AndroidClient.OnRealTimeMessageReceived."); if (!CheckRtmpActive("OnRealTimeMessageReceived")) { return; } RealTimeMultiplayerListener listener = mRtmpListener; if (listener != null) { byte[] messageData; using (AndroidJavaObject messageBytes = message.Call<AndroidJavaObject>("getMessageData")) { messageData = JavaUtil.ConvertByteArray(messageBytes); } bool isReliable = message.Call<bool>("isReliable"); string senderId = message.Call<string>("getSenderParticipantId"); PlayGamesHelperObject.RunOnGameThread(() => { listener.OnRealTimeMessageReceived(isReliable, senderId, messageData); }); } message.Dispose(); } private void OnSelectOpponentsResult(bool success, AndroidJavaObject opponents, bool hasAutoMatch, AndroidJavaObject autoMatchCriteria) { Logger.d("AndroidRtmpClient.OnSelectOpponentsResult, success=" + success); if (!CheckRtmpActive("OnSelectOpponentsResult")) { return; } // we now do not have an external Activity that we launched mLaunchedExternalActivity = false; if (!success) { Logger.w("Room setup failed because select-opponents UI failed."); FailRoomSetup("Select opponents UI failed."); return; } // at this point, we have to create the room -- but we have to make sure that // our GoogleApiClient is connected before we do that. It might NOT be connected // right now because we just came back from calling an external Activity. // So we use CallClientApi to make sure we are only doing this at the right time: mClient.CallClientApi("creating room w/ select-opponents result", () => { Logger.d("Creating room via support lib's RtmpUtil."); AndroidJavaClass rtmpUtil = JavaUtil.GetClass(JavaConsts.SupportRtmpUtilsClass); rtmpUtil.CallStatic("create", mClient.GHManager.GetApiClient(), opponents, mVariant, hasAutoMatch ? autoMatchCriteria : null, new RoomUpdateProxy(this), new RoomStatusUpdateProxy(this), new RealTimeMessageReceivedProxy(this)); }, (bool ok) => { if (!ok) { FailRoomSetup("GoogleApiClient lost connection"); } }); } private void OnInvitationInboxResult(bool success, string invitationId) { Logger.d("AndroidRtmpClient.OnInvitationInboxResult, " + "success=" + success + ", invitationId=" + invitationId); if (!CheckRtmpActive("OnInvitationInboxResult")) { return; } // we now do not have an external Activity that we launched mLaunchedExternalActivity = false; if (!success || invitationId == null || invitationId.Length == 0) { Logger.w("Failed to setup room because invitation inbox UI failed."); FailRoomSetup("Invitation inbox UI failed."); return; } mClient.ClearInvitationIfFromNotification(invitationId); // we use CallClientApi instead of calling the API directly because we need // to make sure that we call it when the GoogleApiClient is connected, which is // not necessarily true at this point (we just came back from an external // activity) mClient.CallClientApi("accept invite from inbox", () => { Logger.d("Accepting invite from inbox via support lib."); AndroidJavaClass rtmpUtil = JavaUtil.GetClass(JavaConsts.SupportRtmpUtilsClass); rtmpUtil.CallStatic("accept", mClient.GHManager.GetApiClient(), invitationId, new RoomUpdateProxy(this), new RoomStatusUpdateProxy(this), new RealTimeMessageReceivedProxy(this)); }, (bool ok) => { if (!ok) { FailRoomSetup("GoogleApiClient lost connection."); } }); } private void DeliverRoomSetupProgressUpdate() { Logger.d("AndroidRtmpClient: DeliverRoomSetupProgressUpdate"); if (!mRtmpActive || mRoom == null || mDeliveredRoomConnected) { // no need to deliver progress return; } float progress = CalcRoomSetupPercentage(); if (progress < mLastReportedProgress) { progress = mLastReportedProgress; } else { mLastReportedProgress = progress; } Logger.d("room setup progress: " + progress + "%"); if (mRtmpListener != null) { Logger.d("Delivering progress to callback."); PlayGamesHelperObject.RunOnGameThread(() => { mRtmpListener.OnRoomSetupProgress(progress); }); } } private float CalcRoomSetupPercentage() { if (!mRtmpActive || mRoom == null) { return 0.0f; } if (mDeliveredRoomConnected) { return 100.0f; } float progress = mAccumulatedProgress; if (progress > 50.0f) { progress = 50.0f; } float remaining = 100.0f - progress; int all = mAllParticipants == null ? 0 : mAllParticipants.Count; int connected = mConnectedParticipants == null ? 0 : mConnectedParticipants.Count; if (all == 0) { return progress; } else { return progress + remaining * ((float)connected / all); } } private class RoomUpdateProxy : AndroidJavaProxy { AndroidRtmpClient mOwner; internal RoomUpdateProxy(AndroidRtmpClient owner) : base(JavaConsts.RoomUpdateListenerClass) { mOwner = owner; } public void onJoinedRoom(int statusCode, AndroidJavaObject room) { mOwner.OnJoinedRoom(statusCode, room); } public void onLeftRoom(int statusCode, AndroidJavaObject room) { mOwner.OnLeftRoom(statusCode, room); } public void onRoomConnected(int statusCode, AndroidJavaObject room) { mOwner.OnRoomConnected(statusCode, room); } public void onRoomCreated(int statusCode, AndroidJavaObject room) { mOwner.OnRoomCreated(statusCode, room); } } private class RoomStatusUpdateProxy : AndroidJavaProxy { AndroidRtmpClient mOwner; internal RoomStatusUpdateProxy(AndroidRtmpClient owner) : base(JavaConsts.RoomStatusUpdateListenerClass) { mOwner = owner; } public void onConnectedToRoom(AndroidJavaObject room) { mOwner.OnConnectedToRoom(room); } public void onDisconnectedFromRoom(AndroidJavaObject room) { mOwner.OnDisconnectedFromRoom(room); } public void onP2PConnected(string participantId) { mOwner.OnP2PConnected(participantId); } public void onP2PDisconnected(string participantId) { mOwner.OnP2PDisconnected(participantId); } public void onPeerDeclined(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeerDeclined(room, participantIds); } public void onPeerInvitedToRoom(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeerInvitedToRoom(room, participantIds); } public void onPeerJoined(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeerJoined(room, participantIds); } public void onPeerLeft(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeerLeft(room, participantIds); } public void onPeersConnected(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeersConnected(room, participantIds); } public void onPeersDisconnected(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeersDisconnected(room, participantIds); } public void onRoomAutoMatching(AndroidJavaObject room) { mOwner.OnRoomAutoMatching(room); } public void onRoomConnecting(AndroidJavaObject room) { mOwner.OnRoomConnecting(room); } } private class RealTimeMessageReceivedProxy : AndroidJavaProxy { AndroidRtmpClient mOwner; internal RealTimeMessageReceivedProxy(AndroidRtmpClient owner) : base(JavaConsts.RealTimeMessageReceivedListenerClass) { mOwner = owner; } public void onRealTimeMessageReceived(AndroidJavaObject message) { mOwner.OnRealTimeMessageReceived(message); } } private class SelectOpponentsProxy : AndroidJavaProxy { AndroidRtmpClient mOwner; internal SelectOpponentsProxy(AndroidRtmpClient owner) : base(JavaConsts.SupportSelectOpponentsHelperActivityListener) { mOwner = owner; } public void onSelectOpponentsResult(bool success, AndroidJavaObject opponents, bool hasAutoMatch, AndroidJavaObject autoMatchCriteria) { mOwner.OnSelectOpponentsResult(success, opponents, hasAutoMatch, autoMatchCriteria); } } internal void OnSignInSucceeded() { // nothing for now } private class InvitationInboxProxy : AndroidJavaProxy { AndroidRtmpClient mOwner; internal InvitationInboxProxy(AndroidRtmpClient owner) : base(JavaConsts.SupportInvitationInboxHelperActivityListener) { mOwner = owner; } public void onInvitationInboxResult(bool success, string invitationId) { mOwner.OnInvitationInboxResult(success, invitationId); } public void onTurnBasedMatch(AndroidJavaObject match) { Logger.e("Bug: RTMP proxy got onTurnBasedMatch(). Shouldn't happen. Ignoring."); } } } } #endif
pixelthieves/Paper-Frog
Assets/GooglePlayGames/Platforms/Android/AndroidRtmpClient.cs
C#
gpl-2.0
43,782
# -*- coding: utf-8 -*- """ *************************************************************************** EditScriptAction.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'April 2014' __copyright__ = '(C) 201, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from qgis.PyQt.QtWidgets import QFileDialog, QMessageBox from qgis.PyQt.QtGui import QIcon from qgis.PyQt.QtCore import QSettings, QFileInfo from processing.script.ScriptAlgorithm import ScriptAlgorithm from processing.gui.ToolboxAction import ToolboxAction from processing.script.WrongScriptException import WrongScriptException from processing.script.ScriptUtils import ScriptUtils from processing.core.alglist import algList pluginPath = os.path.split(os.path.dirname(__file__))[0] class AddScriptFromFileAction(ToolboxAction): def __init__(self): self.name, self.i18n_name = self.trAction('Add script from file') self.group, self.i18n_group = self.trAction('Tools') def getIcon(self): return QIcon(os.path.join(pluginPath, 'images', 'script.png')) def execute(self): settings = QSettings() lastDir = settings.value('Processing/lastScriptsDir', '') filename, selected_filter = QFileDialog.getOpenFileName(self.toolbox, self.tr('Script files', 'AddScriptFromFileAction'), lastDir, self.tr('Script files (*.py *.PY)', 'AddScriptFromFileAction')) if filename: try: settings.setValue('Processing/lastScriptsDir', QFileInfo(filename).absoluteDir().absolutePath()) script = ScriptAlgorithm(filename) except WrongScriptException: QMessageBox.warning(self.toolbox, self.tr('Error reading script', 'AddScriptFromFileAction'), self.tr('The selected file does not contain a valid script', 'AddScriptFromFileAction')) return destFilename = os.path.join(ScriptUtils.scriptsFolders()[0], os.path.basename(filename)) with open(destFilename, 'w') as f: f.write(script.script) algList.reloadProvider('script')
wonder-sk/QGIS
python/plugins/processing/script/AddScriptFromFileAction.py
Python
gpl-2.0
3,158
/* Copyright 2013 David Axmark 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. */ /** * Util.cpp * * Created on: Aug 7, 2012 * Author: Spiridon Alexandru */ #include <maapi.h> #include "Util.h" #define BUF_MAX 256 /** * Detects if the current platform is Android. * @return true if the platform is Android, false otherwise. */ bool isAndroid() { char platform[BUF_MAX]; maGetSystemProperty("mosync.device.OS", platform, BUF_MAX); if ( strcmp(platform,"Android") == 0 ) { return true; } return false; } /** * Detects if the current platform is iOS. * @return true if the platform is iOS, false otherwise. */ bool isIOS() { char platform[BUF_MAX]; maGetSystemProperty("mosync.device.OS", platform, BUF_MAX); for (unsigned int i = 0; i < strlen(platform); i++) { platform[i] = tolower(platform[i]); } if (strstr(platform,"iphone") != NULL) { return true; } return false; } /** * Detects if the current platform is Windows Phone. * @return true if the platform is Windows Phone, false otherwise. */ bool isWindowsPhone() { char platform[BUF_MAX]; maGetSystemProperty("mosync.device.OS", platform, BUF_MAX); for (unsigned int i = 0; i < strlen(platform); i++) { platform[i] = tolower(platform[i]); } if (strstr(platform,"microsoft") != NULL && strstr(platform,"windows") != NULL) { return true; } return false; } /** * Get the string associated with a ListViewItemSelectionStyle. * @param style The given style. * @return The string associated with the given style. */ MAUtil::String getSelectionStyleString(NativeUI::ListViewItemSelectionStyle style) { MAUtil::String returnedValue; switch (style) { case NativeUI::LIST_VIEW_ITEM_SELECTION_STYLE_BLUE: returnedValue = "blue"; break; case NativeUI::LIST_VIEW_ITEM_SELECTION_STYLE_GRAY: returnedValue = "gray"; break; case NativeUI::LIST_VIEW_ITEM_SELECTION_STYLE_NONE: default: returnedValue = "none"; break; } return returnedValue; }
MoSync/MoSync
testPrograms/native_ui_lib/AlphabeticalListTest/Util.cpp
C++
gpl-2.0
2,447
<?php // Global profile namespace reference define( 'NS_USER_PROFILE', 202 ); define( 'NS_USER_WIKI', 200 ); // Default setup for displaying sections $wgUserPageChoice = true; $wgUserProfileDisplay['friends'] = false; $wgUserProfileDisplay['foes'] = false; $wgUserProfileDisplay['gifts'] = true; $wgUserProfileDisplay['awards'] = true; $wgUserProfileDisplay['profile'] = true; $wgUserProfileDisplay['board'] = false; $wgUserProfileDisplay['stats'] = false; // Display statistics on user profile pages? $wgUserProfileDisplay['interests'] = true; $wgUserProfileDisplay['custom'] = true; $wgUserProfileDisplay['personal'] = true; $wgUserProfileDisplay['activity'] = false; // Display recent social activity? $wgUserProfileDisplay['userboxes'] = false; // If FanBoxes extension is installed, setting this to true will display the user's fanboxes on their profile page $wgUserProfileDisplay['games'] = false; // Display casual games created by the user on their profile? This requires three separate social extensions: PictureGame, PollNY and QuizGame $wgUpdateProfileInRecentChanges = false; // Show a log entry in recent changes whenever a user updates their profile? $wgUploadAvatarInRecentChanges = false; // Same as above, but for avatar uploading $wgAvailableRights[] = 'avatarremove'; $wgAvailableRights[] = 'editothersprofiles'; $wgGroupPermissions['sysop']['avatarremove'] = true; $wgGroupPermissions['staff']['editothersprofiles'] = true; // ResourceLoader support for MediaWiki 1.17+ // Modules for Special:EditProfile/Special:UpdateProfile $wgResourceModules['ext.userProfile.updateProfile'] = array( 'styles' => 'UserProfile.css', 'scripts' => 'UpdateProfile.js', 'localBasePath' => dirname( __FILE__ ), 'remoteExtPath' => 'SocialProfile/UserProfile', 'position' => 'top' ); # Add new log types for profile edits and avatar uploads global $wgLogTypes, $wgLogNames, $wgLogHeaders, $wgLogActions; $wgLogTypes[] = 'profile'; $wgLogNames['profile'] = 'profilelogpage'; $wgLogHeaders['profile'] = 'profilelogpagetext'; $wgLogActions['profile/profile'] = 'profilelogentry'; $wgLogTypes[] = 'avatar'; $wgLogNames['avatar'] = 'avatarlogpage'; $wgLogHeaders['avatar'] = 'avatarlogpagetext'; $wgLogActions['avatar/avatar'] = 'avatarlogentry'; $wgHooks['ArticleFromTitle'][] = 'wfUserProfileFromTitle'; /** * Called by ArticleFromTitle hook * Calls UserProfilePage instead of standard article * * @param &$title Title object * @param &$article Article object * @return true */ function wfUserProfileFromTitle( &$title, &$article ) { global $wgRequest, $wgOut, $wgHooks, $wgUserPageChoice, $wgUserProfileScripts; if ( strpos( $title->getText(), '/' ) === false && ( NS_USER == $title->getNamespace() || NS_USER_PROFILE == $title->getNamespace() ) ) { $show_user_page = false; if ( $wgUserPageChoice ) { $profile = new UserProfile( $title->getText() ); $profile_data = $profile->getProfile(); // If they want regular page, ignore this hook if ( isset( $profile_data['user_id'] ) && $profile_data['user_id'] && $profile_data['user_page_type'] == 0 ) { $show_user_page = true; } } if ( !$show_user_page ) { // Prevents editing of userpage if ( $wgRequest->getVal( 'action' ) == 'edit' ) { $wgOut->redirect( $title->getFullURL() ); } } else { $wgOut->enableClientCache( false ); $wgHooks['ParserLimitReport'][] = 'wfUserProfileMarkUncacheable'; } $wgOut->addExtensionStyle( $wgUserProfileScripts . '/UserProfile.css' ); $article = new UserProfilePage( $title ); } return true; } /** * Mark page as uncacheable * * @param $parser Parser object * @param &$limitReport String: unused * @return true */ function wfUserProfileMarkUncacheable( $parser, &$limitReport ) { $parser->disableCache(); return true; }
SuriyaaKudoIsc/wikia-app-test
extensions/SocialProfile/UserProfile/UserProfile.php
PHP
gpl-2.0
3,868
// ext3grep -- An ext3 file system investigation and undelete tool // //! @file debug.cc //! @brief This file contains the definitions of debug related objects and functions. // // Copyright (C) 2008, by // // Carlo Wood, Run on IRC <carlo@alinoe.com> // RSA-1024 0x624ACAD5 1997-01-26 Sign & Encrypt // Fingerprint16 = 32 EC A7 B6 AC DB 65 A6 F6 F6 55 DD 1C DC FF 61 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef USE_PCH #include "sys.h" // Needed for platform-specific code #endif #ifdef CWDEBUG #ifndef USE_PCH #include <cctype> // Needed for std::isprint #include <iomanip> // Needed for setfill #include <map> #include <string> #include <sstream> #include <signal.h> #include "debug.h" #ifdef USE_LIBCW #include <libcw/memleak.h> // memleak_filter #endif #endif // USE_PCH namespace debug { namespace channels { // namespace DEBUGCHANNELS namespace dc { #ifndef DOXYGEN #define DDCN(x) (x) #endif // Add new debug channels here. //channel_ct custom DDCN("CUSTOM"); //!< This debug channel is used for ... } // namespace dc } // namespace DEBUGCHANNELS // Anonymous namespace, this map and its initialization functions are private to this file // for Thead-safeness reasons. namespace { /*! @brief The type of rcfile_dc_states. * @internal */ typedef std::map<std::string, bool> rcfile_dc_states_type; /*! @brief Map containing the default debug channel states used at the start of each new thread. * @internal * * The first thread calls main, which calls debug::init which will initialize this * map with all debug channel labels and whether or not they were turned on in the * rcfile or not. */ rcfile_dc_states_type rcfile_dc_states; /*! @brief Set the default state of debug channel \a dc_label. * @internal * * This function is called once for each debug channel. */ void set_state(char const* dc_label, bool is_on) { std::pair<rcfile_dc_states_type::iterator, bool> res = rcfile_dc_states.insert(rcfile_dc_states_type::value_type(std::string(dc_label), is_on)); if (!res.second) Dout(dc::warning, "Calling set_state() more than once for the same label!"); return; } /*! @brief Save debug channel states. * @internal * * One time initialization function of rcfile_dc_state. * This must be called from debug::init after reading the rcfile. */ void save_dc_states(void) { // We may only call this function once: it reflects the states as stored // in the rcfile and that won't change. Therefore it is not needed to // lock `rcfile_dc_states', it is only written to by the first thread // (once, via main -> init) when there are no other threads yet. static bool second_time = false; if (second_time) { Dout(dc::warning, "Calling save_dc_states() more than once!"); return; } second_time = true; ForAllDebugChannels( set_state(debugChannel.get_label(), debugChannel.is_on()) ); } } // anonymous namespace /*! @brief Returns the the original state of a debug channel. * @internal * * For a given \a dc_label, which must be the exact name (<tt>channel_ct::get_label</tt>) of an * existing debug channel, this function returns \c true when the corresponding debug channel was * <em>on</em> at the startup of the application, directly after reading the libcwd runtime * configuration file (.libcwdrc). * * If the label/channel did not exist at the start of the application, it will return \c false * (note that libcwd disallows adding debug channels to modules - so this would probably * a bug). */ bool is_on_in_rcfile(char const* dc_label) { rcfile_dc_states_type::const_iterator iter = rcfile_dc_states.find(std::string(dc_label)); if (iter == rcfile_dc_states.end()) { Dout(dc::warning, "is_on_in_rcfile(\"" << dc_label << "\"): \"" << dc_label << "\" is an unknown label!"); return false; } return iter->second; } /*! @brief Initialize debugging code from new threads. * * This function needs to be called at the start of each new thread, * because a new thread starts in a completely reset state. * * The function turns on all debug channels that were turned on * after reading the rcfile at the start of the application. * Furthermore it initializes the debug ostream, its mutex and the * margin of the default debug object (Dout). */ void init_thread(void) { // Turn on all debug channels that are turned on as per rcfile configuration. ForAllDebugChannels( if (!debugChannel.is_on() && is_on_in_rcfile(debugChannel.get_label())) debugChannel.on(); ); // Turn on debug output. Debug( libcw_do.on() ); #if LIBCWD_THREAD_SAFE Debug( libcw_do.set_ostream(&std::cout, &cout_mutex) ); #else Debug( libcw_do.set_ostream(&std::cout) ); #endif static bool first_thread = true; if (!first_thread) // So far, the application has only one thread. So don't add a thread id. { // Set the thread id in the margin. char margin[12]; sprintf(margin, "%-10lu ", pthread_self()); Debug( libcw_do.margin().assign(margin, 11) ); } } /*! @brief Initialize debugging code from main. * * This function initializes the debug code. */ void init(void) { #if CWDEBUG_ALLOC && defined(USE_LIBCW) // Tell the memory leak detector which parts of the code are // expected to leak so that we won't get an alarm for those. { std::vector<std::pair<std::string, std::string> > hide_list; hide_list.push_back(std::pair<std::string, std::string>("libdl.so.2", "_dlerror_run")); hide_list.push_back(std::pair<std::string, std::string>("libstdc++.so.6", "__cxa_get_globals")); // The following is actually necessary because of a bug in glibc // (see http://sources.redhat.com/bugzilla/show_bug.cgi?id=311). hide_list.push_back(std::pair<std::string, std::string>("libc.so.6", "dl_open_worker")); memleak_filter().hide_functions_matching(hide_list); } { std::vector<std::string> hide_list; // Also because of http://sources.redhat.com/bugzilla/show_bug.cgi?id=311 hide_list.push_back(std::string("ld-linux.so.2")); memleak_filter().hide_objectfiles_matching(hide_list); } memleak_filter().set_flags(libcwd::show_objectfile|libcwd::show_function); #endif // The following call allocated the filebuf's of cin, cout, cerr, wcin, wcout and wcerr. // Because this causes a memory leak being reported, make them invisible. Debug(set_invisible_on()); // You want this, unless you mix streams output with C output. // Read http://gcc.gnu.org/onlinedocs/libstdc++/27_io/howto.html#8 for an explanation. //std::ios::sync_with_stdio(false); // Cancel previous call to set_invisible_on. Debug(set_invisible_off()); // This will warn you when you are using header files that do not belong to the // shared libcwd object that you linked with. Debug( check_configuration() ); Debug( libcw_do.on(); // Show which rcfile we are reading! ForAllDebugChannels( while (debugChannel.is_on()) debugChannel.off() // Print as little as possible though. ); read_rcfile(); // Put 'silent = on' in the rcfile to suppress most of the output here. libcw_do.off() ); save_dc_states(); init_thread(); } #if CWDEBUG_LOCATION /*! @brief Return call location. * * @param return_addr The return address of the call. */ std::string call_location(void const* return_addr) { libcwd::location_ct loc((char*)return_addr + libcwd::builtin_return_address_offset); std::ostringstream convert; convert << loc; return convert.str(); } #endif } // namespace debug #endif // CWDEBUG //----------------------------------------------------------------------------- // // Debug stuff #include "debug.h" // Define our own assert. #ifdef DEBUG #include <iostream> #include "backtrace.h" #include <signal.h> void assert_fail(char const* expr, char const* file, int line, char const* function) { std::cout << file << ':' << line << ": " << function << ": Assertion `" << expr << "' failed." << std::endl; std::cout << "Backtrace:\n"; dump_backtrace_on(std::cout); raise(6); } #endif #if EXTERNAL_BLOCK #if 0 // Ian Jacobi's '\\' file. uint32_t someones_inode_count = std::numeric_limits<uint32_t>::max(); unsigned char someones_block[SOMEONES_BLOCK_SIZE] = { 0x21, 0x47, 0xf1, 0x00, 0x0c, 0x00, 0x01, 0x02, 0x2e, 0x00, 0x00, 0x00, 0x20, 0x47, 0xf1, 0x00, 0x0c, 0x00, 0x02, 0x02, 0x2e, 0x2e, 0x00, 0x00, 0x22, 0x47, 0xf1, 0x00, 0xe8, 0x0f, 0x01, 0x02, 0x5c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0 }; #else // siegelring -- directory, not detected as directory. uint32_t someones_inode_count = 1465920; unsigned char someones_block[SOMEONES_BLOCK_SIZE] = { 0x34, 0xba, 0x08, 0x00, 0x0c, 0x00, 0x01, 0x02, 0x2e, 0x00, 0x00, 0x00, 0x2d, 0xba, 0x08, 0x00, 0x0c, 0x00, 0x02, 0x02, 0x2e, 0x2e, 0x00, 0x00, 0x35, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x2e, 0x66, 0x6f, 0x72, 0x6d, 0x00, 0x00, 0x00, 0x36, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x00, 0x37, 0xba, 0x08, 0x00, 0x24, 0x00, 0x1b, 0x01, 0x46, 0x61, 0x68, 0x72, 0x74, 0x65, 0x6e, 0x62, 0x75, 0x63, 0x68, 0x2d, 0x61, 0x75, 0x66, 0x72, 0x75, 0x66, 0x2d, 0x6a, 0x61, 0x76, 0x61, 0x2e, 0x74, 0x78, 0x74, 0x00, 0x38, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x34, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x39, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0f, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x44, 0x65, 0x6d, 0x6f, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x3a, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0e, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x3b, 0xba, 0x08, 0x00, 0x10, 0x00, 0x08, 0x01, 0x2e, 0x6e, 0x62, 0x61, 0x74, 0x74, 0x72, 0x73, 0x3c, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0e, 0x01, 0x4a, 0x61, 0x72, 0x4d, 0x61, 0x6b, 0x65, 0x72, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x3d, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x14, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x43, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x54, 0x65, 0x73, 0x74, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x3e, 0xba, 0x08, 0x00, 0x14, 0x00, 0x09, 0x01, 0x46, 0x62, 0x31, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x00, 0x3f, 0xba, 0x08, 0x00, 0x10, 0x00, 0x08, 0x01, 0x46, 0x62, 0x31, 0x2e, 0x66, 0x6f, 0x72, 0x6d, 0x40, 0xba, 0x08, 0x00, 0x10, 0x00, 0x08, 0x01, 0x46, 0x62, 0x31, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x41, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x35, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x42, 0xba, 0x08, 0x00, 0x10, 0x00, 0x08, 0x01, 0x46, 0x62, 0x33, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x43, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0e, 0x01, 0x66, 0x62, 0x5f, 0x4f, 0x6b, 0x74, 0x6f, 0x62, 0x65, 0x72, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x00, 0x44, 0xba, 0x08, 0x00, 0x24, 0x00, 0x1a, 0x01, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x24, 0x4d, 0x79, 0x42, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x45, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x12, 0x01, 0x4a, 0x4d, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x4c, 0x6f, 0x61, 0x64, 0x65, 0x72, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x46, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x36, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x47, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0e, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x44, 0x65, 0x6d, 0x6f, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x48, 0xba, 0x08, 0x00, 0x20, 0x00, 0x16, 0x01, 0x46, 0x62, 0x31, 0x24, 0x4d, 0x79, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x4d, 0x6f, 0x64, 0x65, 0x6c, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x49, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x66, 0x62, 0x5f, 0x41, 0x75, 0x67, 0x75, 0x73, 0x74, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x00, 0x00, 0x4a, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0f, 0x01, 0x66, 0x62, 0x5f, 0x4e, 0x6f, 0x76, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x4b, 0xba, 0x08, 0x00, 0x14, 0x00, 0x09, 0x01, 0x46, 0x62, 0x33, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x00, 0x4c, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x13, 0x01, 0x42, 0x72, 0x6f, 0x77, 0x73, 0x65, 0x72, 0x4d, 0x61, 0x69, 0x6e, 0x54, 0x61, 0x62, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x4d, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x13, 0x01, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x24, 0x31, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x4e, 0xba, 0x08, 0x00, 0x14, 0x00, 0x09, 0x01, 0x55, 0x74, 0x69, 0x6c, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x00, 0x4f, 0xba, 0x08, 0x00, 0x18, 0x00, 0x10, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x24, 0x31, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x50, 0xba, 0x08, 0x00, 0x18, 0x00, 0x10, 0x01, 0x66, 0x62, 0x5f, 0x53, 0x65, 0x70, 0x74, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x2e, 0x64, 0x61, 0x74, 0x51, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x66, 0x6f, 0x6e, 0x74, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x66, 0x6f, 0x72, 0x6d, 0x00, 0x00, 0x00, 0x52, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x66, 0x6f, 0x6e, 0x74, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x00, 0x53, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x11, 0x01, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x00, 0x54, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x4d, 0x41, 0x4e, 0x49, 0x46, 0x45, 0x53, 0x54, 0x2e, 0x4d, 0x46, 0x00, 0x55, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x31, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x56, 0xba, 0x08, 0x00, 0x24, 0x00, 0x1c, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x44, 0x65, 0x6d, 0x6f, 0x24, 0x4d, 0x79, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x4d, 0x6f, 0x64, 0x65, 0x6c, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x57, 0xba, 0x08, 0x00, 0x20, 0x00, 0x15, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x43, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x54, 0x65, 0x73, 0x74, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x00, 0x58, 0xba, 0x08, 0x00, 0x18, 0x00, 0x10, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x24, 0x32, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x59, 0xba, 0x08, 0x00, 0x18, 0x00, 0x10, 0x01, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x5a, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x4a, 0x61, 0x72, 0x4d, 0x61, 0x6b, 0x65, 0x72, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x00, 0x5b, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0c, 0x01, 0x66, 0x62, 0x5f, 0x41, 0x70, 0x72, 0x69, 0x6c, 0x2e, 0x64, 0x61, 0x74, 0x5c, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0f, 0x01, 0x66, 0x61, 0x68, 0x72, 0x74, 0x65, 0x6e, 0x62, 0x75, 0x63, 0x68, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x5d, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0c, 0x01, 0x66, 0x62, 0x5f, 0x4d, 0x61, 0x65, 0x72, 0x7a, 0x2e, 0x64, 0x61, 0x74, 0x5e, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x32, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x5f, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x11, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x44, 0x65, 0x6d, 0x6f, 0x24, 0x31, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x00, 0x60, 0xba, 0x08, 0x00, 0x18, 0x00, 0x10, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x24, 0x33, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x61, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0c, 0x01, 0x46, 0x62, 0x50, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x62, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x13, 0x01, 0x4a, 0x4d, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x4c, 0x6f, 0x61, 0x64, 0x65, 0x72, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x63, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x13, 0x01, 0x66, 0x62, 0x5f, 0x46, 0x65, 0x62, 0x72, 0x75, 0x61, 0x72, 0x5f, 0x32, 0x30, 0x30, 0x34, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x64, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x13, 0x01, 0x66, 0x62, 0x5f, 0x46, 0x65, 0x62, 0x72, 0x75, 0x61, 0x72, 0x5f, 0x32, 0x30, 0x30, 0x35, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x65, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x12, 0x01, 0x66, 0x62, 0x5f, 0x4a, 0x61, 0x6e, 0x75, 0x61, 0x72, 0x5f, 0x32, 0x30, 0x30, 0x34, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x00, 0x66, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0a, 0x01, 0x55, 0x74, 0x69, 0x6c, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x67, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x66, 0x62, 0x5f, 0x4a, 0x75, 0x6c, 0x69, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x68, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0f, 0x01, 0x66, 0x62, 0x5f, 0x44, 0x65, 0x7a, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x69, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x33, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x6a, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x66, 0x62, 0x5f, 0x4a, 0x75, 0x6e, 0x69, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x6b, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0a, 0x01, 0x66, 0x62, 0x5f, 0x4d, 0x61, 0x69, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x00, 0x6c, 0xba, 0x08, 0x00, 0xc8, 0x0a, 0x01, 0x01, 0x9b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0 }; #endif #else // !EXTERNAL_BLOCK // Not used, except in compiler check. uint32_t someones_inode_count; unsigned char someones_block[SOMEONES_BLOCK_SIZE]; #endif // !EXTERNAL_BLOCK
gcode-mirror/ext3grep
src/debug.cc
C++
gpl-2.0
18,296
/* * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 6601652 * @summary Test exception when SortedMap or SortedSet has non-null Comparator * @author Eamonn McManus * @modules java.management */ import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; public class ComparatorExceptionTest { public static interface TestMXBean { public SortedSet<String> getSortedSet(); public SortedMap<String, String> getSortedMap(); } public static class TestImpl implements TestMXBean { public SortedSet<String> getSortedSet() { return new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); } public SortedMap<String, String> getSortedMap() { return new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); } } private static String failure; private static void fail(String why) { failure = "FAILED: " + why; System.out.println(failure); } public static void main(String[] args) throws Exception { MBeanServer mbs = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("a:b=c"); mbs.registerMBean(new TestImpl(), name); for (String attr : new String[] {"SortedSet", "SortedMap"}) { try { Object value = mbs.getAttribute(name, attr); fail("get " + attr + " did not throw exception"); } catch (Exception e) { Throwable t = e; while (!(t instanceof IllegalArgumentException)) { if (t == null) break; t = t.getCause(); } if (t != null) System.out.println("Correct exception for " + attr); else { fail("get " + attr + " got wrong exception"); e.printStackTrace(System.out); } } } if (failure != null) throw new Exception(failure); } }
FauxFaux/jdk9-jdk
test/javax/management/mxbean/ComparatorExceptionTest.java
Java
gpl-2.0
3,210
<?php /* ** Zabbix ** Copyright (C) 2000-2011 Zabbix SIA ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ ?> <?php require_once dirname(__FILE__).'/include/config.inc.php'; require_once dirname(__FILE__).'/include/hosts.inc.php'; require_once dirname(__FILE__).'/include/maintenances.inc.php'; require_once dirname(__FILE__).'/include/forms.inc.php'; $page['title'] = _('Configuration of maintenance'); $page['file'] = 'maintenance.php'; $page['hist_arg'] = array('groupid', 'hostid'); $page['scripts'] = array('class.calendar.js'); require_once dirname(__FILE__).'/include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array( 'hosts' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'groups' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'hostids' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'groupids' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'hostid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'groupid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), // maintenance 'maintenanceid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, 'isset({form})&&({form}=="update")'), 'maintenanceids' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'mname' => array(T_ZBX_STR, O_OPT, null, NOT_EMPTY, 'isset({save})'), 'maintenance_type' => array(T_ZBX_INT, O_OPT, null, null, 'isset({save})'), 'description' => array(T_ZBX_STR, O_OPT, null, null, 'isset({save})'), 'active_since' => array(T_ZBX_STR, O_OPT, null, NOT_EMPTY, 'isset({save})'), 'active_till' => array(T_ZBX_STR, O_OPT, null, NOT_EMPTY, 'isset({save})'), 'new_timeperiod' => array(T_ZBX_STR, O_OPT, null, null, 'isset({add_timeperiod})'), 'timeperiods' => array(T_ZBX_STR, O_OPT, null, null, null), 'g_timeperiodid' => array(null, O_OPT, null, null, null), 'edit_timeperiodid' => array(null, O_OPT, P_ACT, DB_ID, null), 'twb_groupid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), // actions 'go' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'add_timeperiod' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'del_timeperiod' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'cancel_new_timeperiod' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'save' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'clone' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'delete' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'cancel' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), // form 'form' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'form_refresh' => array(T_ZBX_STR, O_OPT, null, null, null) ); check_fields($fields); validate_sort_and_sortorder('name', ZBX_SORT_UP); $_REQUEST['go'] = get_request('go', 'none'); // permissions if (get_request('groupid', 0) > 0) { $groupids = available_groups($_REQUEST['groupid'], 1); if (empty($groupids)) { access_deny(); } } if (get_request('hostid', 0) > 0) { $hostids = available_hosts($_REQUEST['hostid'], 1); if (empty($hostids)) { access_deny(); } } /* * Actions */ if (isset($_REQUEST['clone']) && isset($_REQUEST['maintenanceid'])) { unset($_REQUEST['maintenanceid']); $_REQUEST['form'] = 'clone'; } elseif (isset($_REQUEST['cancel_new_timeperiod'])) { unset($_REQUEST['new_timeperiod']); } elseif (isset($_REQUEST['save'])) { if (!count(get_accessible_nodes_by_user($USER_DETAILS, PERM_READ_WRITE, PERM_RES_IDS_ARRAY))) { access_deny(); } if (isset($_REQUEST['maintenanceid'])) { $msg1 = _('Maintenance updated'); $msg2 = _('Cannot update maintenance'); } else { $msg1 = _('Maintenance added'); $msg2 = _('Cannot add maintenance'); } $active_since = zbxDateToTime(get_request('active_since', date('YmdHi'))); $active_till = zbxDateToTime(get_request('active_till')); $isValid = true; if (empty($active_since)) { error(_s('"%s" must be between 1970.01.01 and 2038.01.18', _('Active since'))); $isValid = false; } if (empty($active_till)) { error(_s('"%s" must be between 1970.01.01 and 2038.01.18', _('Active till'))); $isValid = false; } if ($isValid) { $maintenance = array( 'name' => $_REQUEST['mname'], 'maintenance_type' => $_REQUEST['maintenance_type'], 'description' => $_REQUEST['description'], 'active_since' => $active_since, 'active_till' => $active_till, 'timeperiods' => get_request('timeperiods', array()), 'hostids' => get_request('hostids', array()), 'groupids' => get_request('groupids', array()) ); if (isset($_REQUEST['maintenanceid'])) { $maintenance['maintenanceid'] = $_REQUEST['maintenanceid']; $result = API::Maintenance()->update($maintenance); } else { $result = API::Maintenance()->create($maintenance); } if ($result) { add_audit(!isset($_REQUEST['maintenanceid']) ? AUDIT_ACTION_ADD : AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_MAINTENANCE, _('Name').': '.$_REQUEST['mname']); unset($_REQUEST['form']); } show_messages($result, $msg1, $msg2); } else { show_error_message($msg2); } } elseif (isset($_REQUEST['delete']) || $_REQUEST['go'] == 'delete') { if (!count(get_accessible_nodes_by_user($USER_DETAILS, PERM_READ_WRITE, PERM_RES_IDS_ARRAY))) { access_deny(); } $maintenanceids = get_request('maintenanceid', array()); if (isset($_REQUEST['maintenanceids'])) { $maintenanceids = $_REQUEST['maintenanceids']; } zbx_value2array($maintenanceids); $maintenances = array(); foreach ($maintenanceids as $id => $maintenanceid) { $maintenances[$maintenanceid] = get_maintenance_by_maintenanceid($maintenanceid); } $go_result = API::Maintenance()->delete($maintenanceids); if ($go_result) { foreach ($maintenances as $maintenanceid => $maintenance) { add_audit(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_MAINTENANCE, 'Id ['.$maintenanceid.'] '._('Name').' ['.$maintenance['name'].']'); } unset($_REQUEST['form'], $_REQUEST['maintenanceid']); } show_messages($go_result, _('Maintenance deleted'), _('Cannot delete maintenance')); } elseif (isset($_REQUEST['add_timeperiod']) && isset($_REQUEST['new_timeperiod'])) { $new_timeperiod = $_REQUEST['new_timeperiod']; $new_timeperiod['start_date'] = zbxDateToTime($new_timeperiod['start_date']); // start time $new_timeperiod['start_time'] = ($new_timeperiod['hour'] * SEC_PER_HOUR) + ($new_timeperiod['minute'] * SEC_PER_MIN); // period $new_timeperiod['period'] = ($new_timeperiod['period_days'] * SEC_PER_DAY) + ($new_timeperiod['period_hours'] * SEC_PER_HOUR) + ($new_timeperiod['period_minutes'] * SEC_PER_MIN); // days of week if (!isset($new_timeperiod['dayofweek'])) { $dayofweek = (!isset($new_timeperiod['dayofweek_su'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_sa'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_fr'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_th'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_we'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_tu'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_mo'])) ? '0' : '1'; $new_timeperiod['dayofweek'] = bindec($dayofweek); } // months if (!isset($new_timeperiod['month'])) { $month = (!isset($new_timeperiod['month_dec'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_nov'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_oct'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_sep'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_aug'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_jul'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_jun'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_may'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_apr'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_mar'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_feb'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_jan'])) ? '0' : '1'; $new_timeperiod['month'] = bindec($month); } if ($new_timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_MONTHLY) { if ($new_timeperiod['month_date_type'] > 0) { $new_timeperiod['day'] = 0; } else { $new_timeperiod['every'] = 0; $new_timeperiod['dayofweek'] = 0; } } $_REQUEST['timeperiods'] = get_request('timeperiods', array()); $result = false; if ($new_timeperiod['period'] < 300) { info(_('Incorrect maintenance period (minimum 5 minutes)')); } elseif ($new_timeperiod['hour'] > 23 || $new_timeperiod['minute'] > 59) { info(_('Incorrect maintenance period')); } elseif ($new_timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_ONETIME && $new_timeperiod['start_date'] < 1) { error(_('Incorrect maintenance - date must be between 1970.01.01 and 2038.01.18')); } elseif ($new_timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_DAILY && $new_timeperiod['every'] < 1) { info(_('Incorrect maintenance day period')); } elseif ($new_timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_WEEKLY) { if ($new_timeperiod['every'] < 1) { info(_('Incorrect maintenance week period')); } elseif ($new_timeperiod['dayofweek'] < 1) { info(_('Incorrect maintenance days of week')); } else { $result = true; } } elseif ($new_timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_MONTHLY) { if ($new_timeperiod['month'] < 1) { info(_('Incorrect maintenance month period')); } elseif ($new_timeperiod['day'] == 0 && $new_timeperiod['dayofweek'] < 1) { info(_('Incorrect maintenance days of week')); } elseif (($new_timeperiod['day'] < 1 || $new_timeperiod['day'] > 31) && $new_timeperiod['dayofweek'] == 0) { info(_('Incorrect maintenance date')); } else { $result = true; } } else { $result = true; } show_messages(); if ($result) { if (!isset($new_timeperiod['id'])) { if (!str_in_array($new_timeperiod, $_REQUEST['timeperiods'])) { array_push($_REQUEST['timeperiods'], $new_timeperiod); } } else { $id = $new_timeperiod['id']; unset($new_timeperiod['id']); $_REQUEST['timeperiods'][$id] = $new_timeperiod; } unset($_REQUEST['new_timeperiod']); } } elseif (isset($_REQUEST['del_timeperiod']) && isset($_REQUEST['g_timeperiodid'])) { $_REQUEST['timeperiods'] = get_request('timeperiods', array()); foreach ($_REQUEST['g_timeperiodid'] as $val) { unset($_REQUEST['timeperiods'][$val]); } } elseif (isset($_REQUEST['edit_timeperiodid'])) { $_REQUEST['edit_timeperiodid'] = array_keys($_REQUEST['edit_timeperiodid']); $edit_timeperiodid = $_REQUEST['edit_timeperiodid'] = array_pop($_REQUEST['edit_timeperiodid']); $_REQUEST['timeperiods'] = get_request('timeperiods', array()); if (isset($_REQUEST['timeperiods'][$edit_timeperiodid])) { $_REQUEST['new_timeperiod'] = $_REQUEST['timeperiods'][$edit_timeperiodid]; $_REQUEST['new_timeperiod']['id'] = $edit_timeperiodid; $_REQUEST['new_timeperiod']['start_date'] = date('YmdHi', $_REQUEST['timeperiods'][$edit_timeperiodid]['start_date']); } } if ($_REQUEST['go'] != 'none' && !empty($go_result)) { $url = new CUrl(); $path = $url->getPath(); insert_js('cookie.eraseArray("'.$path.'")'); } $options = array( 'groups' => array('editable' => 1), 'groupid' => get_request('groupid', null) ); $pageFilter = new CPageFilter($options); $_REQUEST['groupid'] = $pageFilter->groupid; /* * Display */ $data = array('form' => get_request('form')); if (!empty($data['form'])) { $data['maintenanceid'] = get_request('maintenanceid'); $data['form_refresh'] = get_request('form_refresh', 0); if (!empty($data['maintenanceid']) && !isset($_REQUEST['form_refresh'])) { // get maintenance $options = array( 'editable' => true, 'maintenanceids' => $data['maintenanceid'], 'output' => API_OUTPUT_EXTEND ); $maintenance = API::Maintenance()->get($options); $maintenance = reset($maintenance); $data['mname'] = $maintenance['name']; $data['maintenance_type'] = $maintenance['maintenance_type']; $data['active_since'] = $maintenance['active_since']; $data['active_till'] = $maintenance['active_till']; $data['description'] = $maintenance['description']; // get time periods $data['timeperiods'] = array(); $sql = 'SELECT DISTINCT mw.maintenanceid,tp.*'. ' FROM timeperiods tp,maintenances_windows mw'. ' WHERE mw.maintenanceid='.$data['maintenanceid']. ' AND tp.timeperiodid=mw.timeperiodid'. ' ORDER BY tp.timeperiod_type,tp.start_date'; $db_timeperiods = DBselect($sql); while ($timeperiod = DBfetch($db_timeperiods)) { $data['timeperiods'][] = $timeperiod; } // get hosts $options = array( 'maintenanceids' => $data['maintenanceid'], 'real_hosts' => true, 'output' => API_OUTPUT_SHORTEN, 'editable' => true ); $data['hostids'] = API::Host()->get($options); $data['hostids'] = zbx_objectValues($data['hostids'], 'hostid'); // get groupids $options = array( 'maintenanceids' => $data['maintenanceid'], 'real_hosts' => true, 'output' => API_OUTPUT_SHORTEN, 'editable' => true ); $data['groupids'] = API::HostGroup()->get($options); $data['groupids'] = zbx_objectValues($data['groupids'], 'groupid'); } else { $data['mname'] = get_request('mname', ''); $data['maintenance_type'] = get_request('maintenance_type', 0); $data['active_since'] = zbxDateToTime(get_request('active_since', date('YmdHi'))); $data['active_till'] = zbxDateToTime(get_request('active_till', date('YmdHi', time() + SEC_PER_DAY))); $data['description'] = get_request('description', ''); $data['timeperiods'] = get_request('timeperiods', array()); $data['hostids'] = get_request('hostids', array()); $data['groupids'] = get_request('groupids', array()); } // get groups $options = array( 'editable' => true, 'output' => array('groupid', 'name'), 'real_hosts' => true, 'preservekeys' => true ); $data['all_groups'] = API::HostGroup()->get($options); order_result($data['all_groups'], 'name'); $data['twb_groupid'] = get_request('twb_groupid', 0); if (!isset($data['all_groups'][$data['twb_groupid']])) { $twb_groupid = reset($data['all_groups']); $data['twb_groupid'] = $twb_groupid['groupid']; } // get hosts from selected twb group $options = array( 'output' => array('hostid', 'name'), 'real_hosts' => 1, 'editable' => 1, 'groupids' => $data['twb_groupid'] ); $data['hosts'] = API::Host()->get($options); // selected hosts $options = array( 'output' => array('hostid', 'name'), 'real_hosts' => 1, 'editable' => 1, 'hostids' => $data['hostids'] ); $hosts_selected = API::Host()->get($options); $data['hosts'] = array_merge($data['hosts'], $hosts_selected); $data['hosts'] = zbx_toHash($data['hosts'], 'hostid'); order_result($data['hosts'], 'name'); // render view $maintenanceView = new CView('configuration.maintenance.edit', $data); $maintenanceView->render(); $maintenanceView->show(); } else { // get maintenances $sortfield = getPageSortField('name'); $sortorder = getPageSortOrder(); $options = array( 'output' => API_OUTPUT_EXTEND, 'editable' => 1, 'sortfield' => $sortfield, 'sortorder' => $sortorder, 'limit' => $config['search_limit'] + 1 ); if ($pageFilter->groupsSelected) { if ($pageFilter->groupid > 0) { $options['groupids'] = $pageFilter->groupid; } else { $options['groupids'] = array_keys($pageFilter->groups); } } else { $options['groupids'] = array(); } $data['maintenances'] = API::Maintenance()->get($options); foreach ($data['maintenances'] as $number => $maintenance) { if ($maintenance['active_till'] < time()) { $data['maintenances'][$number]['status'] = MAINTENANCE_STATUS_EXPIRED; } elseif ($maintenance['active_since'] > time()) { $data['maintenances'][$number]['status'] = MAINTENANCE_STATUS_APPROACH; } else { $data['maintenances'][$number]['status'] = MAINTENANCE_STATUS_ACTIVE; } } order_result($data['maintenances'], $sortfield, $sortorder); $data['paging'] = getPagingLine($data['maintenances']); $data['pageFilter'] = $pageFilter; // render view $maintenanceView = new CView('configuration.maintenance.list', $data); $maintenanceView->render(); $maintenanceView->show(); } require_once dirname(__FILE__).'/include/page_footer.php'; ?>
gheja/zabbix-ext
frontends/php/maintenance.php
PHP
gpl-2.0
16,900
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program; if not, write to the Free Software // // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetradapp.editor; import edu.cmu.tetrad.session.SessionModel; import edu.cmu.tetrad.util.Parameters; import edu.cmu.tetradapp.model.DataWrapper; import edu.cmu.tetradapp.model.GeneralAlgorithmRunner; import edu.cmu.tetradapp.model.GraphSource; import edu.cmu.tetradapp.model.Simulation; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.LinkedList; import java.util.List; /** * Edits the parameters for generating random graphs. * * @author Joseph Ramsey */ public class EdgewiseComparisonParamsEditor extends JPanel implements ParameterEditor { /** * The parameters object being edited. */ private Parameters params = null; /** * The first graph source. */ private SessionModel model1; /** * The second graph source. */ private SessionModel model2; /** * The parent models. These should be graph sources. */ private Object[] parentModels; public void setParams(Parameters params) { if (params == null) { throw new NullPointerException(); } this.params = params; } public void setParentModels(Object[] parentModels) { this.parentModels = parentModels; } public boolean mustBeShown() { return false; } public void setup() { List<GraphSource> graphSources = new LinkedList<>(); for (Object parentModel : parentModels) { if (parentModel instanceof GraphSource) { graphSources.add((GraphSource) parentModel); } } if (graphSources.size() == 1 && graphSources.get(0) instanceof GeneralAlgorithmRunner) { model1 = (GeneralAlgorithmRunner) graphSources.get(0); model2 = ((GeneralAlgorithmRunner) model1).getDataWrapper(); } else if (graphSources.size() == 2) { model1 = (SessionModel) graphSources.get(0); model2 = (SessionModel) graphSources.get(1); } else { throw new IllegalArgumentException("Expecting 2 graph source."); } setLayout(new BorderLayout()); // Reset? JRadioButton resetOnExecute = new JRadioButton("Reset"); JRadioButton dontResetOnExecute = new JRadioButton("Appended to"); ButtonGroup group1 = new ButtonGroup(); group1.add(resetOnExecute); group1.add(dontResetOnExecute); resetOnExecute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getParams().set("resetTableOnExecute", true); } }); dontResetOnExecute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getParams().set("resetTableOnExecute", false); } }); if (getParams().getBoolean("resetTableOnExecute", false)) { resetOnExecute.setSelected(true); } else { dontResetOnExecute.setSelected(true); } // Latents? JRadioButton latents = new JRadioButton("Yes"); JRadioButton noLatents = new JRadioButton("No"); ButtonGroup group2 = new ButtonGroup(); group2.add(latents); group2.add(noLatents); latents.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getParams().set("keepLatents", true); } }); if (getParams().getBoolean("keepLatents", false)) { latents.setSelected(true); } else { noLatents.setSelected(true); } // True graph? JRadioButton graph1 = new JRadioButton(model1.getName()); JRadioButton graph2 = new JRadioButton(model2.getName()); graph1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getParams().set("referenceGraphName", model1.getName()); getParams().set("targetGraphName", model2.getName()); } }); graph2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getParams().set("referenceGraphName", model2.getName()); getParams().set("targetGraphName", model1.getName()); } }); ButtonGroup group = new ButtonGroup(); group.add(graph1); group.add(graph2); boolean alreadySet = false; if (model1 instanceof GeneralAlgorithmRunner) { graph1.setSelected(true); } if (model2 instanceof GeneralAlgorithmRunner) { graph2.setSelected(true); alreadySet = true; } if (model2 instanceof Simulation) { graph2.setSelected(true); alreadySet = true; } if (!alreadySet) { graph1.setSelected(true); } if (graph1.isSelected()) { getParams().set("referenceGraphName", model1.getName()); getParams().set("targetGraphName", model2.getName()); } else if (graph2.isSelected()) { getParams().set("referenceGraphName", model2.getName()); getParams().set("targetGraphName", model1.getName()); } Box b1 = Box.createVerticalBox(); Box b8 = Box.createHorizontalBox(); b8.add(new JLabel("Which of the two input graphs is the true graph?")); b8.add(Box.createHorizontalGlue()); b1.add(b8); Box b9 = Box.createHorizontalBox(); b9.add(graph1); b9.add(Box.createHorizontalGlue()); b1.add(b9); Box b10 = Box.createHorizontalBox(); b10.add(graph2); b10.add(Box.createHorizontalGlue()); b1.add(b10); b1.add(Box.createHorizontalGlue()); add(b1, BorderLayout.CENTER); } /** * @return the getMappings object being edited. (This probably should not be * public, but it is needed so that the textfields can edit the model.) */ private synchronized Parameters getParams() { return this.params; } }
ekummerfeld/tetrad
tetrad-gui/src/main/java/edu/cmu/tetradapp/editor/EdgewiseComparisonParamsEditor.java
Java
gpl-2.0
7,810
/* * Copyright 2007 Yusuke Yamamoto * * 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. */ package twitter4j; import java.util.Date; /** * A data interface representing one single status of a user. * * @author Yusuke Yamamoto - yusuke at mac.com */ public interface Status extends Comparable<Status>, TwitterResponse, EntitySupport, java.io.Serializable { /** * Return the created_at * * @return created_at * @since Twitter4J 1.1.0 */ Date getCreatedAt(); /** * Returns the id of the status * * @return the id */ long getId(); /** * Returns the text of the status * * @return the text */ String getText(); /** * Returns the source * * @return the source * @since Twitter4J 1.0.4 */ String getSource(); /** * Test if the status is truncated * * @return true if truncated * @since Twitter4J 1.0.4 */ boolean isTruncated(); /** * Returns the in_reply_tostatus_id * * @return the in_reply_tostatus_id * @since Twitter4J 1.0.4 */ long getInReplyToStatusId(); /** * Returns the in_reply_user_id * * @return the in_reply_tostatus_id * @since Twitter4J 1.0.4 */ long getInReplyToUserId(); /** * Returns the in_reply_to_screen_name * * @return the in_in_reply_to_screen_name * @since Twitter4J 2.0.4 */ String getInReplyToScreenName(); /** * Returns The location that this tweet refers to if available. * * @return returns The location that this tweet refers to if available (can be null) * @since Twitter4J 2.1.0 */ GeoLocation getGeoLocation(); /** * Returns the place attached to this status * * @return The place attached to this status * @since Twitter4J 2.1.1 */ Place getPlace(); /** * Test if the status is favorited * * @return true if favorited * @since Twitter4J 1.0.4 */ boolean isFavorited(); /** * Test if the status is retweeted * * @return true if retweeted * @since Twitter4J 3.0.4 */ boolean isRetweeted(); /** * Indicates approximately how many times this Tweet has been "favorited" by Twitter users. * * @return the favorite count * @since Twitter4J 3.0.4 */ int getFavoriteCount(); /** * Return the user associated with the status.<br> * This can be null if the instance if from User.getStatus(). * * @return the user */ User getUser(); /** * @since Twitter4J 2.0.10 */ boolean isRetweet(); /** * @since Twitter4J 2.1.0 */ Status getRetweetedStatus(); /** * Returns an array of contributors, or null if no contributor is associated with this status. * * @since Twitter4J 2.2.3 */ long[] getContributors(); /** * Returns the number of times this tweet has been retweeted, or -1 when the tweet was * created before this feature was enabled. * * @return the retweet count. */ int getRetweetCount(); /** * Returns true if the authenticating user has retweeted this tweet, or false when the tweet was * created before this feature was enabled. * * @return whether the authenticating user has retweeted this tweet. * @since Twitter4J 2.1.4 */ boolean isRetweetedByMe(); /** * Returns the authenticating user's retweet's id of this tweet, or -1L when the tweet was created * before this feature was enabled. * * @return the authenticating user's retweet's id of this tweet * @since Twitter4J 3.0.1 */ long getCurrentUserRetweetId(); /** * Returns true if the status contains a link that is identified as sensitive. * * @return whether the status contains sensitive links * @since Twitter4J 3.0.0 */ boolean isPossiblySensitive(); /** * Returns the lang of the status text if available. * * @return two-letter iso language code * @since Twitter4J 3.0.6 */ String getLang(); /** * Returns the targeting scopes applied to a status. * * @return the targeting scopes applied to a status. * @since Twitter4J 3.0.6 */ Scopes getScopes(); }
jonathanmcelroy/DataCommunicationsProgram456
twitter4j/twitter4j-core/src/main/java/twitter4j/Status.java
Java
gpl-2.0
4,909
/* Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.com/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Instance_Uldaman SD%Complete: 60 SDComment: SDCategory: Uldaman EndScriptData */ #include "precompiled.h" #include "uldaman.h" instance_uldaman::instance_uldaman(Map* pMap) : ScriptedInstance(pMap), m_uiStoneKeepersFallen(0), m_uiKeeperCooldown(5000) { Initialize(); } void instance_uldaman::Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); } void instance_uldaman::OnObjectCreate(GameObject* pGo) { switch(pGo->GetEntry()) { case GO_TEMPLE_DOOR_UPPER: if (m_auiEncounter[0] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_TEMPLE_DOOR_LOWER: if (m_auiEncounter[0] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_ANCIENT_VAULT: if (m_auiEncounter[1] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; default: return; } m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid(); } void instance_uldaman::OnCreatureCreate(Creature* pCreature) { switch(pCreature->GetEntry()) { case NPC_HALLSHAPER: case NPC_CUSTODIAN: case NPC_GUARDIAN: case NPC_VAULT_WARDER: m_lWardens.push_back(pCreature->GetObjectGuid()); pCreature->SetNoCallAssistance(true); // no assistance break; case NPC_STONE_KEEPER: // FIXME - This isAlive check is currently useless m_mKeeperMap[pCreature->GetObjectGuid()] = pCreature->isAlive(); pCreature->SetNoCallAssistance(true); // no assistance break; default: break; } } void instance_uldaman::SetData(uint32 uiType, uint32 uiData) { switch(uiType) { case TYPE_ALTAR_EVENT: if (uiData == DONE) { DoUseDoorOrButton(GO_TEMPLE_DOOR_UPPER); DoUseDoorOrButton(GO_TEMPLE_DOOR_LOWER); m_auiEncounter[0] = uiData; } break; case TYPE_ARCHAEDAS: if (uiData == FAIL) { for (GuidList::const_iterator itr = m_lWardens.begin(); itr != m_lWardens.end(); ++itr) { if (Creature* pWarden = instance->GetCreature(*itr)) { pWarden->SetDeathState(JUST_DIED); pWarden->Respawn(); pWarden->SetNoCallAssistance(true); } } } else if (uiData == DONE) { for (GuidList::const_iterator itr = m_lWardens.begin(); itr != m_lWardens.end(); ++itr) { Creature* pWarden = instance->GetCreature(*itr); if (pWarden && pWarden->isAlive()) pWarden->ForcedDespawn(); } DoUseDoorOrButton(GO_ANCIENT_VAULT); } m_auiEncounter[1] = uiData; break; } if (uiData == DONE) { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1]; m_strInstData = saveStream.str(); SaveToDB(); OUT_SAVE_INST_DATA_COMPLETE; } } void instance_uldaman::Load(const char* chrIn) { if (!chrIn) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(chrIn); std::istringstream loadStream(chrIn); loadStream >> m_auiEncounter[0] >> m_auiEncounter[1]; for(uint8 i = 0; i < MAX_ENCOUNTER; ++i) { if (m_auiEncounter[i] == IN_PROGRESS) m_auiEncounter[i] = NOT_STARTED; } OUT_LOAD_INST_DATA_COMPLETE; } void instance_uldaman::SetData64(uint32 uiData, uint64 uiGuid) { switch(uiData) { case DATA_EVENT_STARTER: m_playerGuid = ObjectGuid(uiGuid); break; } } uint32 instance_uldaman::GetData(uint32 uiType) { switch(uiType) { case TYPE_ARCHAEDAS: return m_auiEncounter[1]; } return 0; } uint64 instance_uldaman::GetData64(uint32 uiData) { switch(uiData) { case DATA_EVENT_STARTER: return m_playerGuid.GetRawValue(); } return 0; } void instance_uldaman::StartEvent(uint32 uiEventId, Player* pPlayer) { m_playerGuid = pPlayer->GetObjectGuid(); if (uiEventId == EVENT_ID_ALTAR_KEEPER) { if (m_auiEncounter[0] == NOT_STARTED) m_auiEncounter[0] = IN_PROGRESS; } else if (m_auiEncounter[1] == NOT_STARTED || m_auiEncounter[1] == FAIL) m_auiEncounter[1] = SPECIAL; } void instance_uldaman::DoResetKeeperEvent() { m_auiEncounter[0] = NOT_STARTED; m_uiStoneKeepersFallen = 0; for (std::map<ObjectGuid, bool>::iterator itr = m_mKeeperMap.begin(); itr != m_mKeeperMap.end(); ++itr) { if (Creature* pKeeper = instance->GetCreature(itr->first)) { pKeeper->SetDeathState(JUST_DIED); pKeeper->Respawn(); pKeeper->SetNoCallAssistance(true); itr->second = true; } } } Creature* instance_uldaman::GetClosestDwarfNotInCombat(Creature* pSearcher, uint32 uiPhase) { std::list<Creature*> lTemp; for (GuidList::const_iterator itr = m_lWardens.begin(); itr != m_lWardens.end(); ++itr) { Creature* pTemp = instance->GetCreature(*itr); if (pTemp && pTemp->isAlive() && !pTemp->getVictim()) { switch(uiPhase) { case PHASE_ARCHA_1: if (pTemp->GetEntry() != NPC_CUSTODIAN && pTemp->GetEntry() != NPC_HALLSHAPER) continue; break; case PHASE_ARCHA_2: if (pTemp->GetEntry() != NPC_GUARDIAN) continue; break; case PHASE_ARCHA_3: if (pTemp->GetEntry() != NPC_VAULT_WARDER) continue; break; } lTemp.push_back(pTemp); } } if (lTemp.empty()) return NULL; lTemp.sort(ObjectDistanceOrder(pSearcher)); return lTemp.front(); } void instance_uldaman::Update(uint32 uiDiff) { if (m_auiEncounter[0] == IN_PROGRESS) { if (m_uiKeeperCooldown >= uiDiff) m_uiKeeperCooldown -= uiDiff; else { m_uiKeeperCooldown = 5000; if (!m_mKeeperMap.empty()) { for(std::map<ObjectGuid, bool>::iterator itr = m_mKeeperMap.begin(); itr != m_mKeeperMap.end(); ++itr) { // died earlier if (!itr->second) continue; if (Creature* pKeeper = instance->GetCreature(itr->first)) { if (pKeeper->isAlive() && !pKeeper->getVictim()) { if (Player* pPlayer = pKeeper->GetMap()->GetPlayer(m_playerGuid)) { // we should use group instead, event starter can be dead while group is still fighting if (pPlayer->isAlive() && !pPlayer->isInCombat()) { pKeeper->RemoveAurasDueToSpell(SPELL_STONED); pKeeper->SetInCombatWith(pPlayer); pKeeper->AddThreat(pPlayer); } else { if (!pPlayer->isAlive()) DoResetKeeperEvent(); } } break; } else if (!pKeeper->isAlive()) { itr->second = pKeeper->isAlive(); ++m_uiStoneKeepersFallen; } } } if (m_uiStoneKeepersFallen == m_mKeeperMap.size()) SetData(TYPE_ALTAR_EVENT, DONE); } } } } InstanceData* GetInstanceData_instance_uldaman(Map* pMap) { return new instance_uldaman(pMap); } bool ProcessEventId_event_spell_altar_boss_aggro(uint32 uiEventId, Object* pSource, Object* pTarget, bool bIsStart) { if (bIsStart && pSource->GetTypeId() == TYPEID_PLAYER) { if (instance_uldaman* pInstance = (instance_uldaman*)((Player*)pSource)->GetInstanceData()) { pInstance->StartEvent(uiEventId, (Player*)pSource); return true; } } return false; } void AddSC_instance_uldaman() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "instance_uldaman"; pNewScript->GetInstanceData = &GetInstanceData_instance_uldaman; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "event_spell_altar_boss_aggro"; pNewScript->pProcessEventId = &ProcessEventId_event_spell_altar_boss_aggro; pNewScript->RegisterSelf(); }
Remix99/MaNGOS
src/bindings/scriptdev2/scripts/eastern_kingdoms/uldaman/instance_uldaman.cpp
C++
gpl-2.0
10,144
// This file is part of par2cmdline (a PAR 2.0 compatible file verification and // repair tool). See http://parchive.sourceforge.net for details of PAR 2.0. // // Copyright (c) 2003 Peter Brian Clements // // par2cmdline is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // par2cmdline is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "par2cmdline.h" #ifdef _MSC_VER #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #endif Par2Creator::Par2Creator(void) : noiselevel(CommandLine::nlUnknown) , blocksize(0) , chunksize(0) , inputbuffer(0) , outputbuffer(0) , sourcefilecount(0) , sourceblockcount(0) , largestfilesize(0) , recoveryfilescheme(CommandLine::scUnknown) , recoveryfilecount(0) , recoveryblockcount(0) , firstrecoveryblock(0) , mainpacket(0) , creatorpacket(0) , deferhashcomputation(false) { } Par2Creator::~Par2Creator(void) { delete mainpacket; delete creatorpacket; delete [] (u8*)inputbuffer; delete [] (u8*)outputbuffer; vector<Par2CreatorSourceFile*>::iterator sourcefile = sourcefiles.begin(); while (sourcefile != sourcefiles.end()) { delete *sourcefile; ++sourcefile; } } Result Par2Creator::Process(const CommandLine &commandline) { // Get information from commandline noiselevel = commandline.GetNoiseLevel(); blocksize = commandline.GetBlockSize(); sourceblockcount = commandline.GetBlockCount(); const list<CommandLine::ExtraFile> extrafiles = commandline.GetExtraFiles(); sourcefilecount = (u32)extrafiles.size(); u32 redundancy = commandline.GetRedundancy(); recoveryblockcount = commandline.GetRecoveryBlockCount(); recoveryfilecount = commandline.GetRecoveryFileCount(); firstrecoveryblock = commandline.GetFirstRecoveryBlock(); recoveryfilescheme = commandline.GetRecoveryFileScheme(); string par2filename = commandline.GetParFilename(); size_t memorylimit = commandline.GetMemoryLimit(); largestfilesize = commandline.GetLargestSourceSize(); // Compute block size from block count or vice versa depending on which was // specified on the command line if (!ComputeBlockSizeAndBlockCount(extrafiles)) return eInvalidCommandLineArguments; // Determine how many recovery blocks to create based on the source block // count and the requested level of redundancy. if (redundancy > 0 && !ComputeRecoveryBlockCount(redundancy)) return eInvalidCommandLineArguments; // Determine how much recovery data can be computed on one pass if (!CalculateProcessBlockSize(memorylimit)) return eLogicError; // Determine how many recovery files to create. if (!ComputeRecoveryFileCount()) return eInvalidCommandLineArguments; if (noiselevel > CommandLine::nlQuiet) { // Display information. cout << "Block size: " << blocksize << endl; cout << "Source file count: " << sourcefilecount << endl; cout << "Source block count: " << sourceblockcount << endl; if (redundancy>0 || recoveryblockcount==0) cout << "Redundancy: " << redundancy << '%' << endl; cout << "Recovery block count: " << recoveryblockcount << endl; cout << "Recovery file count: " << recoveryfilecount << endl; cout << endl; } // Open all of the source files, compute the Hashes and CRC values, and store // the results in the file verification and file description packets. if (!OpenSourceFiles(extrafiles)) return eFileIOError; // Create the main packet and determine the setid to use with all packets if (!CreateMainPacket()) return eLogicError; // Create the creator packet. if (!CreateCreatorPacket()) return eLogicError; // Initialise all of the source blocks ready to start reading data from the source files. if (!CreateSourceBlocks()) return eLogicError; // Create all of the output files and allocate all packets to appropriate file offets. if (!InitialiseOutputFiles(par2filename)) return eFileIOError; if (recoveryblockcount > 0) { // Allocate memory buffers for reading and writing data to disk. if (!AllocateBuffers()) return eMemoryError; // Compute the Reed Solomon matrix if (!ComputeRSMatrix()) return eLogicError; // Set the total amount of data to be processed. progress = 0; totaldata = blocksize * sourceblockcount * recoveryblockcount; // Start at an offset of 0 within a block. u64 blockoffset = 0; while (blockoffset < blocksize) // Continue until the end of the block. { // Work out how much data to process this time. size_t blocklength = (size_t)min((u64)chunksize, blocksize-blockoffset); // Read source data, process it through the RS matrix and write it to disk. if (!ProcessData(blockoffset, blocklength)) return eFileIOError; blockoffset += blocklength; } if (noiselevel > CommandLine::nlQuiet) cout << "Writing recovery packets" << endl; // Finish computation of the recovery packets and write the headers to disk. if (!WriteRecoveryPacketHeaders()) return eFileIOError; // Finish computing the full file hash values of the source files if (!FinishFileHashComputation()) return eLogicError; } // Fill in all remaining details in the critical packets. if (!FinishCriticalPackets()) return eLogicError; if (noiselevel > CommandLine::nlQuiet) cout << "Writing verification packets" << endl; // Write all other critical packets to disk. if (!WriteCriticalPackets()) return eFileIOError; // Close all files. if (!CloseFiles()) return eFileIOError; if (noiselevel > CommandLine::nlSilent) cout << "Done" << endl; return eSuccess; } // Compute block size from block count or vice versa depending on which was // specified on the command line bool Par2Creator::ComputeBlockSizeAndBlockCount(const list<CommandLine::ExtraFile> &extrafiles) { // Determine blocksize from sourceblockcount or vice-versa if (blocksize > 0) { u64 count = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { count += (i->FileSize() + blocksize-1) / blocksize; } if (count > 32768) { cerr << "Block size is too small. It would require " << count << "blocks." << endl; return false; } sourceblockcount = (u32)count; } else if (sourceblockcount > 0) { if (sourceblockcount < extrafiles.size()) { // The block count cannot be less that the number of files. cerr << "Block count is too small." << endl; return false; } else if (sourceblockcount == extrafiles.size()) { // If the block count is the same as the number of files, then the block // size is the size of the largest file (rounded up to a multiple of 4). u64 largestsourcesize = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { if (largestsourcesize < i->FileSize()) { largestsourcesize = i->FileSize(); } } blocksize = (largestsourcesize + 3) & ~3; } else { u64 totalsize = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { totalsize += (i->FileSize() + 3) / 4; } if (sourceblockcount > totalsize) { sourceblockcount = (u32)totalsize; blocksize = 4; } else { // Absolute lower bound and upper bound on the source block size that will // result in the requested source block count. u64 lowerBound = totalsize / sourceblockcount; u64 upperBound = (totalsize + sourceblockcount - extrafiles.size() - 1) / (sourceblockcount - extrafiles.size()); u64 bestsize = lowerBound; u64 bestdistance = 1000000; u64 bestcount = 0; u64 count; u64 size; // Work out how many blocks you get for the lower bound block size { size = lowerBound; count = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { count += ((i->FileSize()+3)/4 + size-1) / size; } if (bestdistance > (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count)) { bestdistance = (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count); bestcount = count; bestsize = size; } } // Work out how many blocks you get for the upper bound block size { size = upperBound; count = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { count += ((i->FileSize()+3)/4 + size-1) / size; } if (bestdistance > (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count)) { bestdistance = (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count); bestcount = count; bestsize = size; } } // Use binary search to find best block size while (lowerBound+1 < upperBound) { size = (lowerBound + upperBound)/2; count = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { count += ((i->FileSize()+3)/4 + size-1) / size; } if (bestdistance > (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count)) { bestdistance = (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count); bestcount = count; bestsize = size; } if (count < sourceblockcount) { upperBound = size; } else if (count > sourceblockcount) { lowerBound = size; } else { upperBound = size; } } size = bestsize; count = bestcount; if (count > 32768) { cerr << "Error calculating block size." << endl; return false; } sourceblockcount = (u32)count; blocksize = size*4; } } } return true; } // Determine how many recovery blocks to create based on the source block // count and the requested level of redundancy. bool Par2Creator::ComputeRecoveryBlockCount(u32 redundancy) { // Determine recoveryblockcount recoveryblockcount = (sourceblockcount * redundancy + 50) / 100; // Force valid values if necessary if (recoveryblockcount == 0 && redundancy > 0) recoveryblockcount = 1; if (recoveryblockcount > 65536) { cerr << "Too many recovery blocks requested." << endl; return false; } // Check that the last recovery block number would not be too large if (firstrecoveryblock + recoveryblockcount >= 65536) { cerr << "First recovery block number is too high." << endl; return false; } return true; } // Determine how much recovery data can be computed on one pass bool Par2Creator::CalculateProcessBlockSize(size_t memorylimit) { // Are we computing any recovery blocks if (recoveryblockcount == 0) { deferhashcomputation = false; } else { // Would single pass processing use too much memory if (blocksize * recoveryblockcount > memorylimit) { // Pick a size that is small enough chunksize = ~3 & (memorylimit / recoveryblockcount); deferhashcomputation = false; } else { chunksize = (size_t)blocksize; deferhashcomputation = true; } } return true; } // Determine how many recovery files to create. bool Par2Creator::ComputeRecoveryFileCount(void) { // Are we computing any recovery blocks if (recoveryblockcount == 0) { recoveryfilecount = 0; return true; } switch (recoveryfilescheme) { case CommandLine::scUnknown: { assert(false); return false; } break; case CommandLine::scVariable: case CommandLine::scUniform: { if (recoveryfilecount == 0) { // If none specified then then filecount is roughly log2(blockcount) // This prevents you getting excessively large numbers of files // when the block count is high and also allows the files to have // sizes which vary exponentially. for (u32 blocks=recoveryblockcount; blocks>0; blocks>>=1) { recoveryfilecount++; } } if (recoveryfilecount > recoveryblockcount) { // You cannot have move recovery files that there are recovery blocks // to put in them. cerr << "Too many recovery files specified." << endl; return false; } } break; case CommandLine::scLimited: { // No recovery file will contain more recovery blocks than would // be required to reconstruct the largest source file if it // were missing. Other recovery files will have recovery blocks // distributed in an exponential scheme. u32 largest = (u32)((largestfilesize + blocksize-1) / blocksize); u32 whole = recoveryblockcount / largest; whole = (whole >= 1) ? whole-1 : 0; u32 extra = recoveryblockcount - whole * largest; recoveryfilecount = whole; for (u32 blocks=extra; blocks>0; blocks>>=1) { recoveryfilecount++; } } break; } return true; } // Open all of the source files, compute the Hashes and CRC values, and store // the results in the file verification and file description packets. bool Par2Creator::OpenSourceFiles(const list<CommandLine::ExtraFile> &extrafiles) { ExtraFileIterator extrafile = extrafiles.begin(); while (extrafile != extrafiles.end()) { Par2CreatorSourceFile *sourcefile = new Par2CreatorSourceFile; string path; string name; DiskFile::SplitFilename(extrafile->FileName(), path, name); if (noiselevel > CommandLine::nlSilent) cout << "Opening: " << name << endl; // Open the source file and compute its Hashes and CRCs. if (!sourcefile->Open(noiselevel, *extrafile, blocksize, deferhashcomputation)) { delete sourcefile; return false; } // Record the file verification and file description packets // in the critical packet list. sourcefile->RecordCriticalPackets(criticalpackets); // Add the source file to the sourcefiles array. sourcefiles.push_back(sourcefile); // Close the source file until its needed sourcefile->Close(); ++extrafile; } return true; } // Create the main packet and determine the setid to use with all packets bool Par2Creator::CreateMainPacket(void) { // Construct the main packet from the list of source files and the block size. mainpacket = new MainPacket; // Add the main packet to the list of critical packets. criticalpackets.push_back(mainpacket); // Create the packet (sourcefiles will get sorted into FileId order). return mainpacket->Create(sourcefiles, blocksize); } // Create the creator packet. bool Par2Creator::CreateCreatorPacket(void) { // Construct the creator packet creatorpacket = new CreatorPacket; // Create the packet return creatorpacket->Create(mainpacket->SetId()); } // Initialise all of the source blocks ready to start reading data from the source files. bool Par2Creator::CreateSourceBlocks(void) { // Allocate the array of source blocks sourceblocks.resize(sourceblockcount); vector<DataBlock>::iterator sourceblock = sourceblocks.begin(); for (vector<Par2CreatorSourceFile*>::iterator sourcefile = sourcefiles.begin(); sourcefile!= sourcefiles.end(); sourcefile++) { // Allocate the appopriate number of source blocks to each source file. // sourceblock will be advanced. (*sourcefile)->InitialiseSourceBlocks(sourceblock, blocksize); } return true; } class FileAllocation { public: FileAllocation(void) { filename = ""; exponent = 0; count = 0; } string filename; u32 exponent; u32 count; }; // Create all of the output files and allocate all packets to appropriate file offets. bool Par2Creator::InitialiseOutputFiles(string par2filename) { // Allocate the recovery packets recoverypackets.resize(recoveryblockcount); // Choose filenames and decide which recovery blocks to place in each file vector<FileAllocation> fileallocations; fileallocations.resize(recoveryfilecount+1); // One extra file with no recovery blocks { // Decide how many recovery blocks to place in each file u32 exponent = firstrecoveryblock; if (recoveryfilecount > 0) { switch (recoveryfilescheme) { case CommandLine::scUnknown: { assert(false); return false; } break; case CommandLine::scUniform: { // Files will have roughly the same number of recovery blocks each. u32 base = recoveryblockcount / recoveryfilecount; u32 remainder = recoveryblockcount % recoveryfilecount; for (u32 filenumber=0; filenumber<recoveryfilecount; filenumber++) { fileallocations[filenumber].exponent = exponent; fileallocations[filenumber].count = (filenumber<remainder) ? base+1 : base; exponent += fileallocations[filenumber].count; } } break; case CommandLine::scVariable: { // Files will have recovery blocks allocated in an exponential fashion. // Work out how many blocks to place in the smallest file u32 lowblockcount = 1; u32 maxrecoveryblocks = (1 << recoveryfilecount) - 1; while (maxrecoveryblocks < recoveryblockcount) { lowblockcount <<= 1; maxrecoveryblocks <<= 1; } // Allocate the blocks. u32 blocks = recoveryblockcount; for (u32 filenumber=0; filenumber<recoveryfilecount; filenumber++) { u32 number = min(lowblockcount, blocks); fileallocations[filenumber].exponent = exponent; fileallocations[filenumber].count = number; exponent += number; blocks -= number; lowblockcount <<= 1; } } break; case CommandLine::scLimited: { // Files will be allocated in an exponential fashion but the // Maximum file size will be limited. u32 largest = (u32)((largestfilesize + blocksize-1) / blocksize); u32 filenumber = recoveryfilecount; u32 blocks = recoveryblockcount; exponent = firstrecoveryblock + recoveryblockcount; // Allocate uniformly at the top while (blocks >= 2*largest && filenumber > 0) { filenumber--; exponent -= largest; blocks -= largest; fileallocations[filenumber].exponent = exponent; fileallocations[filenumber].count = largest; } assert(blocks > 0 && filenumber > 0); exponent = firstrecoveryblock; u32 count = 1; u32 files = filenumber; // Allocate exponentially at the bottom for (filenumber=0; filenumber<files; filenumber++) { u32 number = min(count, blocks); fileallocations[filenumber].exponent = exponent; fileallocations[filenumber].count = number; exponent += number; blocks -= number; count <<= 1; } } break; } } // There will be an extra file with no recovery blocks. fileallocations[recoveryfilecount].exponent = exponent; fileallocations[recoveryfilecount].count = 0; // Determine the format to use for filenames of recovery files char filenameformat[300]; { u32 limitLow = 0; u32 limitCount = 0; for (u32 filenumber=0; filenumber<=recoveryfilecount; filenumber++) { if (limitLow < fileallocations[filenumber].exponent) { limitLow = fileallocations[filenumber].exponent; } if (limitCount < fileallocations[filenumber].count) { limitCount = fileallocations[filenumber].count; } } u32 digitsLow = 1; for (u32 t=limitLow; t>=10; t/=10) { digitsLow++; } u32 digitsCount = 1; for (u32 t=limitCount; t>=10; t/=10) { digitsCount++; } sprintf(filenameformat, "%%s.vol%%0%dd+%%0%dd.par2", digitsLow, digitsCount); } // Set the filenames for (u32 filenumber=0; filenumber<recoveryfilecount; filenumber++) { char filename[300]; snprintf(filename, sizeof(filename), filenameformat, par2filename.c_str(), fileallocations[filenumber].exponent, fileallocations[filenumber].count); fileallocations[filenumber].filename = filename; } fileallocations[recoveryfilecount].filename = par2filename + ".par2"; } // Allocate the recovery files { recoveryfiles.resize(recoveryfilecount+1); // Allocate packets to the output files { const MD5Hash &setid = mainpacket->SetId(); vector<RecoveryPacket>::iterator recoverypacket = recoverypackets.begin(); vector<DiskFile>::iterator recoveryfile = recoveryfiles.begin(); vector<FileAllocation>::iterator fileallocation = fileallocations.begin(); // For each recovery file: while (recoveryfile != recoveryfiles.end()) { // How many recovery blocks in this file u32 count = fileallocation->count; // start at the beginning of the recovery file u64 offset = 0; if (count == 0) { // Write one set of critical packets list<CriticalPacket*>::const_iterator nextCriticalPacket = criticalpackets.begin(); while (nextCriticalPacket != criticalpackets.end()) { criticalpacketentries.push_back(CriticalPacketEntry(&*recoveryfile, offset, *nextCriticalPacket)); offset += (*nextCriticalPacket)->PacketLength(); ++nextCriticalPacket; } } else { // How many copies of each critical packet u32 copies = 0; for (u32 t=count; t>0; t>>=1) { copies++; } // Get ready to iterate through the critical packets u32 packetCount = 0; list<CriticalPacket*>::const_iterator nextCriticalPacket = criticalpackets.end(); // What is the first exponent u32 exponent = fileallocation->exponent; // Start allocating the recovery packets u32 limit = exponent + count; while (exponent < limit) { // Add the next recovery packet recoverypacket->Create(&*recoveryfile, offset, blocksize, exponent, setid); offset += recoverypacket->PacketLength(); ++recoverypacket; ++exponent; // Add some critical packets packetCount += copies * criticalpackets.size(); while (packetCount >= count) { if (nextCriticalPacket == criticalpackets.end()) nextCriticalPacket = criticalpackets.begin(); criticalpacketentries.push_back(CriticalPacketEntry(&*recoveryfile, offset, *nextCriticalPacket)); offset += (*nextCriticalPacket)->PacketLength(); ++nextCriticalPacket; packetCount -= count; } } } // Add one copy of the creator packet criticalpacketentries.push_back(CriticalPacketEntry(&*recoveryfile, offset, creatorpacket)); offset += creatorpacket->PacketLength(); // Create the file on disk and make it the required size if (!recoveryfile->Create(fileallocation->filename, offset)) return false; ++recoveryfile; ++fileallocation; } } } return true; } // Allocate memory buffers for reading and writing data to disk. bool Par2Creator::AllocateBuffers(void) { inputbuffer = new u8[chunksize]; outputbuffer = new u8[chunksize * recoveryblockcount]; if (inputbuffer == NULL || outputbuffer == NULL) { cerr << "Could not allocate buffer memory." << endl; return false; } return true; } // Compute the Reed Solomon matrix bool Par2Creator::ComputeRSMatrix(void) { // Set the number of input blocks if (!rs.SetInput(sourceblockcount)) return false; // Set the number of output blocks to be created if (!rs.SetOutput(false, (u16)firstrecoveryblock, (u16)firstrecoveryblock + (u16)(recoveryblockcount-1))) return false; // Compute the RS matrix if (!rs.Compute(noiselevel)) return false; return true; } // Read source data, process it through the RS matrix and write it to disk. bool Par2Creator::ProcessData(u64 blockoffset, size_t blocklength) { // Clear the output buffer memset(outputbuffer, 0, chunksize * recoveryblockcount); // If we have defered computation of the file hash and block crc and hashes // sourcefile and sourceindex will be used to update them during // the main recovery block computation vector<Par2CreatorSourceFile*>::iterator sourcefile = sourcefiles.begin(); u32 sourceindex = 0; vector<DataBlock>::iterator sourceblock; u32 inputblock; DiskFile *lastopenfile = NULL; // For each input block for ((sourceblock=sourceblocks.begin()),(inputblock=0); sourceblock != sourceblocks.end(); ++sourceblock, ++inputblock) { // Are we reading from a new file? if (lastopenfile != (*sourceblock).GetDiskFile()) { // Close the last file if (lastopenfile != NULL) { lastopenfile->Close(); } // Open the new file lastopenfile = (*sourceblock).GetDiskFile(); if (!lastopenfile->Open()) { return false; } } // Read data from the current input block if (!sourceblock->ReadData(blockoffset, blocklength, inputbuffer)) return false; if (deferhashcomputation) { assert(blockoffset == 0 && blocklength == blocksize); assert(sourcefile != sourcefiles.end()); (*sourcefile)->UpdateHashes(sourceindex, inputbuffer, blocklength); } // For each output block for (u32 outputblock=0; outputblock<recoveryblockcount; outputblock++) { // Select the appropriate part of the output buffer void *outbuf = &((u8*)outputbuffer)[chunksize * outputblock]; // Process the data through the RS matrix rs.Process(blocklength, inputblock, inputbuffer, outputblock, outbuf); if (noiselevel > CommandLine::nlQuiet) { // Update a progress indicator u32 oldfraction = (u32)(1000 * progress / totaldata); progress += blocklength; u32 newfraction = (u32)(1000 * progress / totaldata); if (oldfraction != newfraction) { cout << "Processing: " << newfraction/10 << '.' << newfraction%10 << "%\r" << flush; } } } // Work out which source file the next block belongs to if (++sourceindex >= (*sourcefile)->BlockCount()) { sourceindex = 0; ++sourcefile; } } // Close the last file if (lastopenfile != NULL) { lastopenfile->Close(); } if (noiselevel > CommandLine::nlQuiet) cout << "Writing recovery packets\r"; // For each output block for (u32 outputblock=0; outputblock<recoveryblockcount;outputblock++) { // Select the appropriate part of the output buffer char *outbuf = &((char*)outputbuffer)[chunksize * outputblock]; // Write the data to the recovery packet if (!recoverypackets[outputblock].WriteData(blockoffset, blocklength, outbuf)) return false; } if (noiselevel > CommandLine::nlQuiet) cout << "Wrote " << recoveryblockcount * blocklength << " bytes to disk" << endl; return true; } // Finish computation of the recovery packets and write the headers to disk. bool Par2Creator::WriteRecoveryPacketHeaders(void) { // For each recovery packet for (vector<RecoveryPacket>::iterator recoverypacket = recoverypackets.begin(); recoverypacket != recoverypackets.end(); ++recoverypacket) { // Finish the packet header and write it to disk if (!recoverypacket->WriteHeader()) return false; } return true; } bool Par2Creator::FinishFileHashComputation(void) { // If we defered the computation of the full file hash, then we finish it now if (deferhashcomputation) { // For each source file vector<Par2CreatorSourceFile*>::iterator sourcefile = sourcefiles.begin(); while (sourcefile != sourcefiles.end()) { (*sourcefile)->FinishHashes(); ++sourcefile; } } return true; } // Fill in all remaining details in the critical packets. bool Par2Creator::FinishCriticalPackets(void) { // Get the setid from the main packet const MD5Hash &setid = mainpacket->SetId(); for (list<CriticalPacket*>::iterator criticalpacket=criticalpackets.begin(); criticalpacket!=criticalpackets.end(); criticalpacket++) { // Store the setid in each of the critical packets // and compute the packet_hash of each one. (*criticalpacket)->FinishPacket(setid); } return true; } // Write all other critical packets to disk. bool Par2Creator::WriteCriticalPackets(void) { list<CriticalPacketEntry>::const_iterator packetentry = criticalpacketentries.begin(); // For each critical packet while (packetentry != criticalpacketentries.end()) { // Write it to disk if (!packetentry->WritePacket()) return false; ++packetentry; } return true; } // Close all files. bool Par2Creator::CloseFiles(void) { // // Close each source file. // for (vector<Par2CreatorSourceFile*>::iterator sourcefile = sourcefiles.begin(); // sourcefile != sourcefiles.end(); // ++sourcefile) // { // (*sourcefile)->Close(); // } // Close each recovery file. for (vector<DiskFile>::iterator recoveryfile = recoveryfiles.begin(); recoveryfile != recoveryfiles.end(); ++recoveryfile) { recoveryfile->Close(); } return true; }
jojje/par2cmdline-dir
par2creator.cpp
C++
gpl-2.0
31,351
<?php /** * english language file * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Christopher Smith <chris@jalakai.co.uk> * @author Matthias Schulte <dokuwiki@lupo49.de> * @author Schplurtz le Déboulonné <Schplurtz@laposte.net> */ // for admin plugins, the menu prompt to be displayed in the admin menu // if set here, the plugin doesn't need to override the getMenuText() method $lang['menu'] = 'Configuration Settings'; $lang['error'] = 'Settings not updated due to an invalid value, please review your changes and resubmit. <br />The incorrect value(s) will be shown surrounded by a red border.'; $lang['updated'] = 'Settings updated successfully.'; $lang['nochoice'] = '(no other choices available)'; $lang['locked'] = 'The settings file can not be updated, if this is unintentional, <br /> ensure the local settings file name and permissions are correct.'; $lang['danger'] = 'Danger: Changing this option could make your wiki and the configuration menu inaccessible.'; $lang['warning'] = 'Warning: Changing this option could cause unintended behaviour.'; $lang['security'] = 'Security Warning: Changing this option could present a security risk.'; /* --- Config Setting Headers --- */ $lang['_configuration_manager'] = 'Configuration Manager'; //same as heading in intro.txt $lang['_header_dokuwiki'] = 'DokuWiki'; $lang['_header_plugin'] = 'Plugin'; $lang['_header_template'] = 'Template'; $lang['_header_undefined'] = 'Undefined Settings'; /* --- Config Setting Groups --- */ $lang['_basic'] = 'Basic'; $lang['_display'] = 'Display'; $lang['_authentication'] = 'Authentication'; $lang['_anti_spam'] = 'Anti-Spam'; $lang['_editing'] = 'Editing'; $lang['_links'] = 'Links'; $lang['_media'] = 'Media'; $lang['_notifications'] = 'Notification'; $lang['_syndication'] = 'Syndication (RSS)'; $lang['_advanced'] = 'Advanced'; $lang['_network'] = 'Network'; /* --- Undefined Setting Messages --- */ $lang['_msg_setting_undefined'] = 'No setting metadata.'; $lang['_msg_setting_no_class'] = 'No setting class.'; $lang['_msg_setting_no_default'] = 'No default value.'; /* -------------------- Config Options --------------------------- */ /* Basic Settings */ $lang['title'] = 'Wiki title aka. your wiki\'s name'; $lang['start'] = 'Page name to use as the starting point for each namespace'; $lang['lang'] = 'Interface language'; $lang['template'] = 'Template aka. the design of the wiki.'; $lang['tagline'] = 'Tagline (if template supports it)'; $lang['sidebar'] = 'Sidebar page name (if template supports it), empty field disables the sidebar'; $lang['license'] = 'Under which license should your content be released?'; $lang['savedir'] = 'Directory for saving data'; $lang['basedir'] = 'Server path (eg. <code>/dokuwiki/</code>). Leave blank for autodetection.'; $lang['baseurl'] = 'Server URL (eg. <code>http://www.yourserver.com</code>). Leave blank for autodetection.'; $lang['cookiedir'] = 'Cookie path. Leave blank for using baseurl.'; $lang['dmode'] = 'Directory creation mode'; $lang['fmode'] = 'File creation mode'; $lang['allowdebug'] = 'Allow debug. <b>Disable if not needed!</b>'; /* Display Settings */ $lang['recent'] = 'Number of entries per page in the recent changes'; $lang['recent_days'] = 'How many recent changes to keep (days)'; $lang['breadcrumbs'] = 'Number of "trace" breadcrumbs. Set to 0 to disable.'; $lang['youarehere'] = 'Use hierarchical breadcrumbs (you probably want to disable the above option then)'; $lang['fullpath'] = 'Reveal full path of pages in the footer'; $lang['typography'] = 'Do typographical replacements'; $lang['dformat'] = 'Date format (see PHP\'s <a href="http://php.net/strftime">strftime</a> function)'; $lang['signature'] = 'What to insert with the signature button in the editor'; $lang['showuseras'] = 'What to display when showing the user that last edited a page'; $lang['toptoclevel'] = 'Top level for table of contents'; $lang['tocminheads'] = 'Minimum amount of headlines that determines whether the TOC is built'; $lang['maxtoclevel'] = 'Maximum level for table of contents'; $lang['maxseclevel'] = 'Maximum section edit level'; $lang['camelcase'] = 'Use CamelCase for links'; $lang['deaccent'] = 'How to clean pagenames'; $lang['useheading'] = 'Use first heading for pagenames'; $lang['sneaky_index'] = 'By default, DokuWiki will show all namespaces in the sitemap. Enabling this option will hide those where the user doesn\'t have read permissions. This might result in hiding of accessable subnamespaces which may make the index unusable with certain ACL setups.'; $lang['hidepages'] = 'Hide pages matching this regular expression from search, the sitemap and other automatic indexes'; /* Authentication Settings */ $lang['useacl'] = 'Use access control lists'; $lang['autopasswd'] = 'Autogenerate passwords'; $lang['authtype'] = 'Authentication backend'; $lang['passcrypt'] = 'Password encryption method'; $lang['defaultgroup']= 'Default group, all new users will be placed in this group'; $lang['superuser'] = 'Superuser - group, user or comma separated list user1,@group1,user2 with full access to all pages and functions regardless of the ACL settings'; $lang['manager'] = 'Manager - group, user or comma separated list user1,@group1,user2 with access to certain management functions'; $lang['profileconfirm'] = 'Confirm profile changes with password'; $lang['rememberme'] = 'Allow permanent login cookies (remember me)'; $lang['disableactions'] = 'Disable DokuWiki actions'; $lang['disableactions_check'] = 'Check'; $lang['disableactions_subscription'] = 'Subscribe/Unsubscribe'; $lang['disableactions_wikicode'] = 'View source/Export Raw'; $lang['disableactions_profile_delete'] = 'Delete Own Account'; $lang['disableactions_other'] = 'Other actions (comma separated)'; $lang['disableactions_rss'] = 'XML Syndication (RSS)'; $lang['auth_security_timeout'] = 'Authentication Security Timeout (seconds)'; $lang['securecookie'] = 'Should cookies set via HTTPS only be sent via HTTPS by the browser? Disable this option when only the login of your wiki is secured with SSL but browsing the wiki is done unsecured.'; $lang['remote'] = 'Enable the remote API system. This allows other applications to access the wiki via XML-RPC or other mechanisms.'; $lang['remoteuser'] = 'Restrict remote API access to the comma separated groups or users given here. Leave empty to give access to everyone.'; /* Anti-Spam Settings */ $lang['usewordblock']= 'Block spam based on wordlist'; $lang['relnofollow'] = 'Use rel="nofollow" on external links'; $lang['indexdelay'] = 'Time delay before indexing (sec)'; $lang['mailguard'] = 'Obfuscate email addresses'; $lang['iexssprotect']= 'Check uploaded files for possibly malicious JavaScript or HTML code'; /* Editing Settings */ $lang['usedraft'] = 'Automatically save a draft while editing'; $lang['htmlok'] = 'Allow embedded HTML'; $lang['phpok'] = 'Allow embedded PHP'; $lang['locktime'] = 'Maximum age for lock files (sec)'; $lang['cachetime'] = 'Maximum age for cache (sec)'; /* Link settings */ $lang['target____wiki'] = 'Target window for internal links'; $lang['target____interwiki'] = 'Target window for interwiki links'; $lang['target____extern'] = 'Target window for external links'; $lang['target____media'] = 'Target window for media links'; $lang['target____windows'] = 'Target window for windows links'; /* Media Settings */ $lang['mediarevisions'] = 'Enable Mediarevisions?'; $lang['refcheck'] = 'Check if a media file is still in use before deleting it'; $lang['gdlib'] = 'GD Lib version'; $lang['im_convert'] = 'Path to ImageMagick\'s convert tool'; $lang['jpg_quality'] = 'JPG compression quality (0-100)'; $lang['fetchsize'] = 'Maximum size (bytes) fetch.php may download from external URLs, eg. to cache and resize external images.'; /* Notification Settings */ $lang['subscribers'] = 'Allow users to subscribe to page changes by email'; $lang['subscribe_time'] = 'Time after which subscription lists and digests are sent (sec); This should be smaller than the time specified in recent_days.'; $lang['notify'] = 'Always send change notifications to this email address'; $lang['registernotify'] = 'Always send info on newly registered users to this email address'; $lang['mailfrom'] = 'Sender email address to use for automatic mails'; $lang['mailreturnpath'] = 'Recipient email address for non delivery notifications'; $lang['mailprefix'] = 'Email subject prefix to use for automatic mails. Leave blank to use the wiki title'; $lang['htmlmail'] = 'Send better looking, but larger in size HTML multipart emails. Disable for plain text only mails.'; /* Syndication Settings */ $lang['sitemap'] = 'Generate Google sitemap this often (in days). 0 to disable'; $lang['rss_type'] = 'XML feed type'; $lang['rss_linkto'] = 'XML feed links to'; $lang['rss_content'] = 'What to display in the XML feed items?'; $lang['rss_update'] = 'XML feed update interval (sec)'; $lang['rss_show_summary'] = 'XML feed show summary in title'; $lang['rss_media'] = 'What kind of changes should be listed in the XML feed?'; $lang['rss_media_o_both'] = 'both'; $lang['rss_media_o_pages'] = 'pages'; $lang['rss_media_o_media'] = 'media'; /* Advanced Options */ $lang['updatecheck'] = 'Check for updates and security warnings? DokuWiki needs to contact update.dokuwiki.org for this feature.'; $lang['userewrite'] = 'Use nice URLs'; $lang['useslash'] = 'Use slash as namespace separator in URLs'; $lang['sepchar'] = 'Page name word separator'; $lang['canonical'] = 'Use fully canonical URLs'; $lang['fnencode'] = 'Method for encoding non-ASCII filenames.'; $lang['autoplural'] = 'Check for plural forms in links'; $lang['compression'] = 'Compression method for attic files'; $lang['gzip_output'] = 'Use gzip Content-Encoding for xhtml'; $lang['compress'] = 'Compact CSS and javascript output'; $lang['cssdatauri'] = 'Size in bytes up to which images referenced in CSS files should be embedded right into the stylesheet to reduce HTTP request header overhead. <code>400</code> to <code>600</code> bytes is a good value. Set <code>0</code> to disable.'; $lang['send404'] = 'Send "HTTP 404/Page Not Found" for non existing pages'; $lang['broken_iua'] = 'Is the ignore_user_abort function broken on your system? This could cause a non working search index. IIS+PHP/CGI is known to be broken. See <a href="http://bugs.dokuwiki.org/?do=details&amp;task_id=852">Bug 852</a> for more info.'; $lang['xsendfile'] = 'Use the X-Sendfile header to let the webserver deliver static files? Your webserver needs to support this.'; $lang['renderer_xhtml'] = 'Renderer to use for main (xhtml) wiki output'; $lang['renderer__core'] = '%s (dokuwiki core)'; $lang['renderer__plugin'] = '%s (plugin)'; $lang['search_nslimit'] = 'Limit the search to the current X namespaces. When a search is executed from a page within a deeper namespace, the first X namespaces will be added as filter'; $lang['search_fragment'] = 'Specify the default fragment search behavior'; $lang['search_fragment_o_exact'] = 'exact'; $lang['search_fragment_o_starts_with'] = 'starts with'; $lang['search_fragment_o_ends_with'] = 'ends with'; $lang['search_fragment_o_contains'] = 'contains'; /* Network Options */ $lang['dnslookups'] = 'DokuWiki will lookup hostnames for remote IP addresses of users editing pages. If you have a slow or non working DNS server or don\'t want this feature, disable this option'; $lang['jquerycdn'] = 'Should the jQuery and jQuery UI script files be loaded from a CDN? This adds additional HTTP requests, but files may load faster and users may have them cached already.'; /* jQuery CDN options */ $lang['jquerycdn_o_0'] = 'No CDN, local delivery only'; $lang['jquerycdn_o_jquery'] = 'CDN at code.jquery.com'; $lang['jquerycdn_o_cdnjs'] = 'CDN at cdnjs.com'; /* Proxy Options */ $lang['proxy____host'] = 'Proxy servername'; $lang['proxy____port'] = 'Proxy port'; $lang['proxy____user'] = 'Proxy user name'; $lang['proxy____pass'] = 'Proxy password'; $lang['proxy____ssl'] = 'Use SSL to connect to proxy'; $lang['proxy____except'] = 'Regular expression to match URLs for which the proxy should be skipped.'; /* Safemode Hack */ $lang['safemodehack'] = 'Enable safemode hack'; $lang['ftp____host'] = 'FTP server for safemode hack'; $lang['ftp____port'] = 'FTP port for safemode hack'; $lang['ftp____user'] = 'FTP user name for safemode hack'; $lang['ftp____pass'] = 'FTP password for safemode hack'; $lang['ftp____root'] = 'FTP root directory for safemode hack'; /* License Options */ $lang['license_o_'] = 'None chosen'; /* typography options */ $lang['typography_o_0'] = 'none'; $lang['typography_o_1'] = 'excluding single quotes'; $lang['typography_o_2'] = 'including single quotes (might not always work)'; /* userewrite options */ $lang['userewrite_o_0'] = 'none'; $lang['userewrite_o_1'] = '.htaccess'; $lang['userewrite_o_2'] = 'DokuWiki internal'; /* deaccent options */ $lang['deaccent_o_0'] = 'off'; $lang['deaccent_o_1'] = 'remove accents'; $lang['deaccent_o_2'] = 'romanize'; /* gdlib options */ $lang['gdlib_o_0'] = 'GD Lib not available'; $lang['gdlib_o_1'] = 'Version 1.x'; $lang['gdlib_o_2'] = 'Autodetection'; /* rss_type options */ $lang['rss_type_o_rss'] = 'RSS 0.91'; $lang['rss_type_o_rss1'] = 'RSS 1.0'; $lang['rss_type_o_rss2'] = 'RSS 2.0'; $lang['rss_type_o_atom'] = 'Atom 0.3'; $lang['rss_type_o_atom1'] = 'Atom 1.0'; /* rss_content options */ $lang['rss_content_o_abstract'] = 'Abstract'; $lang['rss_content_o_diff'] = 'Unified Diff'; $lang['rss_content_o_htmldiff'] = 'HTML formatted diff table'; $lang['rss_content_o_html'] = 'Full HTML page content'; /* rss_linkto options */ $lang['rss_linkto_o_diff'] = 'difference view'; $lang['rss_linkto_o_page'] = 'the revised page'; $lang['rss_linkto_o_rev'] = 'list of revisions'; $lang['rss_linkto_o_current'] = 'the current page'; /* compression options */ $lang['compression_o_0'] = 'none'; $lang['compression_o_gz'] = 'gzip'; $lang['compression_o_bz2'] = 'bz2'; /* xsendfile header */ $lang['xsendfile_o_0'] = "don't use"; $lang['xsendfile_o_1'] = 'Proprietary lighttpd header (before release 1.5)'; $lang['xsendfile_o_2'] = 'Standard X-Sendfile header'; $lang['xsendfile_o_3'] = 'Proprietary Nginx X-Accel-Redirect header'; /* Display user info */ $lang['showuseras_o_loginname'] = 'Login name'; $lang['showuseras_o_username'] = "User's full name"; $lang['showuseras_o_username_link'] = "User's full name as interwiki user link"; $lang['showuseras_o_email'] = "User's e-mail addresss (obfuscated according to mailguard setting)"; $lang['showuseras_o_email_link'] = "User's e-mail addresss as a mailto: link"; /* useheading options */ $lang['useheading_o_0'] = 'Never'; $lang['useheading_o_navigation'] = 'Navigation Only'; $lang['useheading_o_content'] = 'Wiki Content Only'; $lang['useheading_o_1'] = 'Always'; $lang['readdircache'] = 'Maximum age for readdir cache (sec)';
randonnerleger/wiki_new
lib/plugins/config/lang/en/lang.php
PHP
gpl-2.0
15,290
<div class="weather"> <p><strong><?php print $weather->real_name; ?></strong></p> <div style="text-align:center;"> <img src="<?php print $weather->image_filename; ?>" <?php print $weather->image_size; ?> alt="<?php print $weather->condition; ?>" title="<?php print $weather->condition; ?>" /> </div> <ul> <li><?php print $weather->condition; ?></li> <?php if (isset($weather->temperature)): ?> <?php if (isset($weather->windchill)): ?> <li><?php print t("Temperature: !temperature1, feels like !temperature2", array( '!temperature1' => $weather->temperature, '!temperature2' => $weather->windchill )); ?></li> <?php else: ?> <li><?php print t("Temperature: !temperature", array('!temperature' => $weather->temperature)); ?></li> <?php endif ?> <?php endif ?> <?php if (isset($weather->wind)): ?> <li><?php print t('Wind: !wind', array('!wind' => $weather->wind)); ?></li> <?php endif ?> <?php if (isset($weather->pressure)): ?> <li><?php print t('Pressure: !pressure', array('!pressure' => $weather->pressure)); ?></li> <?php endif ?> <?php if (isset($weather->rel_humidity)): ?> <li><?php print t('Rel. Humidity: !rel_humidity', array('!rel_humidity' => $weather->rel_humidity)); ?></li> <?php endif ?> <?php if (isset($weather->visibility)): ?> <li><?php print t('Visibility: !visibility', array('!visibility' => $weather->visibility)); ?></li> <?php endif ?> <?php if (isset($weather->sunrise)): ?> <li><?php print $weather->sunrise; ?></li> <?php endif ?> <?php if (isset($weather->sunset)): ?> <li><?php print $weather->sunset; ?></li> <?php endif ?> <?php if (isset($weather->metar)): ?> <li><?php print t('METAR data: !metar', array('!metar' => '<pre>'. wordwrap($weather->metar, 20) .'</pre>')); ?></li> <?php endif ?> </ul> <?php if (isset($weather->station)): ?> <small> <?php print t('Location of this weather station:'); ?><br /> <?php print $weather->station; ?> </small> <br /> <?php endif ?> <?php if (isset($weather->legal)): ?> <small> <?php print $weather->legal; ?> </small> <br /> <?php endif ?> <?php if (isset($weather->reported_on)): ?> <small> <?php print t('Reported on:'); ?><br /> <?php print $weather->reported_on; ?> </small> <?php endif ?> </div>
shieldsdesignstudio/lefkowitz
sites/all/modules/weather/weather.tpl.php
PHP
gpl-2.0
2,487
# # Karaka Skype-XMPP Gateway: Python package metadata # <http://www.vipadia.com/products/karaka.html> # # Copyright (C) 2008-2009 Vipadia Limited # Richard Mortier <mort@vipadia.com> # Neil Stratford <neils@vipadia.com> # ## This program is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License version ## 2 as published by the Free Software Foundation. ## 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 version 2 for more details. ## You should have received a copy of the GNU General Public License ## version 2 along with this program; if not, write to the Free ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA.
gaka13/karaka
karaka/api/__init__.py
Python
gpl-2.0
896
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using STSdb4.General.Extensions; namespace STSdb4.Data { public class DataToObjects : IToObjects<IData> { public readonly Func<IData, object[]> to; public readonly Func<object[], IData> from; public readonly Type Type; public readonly Func<Type, MemberInfo, int> MembersOrder; public DataToObjects(Type type, Func<Type, MemberInfo, int> membersOrder = null) { if (!DataType.IsPrimitiveType(type) && !type.HasDefaultConstructor()) throw new NotSupportedException("No default constructor."); bool isSupported = DataTypeUtils.IsAllPrimitive(type); if (!isSupported) throw new NotSupportedException("Not all types are primitive."); Type = type; MembersOrder = membersOrder; to = CreateToMethod().Compile(); from = CreateFromMethod().Compile(); } public Expression<Func<IData, object[]>> CreateToMethod() { var data = Expression.Parameter(typeof(IData), "data"); var d = Expression.Variable(typeof(Data<>).MakeGenericType(Type), "d"); var body = Expression.Block(new ParameterExpression[] { d }, Expression.Assign(d, Expression.Convert(data, d.Type)), ValueToObjectsHelper.ToObjects(d.Value(), MembersOrder)); return Expression.Lambda<Func<IData, object[]>>(body, data); } public Expression<Func<object[], IData>> CreateFromMethod() { var objectArray = Expression.Parameter(typeof(object[]), "item"); var data = Expression.Variable(typeof(Data<>).MakeGenericType(Type)); List<Expression> list = new List<Expression>(); list.Add(Expression.Assign(data, Expression.New(data.Type.GetConstructor(new Type[] { })))); if (!DataType.IsPrimitiveType(Type)) list.Add(Expression.Assign(data.Value(), Expression.New(data.Value().Type.GetConstructor(new Type[] { })))); list.Add(ValueToObjectsHelper.FromObjects(data.Value(), objectArray, MembersOrder)); list.Add(Expression.Label(Expression.Label(typeof(IData)), data)); var body = Expression.Block(typeof(IData), new ParameterExpression[] { data }, list); return Expression.Lambda<Func<object[], IData>>(body, objectArray); } public object[] To(IData value1) { return to(value1); } public IData From(object[] value2) { return from(value2); } } }
Injac/STSdb4
STSdb4/Data/DataToObjects.cs
C#
gpl-2.0
2,719
/** * @copyright 2010-2015, The Titon Project * @license http://opensource.org/licenses/BSD-3-Clause * @link http://titon.io */ define([ 'jquery', './toolkit' ], function($, Toolkit) { // Empty class to extend from var Class = Toolkit.Class = function() {}; // Flag to determine if a constructor is initializing var constructing = false; /** * Very basic method for allowing functions to inherit functionality through the prototype. * * @param {Object} properties * @param {Object} options * @returns {Function} */ Class.extend = function(properties, options) { constructing = true; var prototype = new this(); constructing = false; // Inherit the prototype and merge properties $.extend(prototype, properties); // Fetch the constructor function before setting the prototype var constructor = prototype.constructor; // Class interface function Class() { // Exit constructing if being applied as prototype if (constructing) { return; } // Reset (clone) the array and object properties else they will be referenced between instances for (var key in this) { var value = this[key], type = $.type(value); if (type === 'array') { this[key] = value.slice(0); // Clone array } else if (type === 'object') { this[key] = $.extend(true, {}, value); // Clone object } } // Set the UID and increase global count this.uid = Class.count += 1; // Generate the CSS class name and attribute/event name based off the plugin name var name = this.name; if (name) { this.cssClass = name.replace(/[A-Z]/g, function(match) { return ('-' + match.charAt(0).toLowerCase()); }).slice(1); // Generate an attribute and event key name based off the plugin name this.keyName = name.charAt(0).toLowerCase() + name.slice(1); } // Trigger constructor if (constructor) { constructor.apply(this, arguments); } } // Inherit the prototype Class.prototype = prototype; Class.prototype.constructor = constructor || Class; // Inherit and set default options Class.options = $.extend(true, {}, this.options || {}, options || {}); // Inherit the extend method Class.extend = this.extend; // Count of total instances Class.count = 0; return Class; }; return Class; });
localymine/multisite
wp-content/themes/kodomo/html/toolkit-3.0/js/class.js
JavaScript
gpl-2.0
2,561
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "nstencil_half_bin_3d_newtoff.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ NStencilHalfBin3dNewtoff::NStencilHalfBin3dNewtoff(LAMMPS *lmp) : NStencil(lmp) {} /* ---------------------------------------------------------------------- create stencil based on bin geometry and cutoff ------------------------------------------------------------------------- */ void NStencilHalfBin3dNewtoff::create() { int i,j,k; nstencil = 0; for (k = -sz; k <= sz; k++) for (j = -sy; j <= sy; j++) for (i = -sx; i <= sx; i++) if (bin_distance(i,j,k) < cutneighmaxsq) stencil[nstencil++] = k*mbiny*mbinx + j*mbinx + i; }
Pakketeretet2/lammps
src/nstencil_half_bin_3d_newtoff.cpp
C++
gpl-2.0
1,347
/* This file is part of the KDE project Copyright (C) 2008 David Faure <faure@kde.org> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <konqmisc.h> #include <khtml_part.h> #include <khtmlview.h> #include <ktemporaryfile.h> #include <kstandarddirs.h> #include <ktoolbar.h> #include <kdebug.h> #include <ksycoca.h> #include <QScrollArea> #include <qtest_kde.h> #include <qtest_gui.h> #include <konqmainwindow.h> #include <konqviewmanager.h> #include <konqview.h> #include <konqsessionmanager.h> #include <QObject> class KonqHtmlTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase() { KonqSessionManager::self()->disableAutosave(); //qRegisterMetaType<KonqView *>("KonqView*"); // Ensure the tests use KHTML, not kwebkitpart // This code is inspired by settings/konqhtml/generalopts.cpp KSharedConfig::Ptr profile = KSharedConfig::openConfig("mimeapps.list", KConfig::NoGlobals, "xdgdata-apps"); KConfigGroup addedServices(profile, "Added KDE Service Associations"); Q_FOREACH(const QString& mimeType, QStringList() << "text/html" << "application/xhtml+xml" << "application/xml") { QStringList services = addedServices.readXdgListEntry(mimeType); services.removeAll("khtml.desktop"); services.prepend("khtml.desktop"); // make it the preferred one addedServices.writeXdgListEntry(mimeType, services); } profile->sync(); // kbuildsycoca is the one reading mimeapps.list, so we need to run it now QProcess::execute(KGlobal::dirs()->findExe(KBUILDSYCOCA_EXENAME)); } void cleanupTestCase() { // in case some test broke, don't assert in khtmlglobal... deleteAllMainWindows(); } void loadSimpleHtml() { KonqMainWindow mainWindow; // we specify the mimetype so that we don't have to wait for a KonqRun mainWindow.openUrl(0, KUrl("data:text/html, <p>Hello World</p>"), "text/html"); KonqView* view = mainWindow.currentView(); QVERIFY(view); QVERIFY(view->part()); QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 20000)); QCOMPARE(view->serviceType(), QString("text/html")); //KHTMLPart* part = qobject_cast<KHTMLPart *>(view->part()); //QVERIFY(part); } void loadDirectory() // #164495 { KonqMainWindow mainWindow; mainWindow.openUrl(0, KUrl(QDir::homePath()), "text/html"); KonqView* view = mainWindow.currentView(); kDebug() << "Waiting for first completed signal"; QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 20000)); // error calls openUrlRequest kDebug() << "Waiting for first second signal"; QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 20000)); // which then opens the right part QCOMPARE(view->serviceType(), QString("inode/directory")); } void rightClickClose() // #149736 { QPointer<KonqMainWindow> mainWindow = new KonqMainWindow; // we specify the mimetype so that we don't have to wait for a KonqRun mainWindow->openUrl(0, KUrl( "data:text/html, <script type=\"text/javascript\">" "function closeMe() { window.close(); } " "document.onmousedown = closeMe; " "</script>"), QString("text/html")); QPointer<KonqView> view = mainWindow->currentView(); QVERIFY(view); QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 10000)); QWidget* widget = partWidget(view); qDebug() << "Clicking on" << widget; QTest::mousePress(widget, Qt::RightButton); qApp->processEvents(); QVERIFY(!view); // deleted QVERIFY(!mainWindow); // the whole window gets deleted, in fact } void windowOpen() { // Simple test for window.open in a onmousedown handler. // We have to use the same protocol for both the orig and dest urls. // KAuthorized would forbid a data: URL to redirect to a file: URL for instance. KTemporaryFile tempFile; QVERIFY(tempFile.open()); tempFile.write("<script>document.write(\"Opener=\" + window.opener);</script>"); KTemporaryFile origTempFile; QVERIFY(origTempFile.open()); origTempFile.write( "<html><script>" "function openWindow() { window.open('" + KUrl(tempFile.fileName()).url().toUtf8() + "'); } " "document.onmousedown = openWindow; " "</script>" ); tempFile.close(); const QString origFile = origTempFile.fileName(); origTempFile.close(); KonqMainWindow* mainWindow = new KonqMainWindow; const QString profile = KStandardDirs::locate("data", "konqueror/profiles/webbrowsing"); mainWindow->viewManager()->loadViewProfileFromFile(profile, "webbrowsing", KUrl(origFile)); QCOMPARE(KMainWindow::memberList().count(), 1); KonqView* view = mainWindow->currentView(); QVERIFY(view); QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 10000)); qApp->processEvents(); QWidget* widget = partWidget(view); kDebug() << "Clicking on the khtmlview"; QTest::mousePress(widget, Qt::LeftButton); qApp->processEvents(); // openurlrequestdelayed qApp->processEvents(); // browserrun hideAllMainWindows(); // TODO: why does it appear nonetheless? hiding too early? hiding too late? QTest::qWait(100); // just in case there's more delayed calls :) // Did it open a window? QCOMPARE(KMainWindow::memberList().count(), 2); KMainWindow* newWindow = KMainWindow::memberList().last(); QVERIFY(newWindow != mainWindow); compareToolbarSettings(mainWindow, newWindow); // Does the window contain exactly one tab? QTabWidget* tab = newWindow->findChild<QTabWidget*>(); QVERIFY(tab); QCOMPARE(tab->count(), 1); KonqFrame* frame = qobject_cast<KonqFrame *>(tab->widget(0)); QVERIFY(frame); QVERIFY(!frame->childView()->isLoading()); KHTMLPart* part = qobject_cast<KHTMLPart *>(frame->part()); QVERIFY(part); part->selectAll(); const QString text = part->selectedText(); QCOMPARE(text, QString("Opener=[object Window]")); deleteAllMainWindows(); } void testJSError() { // JS errors appear in a statusbar label, and deleting the frame first // would lead to double deletion (#228255) KonqMainWindow mainWindow; // we specify the mimetype so that we don't have to wait for a KonqRun mainWindow.openUrl(0, KUrl("data:text/html, <script>window.foo=bar</script><p>Hello World</p>"), "text/html"); KonqView* view = mainWindow.currentView(); QVERIFY(view); QVERIFY(view->part()); QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 20000)); QCOMPARE(view->serviceType(), QString("text/html")); delete view->part(); } private: // Return the main widget for the given KonqView; used for clicking onto it static QWidget* partWidget(KonqView* view) { QWidget* widget = view->part()->widget(); KHTMLPart* htmlPart = qobject_cast<KHTMLPart *>(view->part()); if (htmlPart) widget = htmlPart->view(); // khtmlview != widget() nowadays, due to find bar if (QScrollArea* scrollArea = qobject_cast<QScrollArea*>(widget)) widget = scrollArea->widget(); return widget; } // Delete all KonqMainWindows static void deleteAllMainWindows() { const QList<KMainWindow*> windows = KMainWindow::memberList(); qDeleteAll(windows); } void compareToolbarSettings(KMainWindow* mainWindow, KMainWindow* newWindow) { QVERIFY(mainWindow != newWindow); KToolBar* firstToolBar = mainWindow->toolBars().first(); QVERIFY(firstToolBar); KToolBar* newFirstToolBar = newWindow->toolBars().first(); QVERIFY(newFirstToolBar); QCOMPARE(firstToolBar->toolButtonStyle(), newFirstToolBar->toolButtonStyle()); } static void hideAllMainWindows() { const QList<KMainWindow*> windows = KMainWindow::memberList(); kDebug() << "hiding" << windows.count() << "windows"; Q_FOREACH(KMainWindow* window, windows) window->hide(); } }; QTEST_KDEMAIN_WITH_COMPONENTNAME( KonqHtmlTest, GUI, "konqueror" ) #include "konqhtmltest.moc"
blue-shell/folderview
konqueror/src/tests/konqhtmltest.cpp
C++
gpl-2.0
9,297
<?php /** * @version $Id: layout.php 15522 2013-11-13 21:47:07Z kevin $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2015 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only * * Gantry uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system * */ // no direct access defined('_JEXEC') or die('Restricted access'); class GantrySplitmenuLayout extends AbstractRokMenuLayout { protected $theme_path; protected $params; static $jsLoaded = false; private $activeid; public function __construct(&$args) { parent::__construct($args); global $gantry; $theme_rel_path = "/html/mod_roknavmenu/themes/gantry-splitmenu"; $this->theme_path = $gantry->templatePath . $theme_rel_path; $this->args['theme_path'] = $this->theme_path; $this->args['theme_rel_path'] = $gantry->templateUrl. $theme_rel_path; $this->args['theme_url'] = $this->args['theme_rel_path']; $this->args['responsive-menu'] = $args['responsive-menu']; } public function stageHeader() { global $gantry; //don't include class_sfx on 3rd level menu $this->args['class_sfx'] = (array_key_exists('startlevel', $this->args) && $this->args['startLevel']==1) ? '' : $this->args['class_sfx']; $this->activeid = (array_key_exists('splitmenu_enable_current_id', $this->args) && $this->args['splitmenu_enable_current_id']== 0) ? false : true; JHtml::_('behavior.framework', true); if (!self::$jsLoaded && $gantry->get('layout-mode', 'responsive') == 'responsive'){ if (!($gantry->browser->name == 'ie' && $gantry->browser->shortver < 9)){ $gantry->addScript($gantry->baseUrl . 'modules/mod_roknavmenu/themes/default/js/rokmediaqueries.js'); if ($this->args['responsive-menu'] == 'selectbox') { $gantry->addScript($gantry->baseUrl . 'modules/mod_roknavmenu/themes/default/js/responsive.js'); $gantry->addScript($gantry->baseUrl . 'modules/mod_roknavmenu/themes/default/js/responsive-selectbox.js'); } else if (file_exists($gantry->basePath . '/modules/mod_roknavmenu/themes/default/js/sidemenu.js') && ($this->args['responsive-menu'] == 'panel')) { $gantry->addScript($gantry->baseUrl . 'modules/mod_roknavmenu/themes/default/js/sidemenu.js'); } } self::$jsLoaded = true; } $gantry->addLess('menu.less', 'menu.css', 1, array('headerstyle'=>$gantry->get('headerstyle','dark'), 'menuHoverColor'=>$gantry->get('linkcolor'))); // no media queries for IE8 so we compile and load the hovers if ($gantry->browser->name == 'ie' && $gantry->browser->shortver < 9){ $gantry->addLess('menu-hovers.less', 'menu-hovers.css', 1, array('headerstyle'=>$gantry->get('headerstyle','dark'), 'menuHoverColor'=>$gantry->get('linkcolor'))); } } protected function renderItem(JoomlaRokMenuNode &$item, RokMenuNodeTree &$menu) { global $gantry; $item_params = $item->getParams(); //not so elegant solution to add subtext $item_subtext = $item_params->get('splitmenu_item_subtext',''); if ($item_subtext=='') $item_subtext = false; else $item->addLinkClass('subtext'); //get custom image $custom_image = $item_params->get('splitmenu_customimage'); //get the custom icon $custom_icon = $item_params->get('splitmenu_customicon'); //get the custom class $custom_class = $item_params->get('splitmenu_customclass'); //add default link class $item->addLinkClass('item'); if ($custom_image && $custom_image != -1) $item->addLinkClass('image'); if ($custom_icon && $custom_icon != -1) $item->addLinkClass('icon'); if ($custom_class != '') $item->addListItemClass($custom_class); if ($item_params->get('splitmenu_menu_entry_type','normal') == 'normal'): if ($item->getType() != 'menuitem') { $item->setLink('javascript:void(0);'); } ?> <li <?php if($item->hasListItemClasses()) : ?>class="<?php echo $item->getListItemClasses()?>"<?php endif;?> <?php if($item->hasCssId() && $this->activeid):?>id="<?php echo $item->getCssId();?>"<?php endif;?>> <a <?php if($item->hasLinkClasses()):?>class="<?php echo $item->getLinkClasses();?>"<?php endif;?> <?php if($item->hasLink()):?>href="<?php echo $item->getLink();?>"<?php endif;?> <?php if($item->hasTarget()):?>target="<?php echo $item->getTarget();?>"<?php endif;?> <?php if ($item->hasAttribute('onclick')): ?>onclick="<?php echo $item->getAttribute('onclick'); ?>"<?php endif; ?><?php if ($item->hasLinkAttribs()): ?> <?php echo $item->getLinkAttribs(); ?><?php endif; ?>> <?php if ($custom_image && $custom_image != -1) :?> <img class="menu-image" src="<?php echo $gantry->templateUrl."/images/icons/".$custom_image; ?>" alt="<?php echo $custom_image; ?>" /> <?php endif; ?> <?php if ($custom_icon && $custom_icon != -1) { echo '<i class="' . $custom_icon . '">' . $item->getTitle() . '</i>'; } else { echo $item->getTitle(); } if (!empty($item_subtext)) { echo '<em>'. $item_subtext . '</em>'; } ?> </a> <?php if ($item->hasChildren()): ?> <ul class="level<?php echo intval($item->getLevel())+2; ?>"> <?php foreach ($item->getChildren() as $child) : ?> <?php $this->renderItem($child, $menu); ?> <?php endforeach; ?> </ul> <?php endif; ?> </li> <?php else: $item->addListItemClass('menu-module'); $module_id = $item_params->get('splitmenu_menu_module'); $menu_module = $this->getModule($module_id); $document = JFactory::getDocument(); $renderer = $document->loadRenderer('module'); $params = array('style'=> 'splitmenu'); $module_content = $renderer->render($menu_module, $params); ?> <li <?php if ($item->hasListItemClasses()) : ?>class="<?php echo $item->getListItemClasses()?>"<?php endif;?> <?php if ($item->hasCssId() && $this->activeid): ?>id="<?php echo $item->getCssId();?>"<?php endif;?>> <?php echo $module_content; ?> </li> <?php endif; } function getModule ($id=0, $name='') { $modules =& RokNavMenu::loadModules(); $total = count($modules); for ($i = 0; $i < $total; $i++) { // Match the name of the module if ($modules[$i]->id == $id || $modules[$i]->name == $name) { return $modules[$i]; } } return null; } public function curPageURL($link) { $pageURL = 'http'; if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } $replace = str_replace('&', '&amp;', (preg_match("/^http/", $link) ? $pageURL : $_SERVER["REQUEST_URI"])); return $replace == $link || $replace == $link . 'index.php'; } public function renderMenu(&$menu) { ob_start(); $menuname = (isset($this->args['style']) && $this->args['style'] == 'mainmenu') ? 'gf-menu gf-splitmenu' : 'menu'; ?> <?php if ($menu->getChildren()) : ?> <?php if (isset($this->args['style']) && $this->args['style'] == 'mainmenu'): ?> <div class="gf-menu-device-container"></div> <?php endif; ?> <ul class="<?php echo $menuname; ?> l1 <?php echo $this->args['class_sfx']; ?>" <?php if(array_key_exists('tag_id',$this->args)):?>id="<?php echo $this->args['tag_id'];?>"<?php endif;?>> <?php foreach ($menu->getChildren() as $item) : ?> <?php $this->renderItem($item, $menu); ?> <?php endforeach; ?> </ul> <?php endif; ?> <?php return ob_get_clean(); } }
bobozhangshao/HeartCare
templates/heartcare_gantry4/html/mod_roknavmenu/themes/gantry-splitmenu/layout.php
PHP
gpl-2.0
8,317
/**************************************************************************** ** ** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License versions 2.0 or 3.0 as published by the Free ** Software Foundation and appearing in the file LICENSE.GPL included in ** the packaging of this file. Please review the following information ** to ensure GNU General Public Licensing requirements will be met: ** http://www.fsf.org/licensing/licenses/info/GPLv2.html and ** http://www.gnu.org/copyleft/gpl.html. In addition, as a special ** exception, Nokia gives you certain additional rights. These rights ** are described in the Nokia Qt GPL Exception version 1.3, included in ** the file GPL_EXCEPTION.txt in this package. ** ** Qt for Windows(R) Licensees ** As a special exception, Nokia, as the sole copyright holder for Qt ** Designer, grants users of the Qt/Eclipse Integration plug-in the ** right for the Qt/Eclipse Integration to link to functionality ** provided by Qt Designer and its related libraries. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** ****************************************************************************/ #include "qwininputcontext_p.h" #include "qinputcontext_p.h" #include "qfont.h" #include "qwidget.h" #include "qapplication.h" #include "qlibrary.h" #include "qevent.h" #include "qtextformat.h" //#define Q_IME_DEBUG /* Active Input method support on Win95/98/NT */ #include <objbase.h> #include <initguid.h> #ifdef Q_IME_DEBUG #include "qdebug.h" #endif QT_BEGIN_NAMESPACE DEFINE_GUID(IID_IActiveIMMApp, 0x08c0e040, 0x62d1, 0x11d1, 0x93, 0x26, 0x0, 0x60, 0xb0, 0x67, 0xb8, 0x6e); DEFINE_GUID(CLSID_CActiveIMM, 0x4955DD33, 0xB159, 0x11d0, 0x8F, 0xCF, 0x0, 0xAA, 0x00, 0x6B, 0xCC, 0x59); DEFINE_GUID(IID_IActiveIMMMessagePumpOwner, 0xb5cf2cfa, 0x8aeb, 0x11d1, 0x93, 0x64, 0x0, 0x60, 0xb0, 0x67, 0xb8, 0x6e); interface IEnumRegisterWordW; interface IEnumInputContext; #define IFMETHOD HRESULT STDMETHODCALLTYPE interface IActiveIMMApp : public IUnknown { public: virtual IFMETHOD AssociateContext(HWND hWnd, HIMC hIME, HIMC __RPC_FAR *phPrev) = 0; virtual IFMETHOD dummy_ConfigureIMEA() = 0; virtual IFMETHOD ConfigureIMEW(HKL hKL, HWND hWnd, DWORD dwMode, REGISTERWORDW __RPC_FAR *pData) = 0; virtual IFMETHOD CreateContext(HIMC __RPC_FAR *phIMC) = 0; virtual IFMETHOD DestroyContext(HIMC hIME) = 0; virtual IFMETHOD dummy_EnumRegisterWordA() = 0; virtual IFMETHOD EnumRegisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szRegister, LPVOID pData, IEnumRegisterWordW __RPC_FAR *__RPC_FAR *pEnum) = 0; virtual IFMETHOD dummy_EscapeA() = 0; virtual IFMETHOD EscapeW(HKL hKL, HIMC hIMC, UINT uEscape, LPVOID pData, LRESULT __RPC_FAR *plResult) = 0; virtual IFMETHOD dummy_GetCandidateListA() = 0; virtual IFMETHOD GetCandidateListW(HIMC hIMC, DWORD dwIndex, UINT uBufLen, CANDIDATELIST __RPC_FAR *pCandList, UINT __RPC_FAR *puCopied) = 0; virtual IFMETHOD dummy_GetCandidateListCountA() = 0; virtual IFMETHOD GetCandidateListCountW(HIMC hIMC, DWORD __RPC_FAR *pdwListSize, DWORD __RPC_FAR *pdwBufLen) = 0; virtual IFMETHOD GetCandidateWindow(HIMC hIMC, DWORD dwIndex, CANDIDATEFORM __RPC_FAR *pCandidate) = 0; virtual IFMETHOD dummy_GetCompositionFontA() = 0; virtual IFMETHOD GetCompositionFontW(HIMC hIMC, LOGFONTW __RPC_FAR *plf) = 0; virtual IFMETHOD dummy_GetCompositionStringA() = 0; virtual IFMETHOD GetCompositionStringW(HIMC hIMC, DWORD dwIndex, DWORD dwBufLen, LONG __RPC_FAR *plCopied, LPVOID pBuf) = 0; virtual IFMETHOD GetCompositionWindow(HIMC hIMC, COMPOSITIONFORM __RPC_FAR *pCompForm) = 0; virtual IFMETHOD GetContext(HWND hWnd, HIMC __RPC_FAR *phIMC) = 0; virtual IFMETHOD dummy_GetConversionListA() = 0; virtual IFMETHOD GetConversionListW(HKL hKL, HIMC hIMC, LPWSTR pSrc, UINT uBufLen, UINT uFlag, CANDIDATELIST __RPC_FAR *pDst, UINT __RPC_FAR *puCopied) = 0; virtual IFMETHOD GetConversionStatus(HIMC hIMC, DWORD __RPC_FAR *pfdwConversion, DWORD __RPC_FAR *pfdwSentence) = 0; virtual IFMETHOD GetDefaultIMEWnd(HWND hWnd, HWND __RPC_FAR *phDefWnd) = 0; virtual IFMETHOD dummy_GetDescriptionA() = 0; virtual IFMETHOD GetDescriptionW(HKL hKL, UINT uBufLen, LPWSTR szDescription, UINT __RPC_FAR *puCopied) = 0; virtual IFMETHOD dummy_GetGuideLineA() = 0; virtual IFMETHOD GetGuideLineW(HIMC hIMC, DWORD dwIndex, DWORD dwBufLen, LPWSTR pBuf, DWORD __RPC_FAR *pdwResult) = 0; virtual IFMETHOD dummy_GetIMEFileNameA() = 0; virtual IFMETHOD GetIMEFileNameW(HKL hKL, UINT uBufLen, LPWSTR szFileName, UINT __RPC_FAR *puCopied) = 0; virtual IFMETHOD GetOpenStatus(HIMC hIMC) = 0; virtual IFMETHOD GetProperty(HKL hKL, DWORD fdwIndex, DWORD __RPC_FAR *pdwProperty) = 0; virtual IFMETHOD dummy_GetRegisterWordStyleA() = 0; virtual IFMETHOD GetRegisterWordStyleW(HKL hKL, UINT nItem, STYLEBUFW __RPC_FAR *pStyleBuf, UINT __RPC_FAR *puCopied) = 0; virtual IFMETHOD GetStatusWindowPos(HIMC hIMC, POINT __RPC_FAR *pptPos) = 0; virtual IFMETHOD GetVirtualKey(HWND hWnd, UINT __RPC_FAR *puVirtualKey) = 0; virtual IFMETHOD dummy_InstallIMEA() = 0; virtual IFMETHOD InstallIMEW(LPWSTR szIMEFileName, LPWSTR szLayoutText, HKL __RPC_FAR *phKL) = 0; virtual IFMETHOD IsIME(HKL hKL) = 0; virtual IFMETHOD dummy_IsUIMessageA() = 0; virtual IFMETHOD IsUIMessageW(HWND hWndIME, UINT msg, WPARAM wParam, LPARAM lParam) = 0; virtual IFMETHOD NotifyIME(HIMC hIMC, DWORD dwAction, DWORD dwIndex, DWORD dwValue) = 0; virtual IFMETHOD dummy_RegisterWordA() = 0; virtual IFMETHOD RegisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szRegister) = 0; virtual IFMETHOD ReleaseContext(HWND hWnd, HIMC hIMC) = 0; virtual IFMETHOD SetCandidateWindow(HIMC hIMC, CANDIDATEFORM __RPC_FAR *pCandidate) = 0; virtual IFMETHOD SetCompositionFontA(HIMC hIMC, LOGFONTA __RPC_FAR *plf) = 0; virtual IFMETHOD SetCompositionFontW(HIMC hIMC, LOGFONTW __RPC_FAR *plf) = 0; virtual IFMETHOD dummy_SetCompositionStringA() = 0; virtual IFMETHOD SetCompositionStringW(HIMC hIMC, DWORD dwIndex, LPVOID pComp, DWORD dwCompLen, LPVOID pRead, DWORD dwReadLen) = 0; virtual IFMETHOD SetCompositionWindow(HIMC hIMC, COMPOSITIONFORM __RPC_FAR *pCompForm) = 0; virtual IFMETHOD SetConversionStatus(HIMC hIMC, DWORD fdwConversion, DWORD fdwSentence) = 0; virtual IFMETHOD SetOpenStatus(HIMC hIMC, BOOL fOpen) = 0; virtual IFMETHOD SetStatusWindowPos(HIMC hIMC, POINT __RPC_FAR *pptPos) = 0; virtual IFMETHOD SimulateHotKey(HWND hWnd, DWORD dwHotKeyID) = 0; virtual IFMETHOD dummy_UnregisterWordA() = 0; virtual IFMETHOD UnregisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szUnregister) = 0; virtual IFMETHOD Activate(BOOL fRestoreLayout) = 0; virtual IFMETHOD Deactivate(void) = 0; virtual IFMETHOD OnDefWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam, LRESULT __RPC_FAR *plResult) = 0; virtual IFMETHOD FilterClientWindows(ATOM __RPC_FAR *aaClassList, UINT uSize) = 0; virtual IFMETHOD dummy_GetCodePageA() = 0; virtual IFMETHOD GetLangId(HKL hKL, LANGID __RPC_FAR *plid) = 0; virtual IFMETHOD AssociateContextEx(HWND hWnd, HIMC hIMC, DWORD dwFlags) = 0; virtual IFMETHOD DisableIME(DWORD idThread) = 0; virtual IFMETHOD dummy_GetImeMenuItemsA() = 0; virtual IFMETHOD GetImeMenuItemsW(HIMC hIMC, DWORD dwFlags, DWORD dwType, /*IMEMENUITEMINFOW*/ void __RPC_FAR *pImeParentMenu, /*IMEMENUITEMINFOW*/ void __RPC_FAR *pImeMenu, DWORD dwSize, DWORD __RPC_FAR *pdwResult) = 0; virtual IFMETHOD EnumInputContext(DWORD idThread, IEnumInputContext __RPC_FAR *__RPC_FAR *ppEnum) = 0; }; interface IActiveIMMMessagePumpOwner : public IUnknown { public: virtual IFMETHOD Start(void) = 0; virtual IFMETHOD End(void) = 0; virtual IFMETHOD OnTranslateMessage(const MSG __RPC_FAR *pMsg) = 0; virtual IFMETHOD Pause(DWORD __RPC_FAR *pdwCookie) = 0; virtual IFMETHOD Resume(DWORD dwCookie) = 0; }; static IActiveIMMApp *aimm = 0; static IActiveIMMMessagePumpOwner *aimmpump = 0; static QString *imeComposition = 0; static int imePosition = -1; bool qt_use_rtl_extensions = false; static bool haveCaret = false; #ifndef LGRPID_INSTALLED #define LGRPID_INSTALLED 0x00000001 // installed language group ids #define LGRPID_SUPPORTED 0x00000002 // supported language group ids #endif #ifndef LGRPID_ARABIC #define LGRPID_WESTERN_EUROPE 0x0001 // Western Europe & U.S. #define LGRPID_CENTRAL_EUROPE 0x0002 // Central Europe #define LGRPID_BALTIC 0x0003 // Baltic #define LGRPID_GREEK 0x0004 // Greek #define LGRPID_CYRILLIC 0x0005 // Cyrillic #define LGRPID_TURKISH 0x0006 // Turkish #define LGRPID_JAPANESE 0x0007 // Japanese #define LGRPID_KOREAN 0x0008 // Korean #define LGRPID_TRADITIONAL_CHINESE 0x0009 // Traditional Chinese #define LGRPID_SIMPLIFIED_CHINESE 0x000a // Simplified Chinese #define LGRPID_THAI 0x000b // Thai #define LGRPID_HEBREW 0x000c // Hebrew #define LGRPID_ARABIC 0x000d // Arabic #define LGRPID_VIETNAMESE 0x000e // Vietnamese #define LGRPID_INDIC 0x000f // Indic #define LGRPID_GEORGIAN 0x0010 // Georgian #define LGRPID_ARMENIAN 0x0011 // Armenian #endif static DWORD WM_MSIME_MOUSE = 0; QWinInputContext::QWinInputContext(QObject *parent) : QInputContext(parent), recursionGuard(false) { if (QSysInfo::WindowsVersion < QSysInfo::WV_2000) { // try to get the Active IMM COM object on Win95/98/NT, where english versions don't // support the regular Windows input methods. if (CoCreateInstance(CLSID_CActiveIMM, NULL, CLSCTX_INPROC_SERVER, IID_IActiveIMMApp, (LPVOID *)&aimm) != S_OK) { aimm = 0; } if (aimm && (aimm->QueryInterface(IID_IActiveIMMMessagePumpOwner, (LPVOID *)&aimmpump) != S_OK || aimm->Activate(true) != S_OK)) { aimm->Release(); aimm = 0; if (aimmpump) aimmpump->Release(); aimmpump = 0; } if (aimmpump) aimmpump->Start(); } #ifndef Q_OS_WINCE QSysInfo::WinVersion ver = QSysInfo::windowsVersion(); if (ver & QSysInfo::WV_NT_based && ver >= QSysInfo::WV_VISTA) { // Since the IsValidLanguageGroup/IsValidLocale functions always return true on // Vista, check the Keyboard Layouts for enabling RTL. UINT nLayouts = GetKeyboardLayoutList(0, 0); if (nLayouts) { HKL *lpList = new HKL[nLayouts]; GetKeyboardLayoutList(nLayouts, lpList); for (int i = 0; i<(int)nLayouts; i++) { WORD plangid = PRIMARYLANGID((quintptr)lpList[i]); if (plangid == LANG_ARABIC || plangid == LANG_HEBREW || plangid == LANG_FARSI #ifdef LANG_SYRIAC || plangid == LANG_SYRIAC #endif ) { qt_use_rtl_extensions = true; break; } } delete []lpList; } } else { // figure out whether a RTL language is installed typedef BOOL(WINAPI *PtrIsValidLanguageGroup)(DWORD,DWORD); PtrIsValidLanguageGroup isValidLanguageGroup = (PtrIsValidLanguageGroup)QLibrary::resolve(QLatin1String("kernel32"), "IsValidLanguageGroup"); if (isValidLanguageGroup) { qt_use_rtl_extensions = isValidLanguageGroup(LGRPID_ARABIC, LGRPID_INSTALLED) || isValidLanguageGroup(LGRPID_HEBREW, LGRPID_INSTALLED); } qt_use_rtl_extensions |= IsValidLocale(MAKELCID(MAKELANGID(LANG_ARABIC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) || IsValidLocale(MAKELCID(MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) #ifdef LANG_SYRIAC || IsValidLocale(MAKELCID(MAKELANGID(LANG_SYRIAC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) #endif || IsValidLocale(MAKELCID(MAKELANGID(LANG_FARSI, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED); } #else qt_use_rtl_extensions = false; #endif WM_MSIME_MOUSE = QT_WA_INLINE(RegisterWindowMessage(L"MSIMEMouseOperation"), RegisterWindowMessageA("MSIMEMouseOperation")); } QWinInputContext::~QWinInputContext() { // release active input method if we have one if (aimm) { aimmpump->End(); aimmpump->Release(); aimm->Deactivate(); aimm->Release(); aimm = 0; aimmpump = 0; } delete imeComposition; imeComposition = 0; } static HWND getDefaultIMEWnd(HWND wnd) { HWND ime_wnd; if(aimm) aimm->GetDefaultIMEWnd(wnd, &ime_wnd); else ime_wnd = ImmGetDefaultIMEWnd(wnd); return ime_wnd; } static HIMC getContext(HWND wnd) { HIMC imc; if (aimm) aimm->GetContext(wnd, &imc); else imc = ImmGetContext(wnd); return imc; } static void releaseContext(HWND wnd, HIMC imc) { if (aimm) aimm->ReleaseContext(wnd, imc); else ImmReleaseContext(wnd, imc); } static void notifyIME(HIMC imc, DWORD dwAction, DWORD dwIndex, DWORD dwValue) { if (!imc) return; if (aimm) aimm->NotifyIME(imc, dwAction, dwIndex, dwValue); else ImmNotifyIME(imc, dwAction, dwIndex, dwValue); } static LONG getCompositionString(HIMC himc, DWORD dwIndex, LPVOID lpbuf, DWORD dBufLen, bool *unicode = 0) { LONG len = 0; if (unicode) *unicode = true; if (aimm) aimm->GetCompositionStringW(himc, dwIndex, dBufLen, &len, lpbuf); else { if(QSysInfo::WindowsVersion != QSysInfo::WV_95) { len = ImmGetCompositionStringW(himc, dwIndex, lpbuf, dBufLen); } #if !defined(Q_OS_WINCE) else { len = ImmGetCompositionStringA(himc, dwIndex, lpbuf, dBufLen); if (unicode) *unicode = false; } #endif } return len; } static int getCursorPosition(HIMC himc) { return getCompositionString(himc, GCS_CURSORPOS, 0, 0); } static QString getString(HIMC himc, DWORD dwindex, int *selStart = 0, int *selLength = 0) { static char *buffer = 0; static int buflen = 0; int len = getCompositionString(himc, dwindex, 0, 0) + 1; if (!buffer || len > buflen) { delete [] buffer; buflen = qMin(len, 256); buffer = new char[buflen]; } bool unicode = true; len = getCompositionString(himc, dwindex, buffer, buflen, &unicode); if (selStart) { static char *attrbuffer = 0; static int attrbuflen = 0; int attrlen = getCompositionString(himc, dwindex, 0, 0) + 1; if (!attrbuffer || attrlen> attrbuflen) { delete [] attrbuffer; attrbuflen = qMin(attrlen, 256); attrbuffer = new char[attrbuflen]; } attrlen = getCompositionString(himc, GCS_COMPATTR, attrbuffer, attrbuflen); *selStart = attrlen+1; *selLength = -1; for (int i = 0; i < attrlen; i++) { if (attrbuffer[i] & ATTR_TARGET_CONVERTED) { *selStart = qMin(*selStart, i); *selLength = qMax(*selLength, i); } } *selLength = qMax(0, *selLength - *selStart + 1); } if (len <= 0) return QString(); if (unicode) { return QString((QChar *)buffer, len/sizeof(QChar)); } else { buffer[len] = 0; WCHAR *wc = new WCHAR[len+1]; int l = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, buffer, len, wc, len+1); QString res = QString((QChar *)wc, l); delete [] wc; return res; } } void QWinInputContext::TranslateMessage(const MSG *msg) { if (!aimmpump || aimmpump->OnTranslateMessage(msg) != S_OK) ::TranslateMessage(msg); } LRESULT QWinInputContext::DefWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { LRESULT retval; if (!aimm || aimm->OnDefWindowProc(hwnd, msg, wParam, lParam, &retval) != S_OK) { QT_WA({ retval = ::DefWindowProc(hwnd, msg, wParam, lParam); } , { retval = ::DefWindowProcA(hwnd,msg, wParam, lParam); }); } return retval; } void QWinInputContext::update() { QWidget *w = focusWidget(); if(!w) return; Q_ASSERT(w->testAttribute(Qt::WA_WState_Created)); HIMC imc = getContext(w->effectiveWinId()); if (!imc) return; QFont f = qvariant_cast<QFont>(w->inputMethodQuery(Qt::ImFont)); HFONT hf; hf = f.handle(); QT_WA({ LOGFONT lf; if (GetObject(hf, sizeof(lf), &lf)) if (aimm) aimm->SetCompositionFontW(imc, &lf); else ImmSetCompositionFont(imc, &lf); } , { LOGFONTA lf; if (GetObjectA(hf, sizeof(lf), &lf)) if (aimm) aimm->SetCompositionFontA(imc, &lf); else ImmSetCompositionFontA(imc, &lf); }); QRect r = w->inputMethodQuery(Qt::ImMicroFocus).toRect(); // The ime window positions are based on the WinId with active focus. QWidget *imeWnd = QWidget::find(::GetFocus()); if (imeWnd && !aimm) { QPoint pt (r.topLeft()); pt = w->mapToGlobal(pt); pt = imeWnd->mapFromGlobal(pt); r.moveTo(pt); } COMPOSITIONFORM cf; // ### need X-like inputStyle config settings cf.dwStyle = CFS_FORCE_POSITION; cf.ptCurrentPos.x = r.x(); cf.ptCurrentPos.y = r.y(); CANDIDATEFORM candf; candf.dwIndex = 0; candf.dwStyle = CFS_EXCLUDE; candf.ptCurrentPos.x = r.x(); candf.ptCurrentPos.y = r.y() + r.height(); candf.rcArea.left = r.x(); candf.rcArea.top = r.y(); candf.rcArea.right = r.x() + r.width(); candf.rcArea.bottom = r.y() + r.height(); if(haveCaret) SetCaretPos(r.x(), r.y()); if (aimm) { aimm->SetCompositionWindow(imc, &cf); aimm->SetCandidateWindow(imc, &candf); } else { ImmSetCompositionWindow(imc, &cf); ImmSetCandidateWindow(imc, &candf); } releaseContext(w->effectiveWinId(), imc); } bool QWinInputContext::endComposition() { QWidget *fw = focusWidget(); #ifdef Q_IME_DEBUG qDebug("endComposition! fw = %s", fw ? fw->className() : "(null)"); #endif bool result = true; if(imePosition == -1 || recursionGuard) return result; // Googles Pinyin Input Method likes to call endComposition again // when we call notifyIME with CPS_CANCEL, so protect ourselves // against that. recursionGuard = true; if (fw) { Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created)); HIMC imc = getContext(fw->effectiveWinId()); notifyIME(imc, NI_COMPOSITIONSTR, CPS_CANCEL, 0); releaseContext(fw->effectiveWinId(), imc); if(haveCaret) { DestroyCaret(); haveCaret = false; } } if (!fw) fw = qApp->focusWidget(); if (fw) { QInputMethodEvent e; result = qt_sendSpontaneousEvent(fw, &e); } if (imeComposition) imeComposition->clear(); imePosition = -1; recursionGuard = false; return result; } void QWinInputContext::reset() { QWidget *fw = focusWidget(); #ifdef Q_IME_DEBUG qDebug("sending accept to focus widget %s", fw ? fw->className() : "(null)"); #endif if (fw && imePosition != -1) { QInputMethodEvent e; if (imeComposition) e.setCommitString(*imeComposition); qt_sendSpontaneousEvent(fw, &e); } if (imeComposition) imeComposition->clear(); imePosition = -1; if (fw) { Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created)); HIMC imc = getContext(fw->effectiveWinId()); notifyIME(imc, NI_COMPOSITIONSTR, CPS_CANCEL, 0); releaseContext(fw->effectiveWinId(), imc); } } bool QWinInputContext::startComposition() { #ifdef Q_IME_DEBUG qDebug("startComposition"); #endif if (!imeComposition) imeComposition = new QString(); QWidget *fw = focusWidget(); if (fw) { Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created)); imePosition = 0; haveCaret = CreateCaret(fw->effectiveWinId(), 0, 1, 1); HideCaret(fw->effectiveWinId()); update(); } return fw != 0; } enum StandardFormat { PreeditFormat, SelectionFormat }; bool QWinInputContext::composition(LPARAM lParam) { #ifdef Q_IME_DEBUG QString str; if (lParam & GCS_RESULTSTR) str += "RESULTSTR "; if (lParam & GCS_COMPSTR) str += "COMPSTR "; if (lParam & GCS_COMPATTR) str += "COMPATTR "; if (lParam & GCS_CURSORPOS) str += "CURSORPOS "; if (lParam & GCS_COMPCLAUSE) str += "COMPCLAUSE "; if (lParam & CS_INSERTCHAR) str += "INSERTCHAR "; if (lParam & CS_NOMOVECARET) str += "NOMOVECARET "; qDebug("composition, lParam=(%x) %s imePosition=%d", lParam, str.latin1(), imePosition); #endif bool result = true; if(!lParam) // bogus event return true; QWidget *fw = qApp->focusWidget(); if (fw) { Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created)); HIMC imc = getContext(fw->effectiveWinId()); QInputMethodEvent e; if (lParam & (GCS_COMPSTR | GCS_COMPATTR | GCS_CURSORPOS)) { if (imePosition == -1) // need to send a start event startComposition(); // some intermediate composition result int selStart, selLength; *imeComposition = getString(imc, GCS_COMPSTR, &selStart, &selLength); imePosition = getCursorPosition(imc); if (lParam & CS_INSERTCHAR && lParam & CS_NOMOVECARET) { // make korean work correctly. Hope this is correct for all IMEs selStart = 0; selLength = imeComposition->length(); } if(selLength == 0) selStart = 0; QList<QInputMethodEvent::Attribute> attrs; if (selStart > 0) attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, 0, selStart, standardFormat(PreeditFormat)); if (selLength) attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, selStart, selLength, standardFormat(SelectionFormat)); if (selStart + selLength < imeComposition->length()) attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, selStart + selLength, imeComposition->length() - selStart - selLength, standardFormat(PreeditFormat)); if(imePosition >= 0) attrs << QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, imePosition, selLength ? 0 : 1, QVariant()); e = QInputMethodEvent(*imeComposition, attrs); } if (lParam & GCS_RESULTSTR) { if(imePosition == -1) startComposition(); // a fixed result, return the converted string *imeComposition = getString(imc, GCS_RESULTSTR); imePosition = -1; e.setCommitString(*imeComposition); imeComposition->clear(); } result = qt_sendSpontaneousEvent(fw, &e); update(); releaseContext(fw->effectiveWinId(), imc); } #ifdef Q_IME_DEBUG qDebug("imecomposition: cursor pos at %d, str=%x", imePosition, str[0].unicode()); #endif return result; } static HIMC defaultContext = 0; // checks whether widget is a popup inline bool isPopup(QWidget *w) { if (w && (w->windowFlags() & Qt::Popup) == Qt::Popup) return true; else return false; } // checks whether widget is in a popup inline bool isInPopup(QWidget *w) { if (w && (isPopup(w) || isPopup(w->window()))) return true; else return false; } // find the parent widget, which is a non popup toplevel // this is valid only if the widget is/in a popup inline QWidget *findParentforPopup(QWidget *w) { QWidget *e = QWidget::find(w->effectiveWinId()); // check if this or its parent is a popup while (isInPopup(e)) { e = e->window()->parentWidget(); if (!e) break; e = QWidget::find(e->effectiveWinId()); } if (e) return e->window(); else return 0; } // enables or disables the ime inline void enableIme(QWidget *w, bool value) { if (value) { // enable ime if (defaultContext) ImmAssociateContext(w->effectiveWinId(), defaultContext); } else { // disable ime HIMC oldimc = ImmAssociateContext(w->effectiveWinId(), 0); if (!defaultContext) defaultContext = oldimc; } } void QInputContextPrivate::updateImeStatus(QWidget *w, bool hasFocus) { if (!w) return; bool e = w->testAttribute(Qt::WA_InputMethodEnabled) && w->isEnabled(); bool hasIme = e && hasFocus; #ifdef Q_IME_DEBUG qDebug("%s HasFocus = %d hasIme = %d e = %d ", w->className(), hasFocus, hasIme, e); #endif if (hasFocus || e) { if (isInPopup(w)) QWinInputContext::enablePopupChild(w, hasIme); else QWinInputContext::enable(w, hasIme); } } void QWinInputContext::enablePopupChild(QWidget *w, bool e) { if (aimm) { enable(w, e); return; } if (!w || !isInPopup(w)) return; #ifdef Q_IME_DEBUG qDebug("enablePopupChild: w=%s, enable = %s", w ? w->className() : "(null)" , e ? "true" : "false"); #endif QWidget *parent = findParentforPopup(w); if (parent) { // update ime status of the normal toplevel parent of the popup enableIme(parent, e); } QWidget *toplevel = w->window(); if (toplevel) { // update ime status of the toplevel popup enableIme(toplevel, e); } } void QWinInputContext::enable(QWidget *w, bool e) { if(w) { #ifdef Q_IME_DEBUG qDebug("enable: w=%s, enable = %s", w ? w->className() : "(null)" , e ? "true" : "false"); #endif if (!w->testAttribute(Qt::WA_WState_Created)) return; if(aimm) { HIMC oldimc; if (!e) { aimm->AssociateContext(w->effectiveWinId(), 0, &oldimc); if (!defaultContext) defaultContext = oldimc; } else if (defaultContext) { aimm->AssociateContext(w->effectiveWinId(), defaultContext, &oldimc); } } else { // update ime status on the widget QWidget *p = QWidget::find(w->effectiveWinId()); if (p) enableIme(p, e); } } } void QWinInputContext::setFocusWidget(QWidget *w) { QInputContext::setFocusWidget(w); update(); } bool QWinInputContext::isComposing() const { return imeComposition && !imeComposition->isEmpty(); } void QWinInputContext::mouseHandler(int pos, QMouseEvent *e) { if(e->type() != QEvent::MouseButtonPress) return; if (pos < 0 || pos > imeComposition->length()) reset(); // Probably should pass the correct button, but it seems to work fine like this. DWORD button = MK_LBUTTON; QWidget *fw = focusWidget(); if (fw) { Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created)); HIMC himc = getContext(fw->effectiveWinId()); HWND ime_wnd = getDefaultIMEWnd(fw->effectiveWinId()); SendMessage(ime_wnd, WM_MSIME_MOUSE, MAKELONG(MAKEWORD(button, pos == 0 ? 2 : 1), pos), (LPARAM)himc); releaseContext(fw->effectiveWinId(), himc); } //qDebug("mouseHandler: got value %d pos=%d", ret,pos); } QString QWinInputContext::language() { return QString(); } QT_END_NAMESPACE
FilipBE/qtextended
qtopiacore/qt/src/gui/inputmethod/qwininputcontext_win.cpp
C++
gpl-2.0
28,969
/* * $Id$ * * Copyright 2011 Glencoe Software, Inc. All rights reserved. * Use is subject to license terms supplied in LICENSE.txt */ package ome.services.fulltext.bridges; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import ome.io.nio.OriginalFilesService; import ome.model.IAnnotated; import ome.model.IObject; import ome.model.annotations.Annotation; import ome.model.annotations.FileAnnotation; import ome.model.containers.Dataset; import ome.model.core.Image; import ome.model.core.OriginalFile; import ome.model.screen.Plate; import ome.model.screen.Well; import ome.model.screen.WellSample; import ome.services.fulltext.BridgeHelper; import ome.system.OmeroContext; import org.apache.lucene.document.Document; import org.hibernate.search.bridge.LuceneOptions; import org.springframework.context.ApplicationEventPublisher; import ucar.ma2.Array; import ucar.ma2.ArrayChar; import ucar.ma2.ArrayStructure; import ucar.ma2.Index; import ucar.ma2.StructureData; import ucar.ma2.StructureMembers.Member; import ucar.nc2.NetcdfFile; /** * Bridge for parsing OMERO.tables attached to container types. The column names * are taken as field names on each image (or similar) found within the table. * For example, if a table is attached to a plate and has an * omero.grid.ImageColumn "IMAGE" along with one omero.grid.DoubleColumn named * "SIZE", then a row with IMAGE == 1 and SIZE == 0.02 will add a field "SIZE" * to the {@link Image} with id 1 so that a Lucene search "SIZE:0.02" will * return that object. * * This is accomplished by detecting such OMERO.tables on the container and * registering each row (above: IMAGE == 1, IMAGE == 2, etc) for later * processing. When the element objects are handled, the container is found and * the appropriate row processed. This two stage processingis necessary so that * later indexing does not overwrite the table values. * * @since 4.3 */ @Deprecated public class TablesBridge extends BridgeHelper { /** * Mimetype set on OriginalFile.mimetype (or in previous version, * OriginalFile.format.value). */ public final String OMERO_TABLE = "OMERO.tables"; /* final */OriginalFilesService ofs; @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { super.setApplicationEventPublisher(publisher); if (publisher instanceof OmeroContext) { OmeroContext ctx = (OmeroContext) publisher; ofs = ctx.getBean("/OMERO/Files", OriginalFilesService.class); } else { log.warn("Publisher is " + publisher.getClass().getName()); log.warn("Cannot configure TablesBridge properly!"); } } /** * Primary entry point for all bridges. */ @Override public void set(String name, Object value, Document document, LuceneOptions opts) { if (value instanceof Image) { handleImage((Image) value, document, opts); } else if (value instanceof Plate) { handleAnnotated((Plate) value, document, opts); } else if (value instanceof Dataset) { handleAnnotated((Dataset) value, document, opts); } } /** * Processes any annotations attached to the following types which contain * this image: Plate, Dataset */ protected void handleImage(Image image, Document document, LuceneOptions opts) { for (Iterator<WellSample> it = image.iterateWellSamples(); it.hasNext();) { WellSample ws = it.next(); Well well = ws.getWell(); Plate plate = well.getPlate(); for (Annotation a : plate.linkedAnnotationList()) { // /////////////////////////////////////////////////// handleAnnotation(a, new AttachRow(image, document, opts)); // /////////////////////////////////////////////////// } } for (Dataset ds : image.linkedDatasetList()) { for (Annotation a : ds.linkedAnnotationList()) { // /////////////////////////////////////////////////// handleAnnotation(a, new AttachRow(image, document, opts)); // /////////////////////////////////////////////////// } } } /** * Responsible for iterating over any attached OMERO.tables and registering * all appropriate row objects for later processing. For example, if the * table has an omero.grid.ImageColumn with ids 1, 2, 3, and 4, then 4 image * objects will be registered for later processing by * {@link #handleImage(Image, Document, LuceneOptions)}. */ protected void handleAnnotated(IAnnotated annotated, Document document, LuceneOptions opts) { for (Annotation a : annotated.linkedAnnotationList()) { // /////////////////////////////////////////////////// handleAnnotation(a, new RegisterRow()); // /////////////////////////////////////////////////// } } /** * Detects if the given annotation contains an OMERO.table and if so, passes * it off for further processing. */ protected void handleAnnotation(Annotation annotation, RowProcessor proc) { annotation = getProxiedObject(annotation); if (annotation instanceof FileAnnotation) { final OriginalFile file = ((FileAnnotation) annotation).getFile(); final String mimetype = file.getMimetype(); final String path = ofs.getFilesPath(file.getId()); // ///////////////////////////////////////////////// if (OMERO_TABLE.equals(mimetype)) { debug("Handling annotation %s", annotation); handleHdf5(path, proc); } // ////////////////////////////////////////////////// } } /** * Process a single OMERO.tables file. This method is primarily responsible * for iteration and the try/finally logic to guarantee cleanup, etc. */ protected void handleHdf5(String path, RowProcessor proc) { NetcdfFile ncfile = null; try { ncfile = NetcdfFile.open(path); Table table = new Table(ncfile); if (!proc.initialize(table)) { debug("Skipping %s", path); return; } debug("Handling %s with %s rows", path, table.rows); StructureData sData = null; for (int x = 0; x < table.rows; x++) { // ////////////a///////////////////////////// sData = (StructureData) table.structure.getObject(x); if (!proc.processRow(x, sData)) { break; // Permit break out. } // ////////////////////////////////////////// } } catch (IOException ioe) { log.error("trying to open " + path, ioe); } finally { if (null != ncfile) { try { ncfile.close(); } catch (IOException ioe) { log.error("trying to close " + path, ioe); } } } } private void debug(String format, Object... vals) { if (log.isDebugEnabled()) { log.debug(String.format(format, vals)); } } private void trace(String format, Object... vals) { if (log.isTraceEnabled()) { log.trace(String.format(format, vals)); } } // ////////////////////////////////////////////////////////////////////////// abstract class RowProcessor { int targetCol; IObject targetType; public boolean initialize(Table table) { targetCol = table.getFinestColumn(); if (targetCol < 0) { log.info("No column found."); return false; } targetType = table.getObjectForColumn(targetCol); return true; } public abstract boolean processRow(int row, StructureData sData); protected long getLong(Array array) { Index index = array.getIndex(); index.set(0); long targetId = array.getLong(index); return targetId; } protected Object getObject(Array array) { Index index = array.getIndex(); index.set(0); return array.getObject(index); } } /** * Attaches all rows matching the IObject instance to the given Document * argument. */ class AttachRow extends RowProcessor { final IObject object; final Document document; final LuceneOptions opts; AttachRow(IObject object, Document document, LuceneOptions opts) { this.object = object; this.document = document; this.opts = opts; } /** * Primary processing method responsible for adding the value of each * column in "members" to the Document. */ public boolean processRow(int row, StructureData sData) { List<Member> members = sData.getMembers(); Array targetArray = sData.getArray(members.get(targetCol)); long targetId = getLong(targetArray); if (targetId != object.getId().longValue()) { return true; // Keep going. } for (int i = 0; i < members.size(); i++) { if (i == targetCol) { continue; } final Member member = members.get(i); final String name = member.getName(); final Array array = sData.getArray(member); final String str = getObject(array).toString(); trace("Add %s:%s to %s", name, str, object); add(document, name, str, opts); } return true; } } class RegisterRow extends RowProcessor { public boolean processRow(int row, StructureData sData) { List<Member> members = sData.getMembers(); Array targetArray = sData.getArray(members.get(targetCol)); long targetId = getLong(targetArray); // Object reused since the id is copied in EventLogLoader targetType.setId(targetId); reindex(targetType); return true; } } // ////////////////////////////////////////////////////////////////////////// /** * Wraps a NetCDF/HDF5 file conforming to the first version of OMERO.tables. */ private class Table { public final static String COLUMN_BASE = "::omero::grid::"; public final static String IMAGE_COL = COLUMN_BASE + "ImageColumn"; public final static String WELL_COL = COLUMN_BASE + "WellColumn"; public final static String PLATE_COL = COLUMN_BASE + "PlateColumn"; final private NetcdfFile f; final ArrayStructure structure; final long rows; final List<String> types; Table(NetcdfFile f) throws IOException { this.f = f; this.structure = structure(); this.rows = structure.getSize(); this.types = getColTypes(); trace("Column types: %s", this.types); } public IObject getObjectForColumn(int targetCol) { String type = types.get(targetCol); if (type.startsWith(IMAGE_COL)) { return new Image(); } else if (type.startsWith(WELL_COL)) { return new Well(); } else if (type.startsWith(PLATE_COL)) { return new Plate(); } else { throw new RuntimeException("Unsupported type:" + type); } } /** * Returns * * @return */ public int getFinestColumn() { final List<Integer> plates = new ArrayList<Integer>(); final List<Integer> wells = new ArrayList<Integer>(); final List<Integer> images = new ArrayList<Integer>(); for (int i = 0; i < types.size(); i++) { final String type = types.get(i); if (type.startsWith(IMAGE_COL)) { images.add(i); } else if (type.startsWith(WELL_COL)) { wells.add(i); } else if (type.startsWith(PLATE_COL)) { plates.add(i); } else { } } if (images.size() == 1) { return images.get(0); } else if (images.size() > 1) { log.warn("Multiple image columns found."); return -1; } if (wells.size() == 1) { return wells.get(0); } else if (wells.size() > 1) { log.warn("Multiple well columns found."); return -2; } if (plates.size() == 1) { return plates.get(0); } else if (plates.size() > 1) { log.warn("Multiple plate columns found."); return -3; } return -4; } /** * For the current version of OMERO.tables lookup the primary data * structure ("/OME/Measurements"). */ private ArrayStructure structure() throws IOException { return (ArrayStructure) f.findVariable("/OME/Measurements").read(); } /** * For the current version of OMERO.tables lookup the stored Ice class * names of each column, e.g. "::omero::grid::LongColumn" */ private List<String> getColTypes() throws IOException { ArrayChar typeArray = (ArrayChar) f .findVariable("/OME/ColumnTypes").read(); char[][] obj = (char[][]) typeArray.copyToNDJavaArray(); List<String> types = new ArrayList<String>(); for (int i = 0; i < obj.length; i++) { types.add(new String(obj[i])); } return types; } } }
simleo/openmicroscopy
components/server/src/ome/services/fulltext/bridges/TablesBridge.java
Java
gpl-2.0
14,271
package edu.stanford.nlp.stats; import java.io.Serializable; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import edu.stanford.nlp.math.ArrayMath; import edu.stanford.nlp.math.SloppyMath; import edu.stanford.nlp.util.Generics; import edu.stanford.nlp.util.MapFactory; import edu.stanford.nlp.util.MutableDouble; import edu.stanford.nlp.util.Pair; import edu.stanford.nlp.util.StringUtils; /** * A class representing a mapping between pairs of typed objects and double * values. * * @author Teg Grenager */ public class TwoDimensionalCounter<K1, K2> implements TwoDimensionalCounterInterface<K1,K2>, Serializable { private static final long serialVersionUID = 1L; // the outermost Map private Map<K1, ClassicCounter<K2>> map; // the total of all counts private double total; // the MapFactory used to make new maps to counters private MapFactory<K1, ClassicCounter<K2>> outerMF; // the MapFactory used to make new maps in the inner counter private MapFactory<K2, MutableDouble> innerMF; private double defaultValue = 0.0; @Override public void defaultReturnValue(double rv) { defaultValue = rv; } @Override public double defaultReturnValue() { return defaultValue; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof TwoDimensionalCounter)) return false; return ((TwoDimensionalCounter<?, ?>) o).map.equals(map); } @Override public int hashCode() { return map.hashCode() + 17; } /** * @return the inner Counter associated with key o */ @Override public ClassicCounter<K2> getCounter(K1 o) { ClassicCounter<K2> c = map.get(o); if (c == null) { c = new ClassicCounter<>(innerMF); c.setDefaultReturnValue(defaultValue); map.put(o, c); } return c; } public Set<Map.Entry<K1, ClassicCounter<K2>>> entrySet() { return map.entrySet(); } /** * @return total number of entries (key pairs) */ @Override public int size() { int result = 0; for (K1 o : firstKeySet()) { ClassicCounter<K2> c = map.get(o); result += c.size(); } return result; } /** * @return size of the outer map */ public int sizeOuterMap(){ return map.size(); } @Override public boolean containsKey(K1 o1, K2 o2) { if (!map.containsKey(o1)) return false; ClassicCounter<K2> c = map.get(o1); return c.containsKey(o2); } public boolean containsFirstKey(K1 o1) { return map.containsKey(o1); } /** */ @Override public void incrementCount(K1 o1, K2 o2) { incrementCount(o1, o2, 1.0); } /** */ @Override public void incrementCount(K1 o1, K2 o2, double count) { ClassicCounter<K2> c = getCounter(o1); c.incrementCount(o2, count); total += count; } /** */ @Override public void decrementCount(K1 o1, K2 o2) { incrementCount(o1, o2, -1.0); } /** */ @Override public void decrementCount(K1 o1, K2 o2, double count) { incrementCount(o1, o2, -count); } /** */ @Override public void setCount(K1 o1, K2 o2, double count) { ClassicCounter<K2> c = getCounter(o1); double oldCount = getCount(o1, o2); total -= oldCount; c.setCount(o2, count); total += count; } @Override public double remove(K1 o1, K2 o2) { ClassicCounter<K2> c = getCounter(o1); double oldCount = getCount(o1, o2); total -= oldCount; c.remove(o2); if (c.size() == 0) { map.remove(o1); } return oldCount; } /** */ @Override public double getCount(K1 o1, K2 o2) { ClassicCounter<K2> c = getCounter(o1); if (c.totalCount() == 0.0 && !c.keySet().contains(o2)) { return defaultReturnValue(); } return c.getCount(o2); } /** * Takes linear time. * */ @Override public double totalCount() { return total; } /** */ @Override public double totalCount(K1 k1) { ClassicCounter<K2> c = getCounter(k1); return c.totalCount(); } @Override public Set<K1> firstKeySet() { return map.keySet(); } /** * replace the counter for K1-index o by new counter c */ public ClassicCounter<K2> setCounter(K1 o, Counter<K2> c) { ClassicCounter<K2> old = getCounter(o); total -= old.totalCount(); if (c instanceof ClassicCounter) { map.put(o, (ClassicCounter<K2>) c); } else { map.put(o, new ClassicCounter<>(c)); } total += c.totalCount(); return old; } /** * Produces a new ConditionalCounter. * * @return a new ConditionalCounter, where order of indices is reversed */ @SuppressWarnings( { "unchecked" }) public static <K1, K2> TwoDimensionalCounter<K2, K1> reverseIndexOrder(TwoDimensionalCounter<K1, K2> cc) { // they typing on the outerMF is violated a bit, but it'll work.... TwoDimensionalCounter<K2, K1> result = new TwoDimensionalCounter<>((MapFactory) cc.outerMF, (MapFactory) cc.innerMF); for (K1 key1 : cc.firstKeySet()) { ClassicCounter<K2> c = cc.getCounter(key1); for (K2 key2 : c.keySet()) { double count = c.getCount(key2); result.setCount(key2, key1, count); } } return result; } /** * A simple String representation of this TwoDimensionalCounter, which has the * String representation of each key pair on a separate line, followed by the * count for that pair. The items are tab separated, so the result is a * tab-separated value (TSV) file. Iff none of the keys contain spaces, it * will also be possible to treat this as whitespace separated fields. */ @Override public String toString() { StringBuilder buff = new StringBuilder(); for (K1 key1 : map.keySet()) { ClassicCounter<K2> c = getCounter(key1); for (K2 key2 : c.keySet()) { double score = c.getCount(key2); buff.append(key1).append('\t').append(key2).append('\t').append(score).append('\n'); } } return buff.toString(); } @Override @SuppressWarnings( { "unchecked" }) public String toMatrixString(int cellSize) { return toMatrixString(cellSize, new DecimalFormat()); } @SuppressWarnings( { "unchecked" }) public String toMatrixString(int cellSize, NumberFormat nf) { List<K1> firstKeys = new ArrayList<>(firstKeySet()); List<K2> secondKeys = new ArrayList<>(secondKeySet()); Collections.sort((List<? extends Comparable>) firstKeys); Collections.sort((List<? extends Comparable>) secondKeys); double[][] counts = toMatrix(firstKeys, secondKeys); return ArrayMath.toString(counts, cellSize, firstKeys.toArray(), secondKeys.toArray(), nf, true); } /** * Given an ordering of the first (row) and second (column) keys, will produce * a double matrix. * */ @Override public double[][] toMatrix(List<K1> firstKeys, List<K2> secondKeys) { double[][] counts = new double[firstKeys.size()][secondKeys.size()]; for (int i = 0; i < firstKeys.size(); i++) { for (int j = 0; j < secondKeys.size(); j++) { counts[i][j] = getCount(firstKeys.get(i), secondKeys.get(j)); } } return counts; } @Override @SuppressWarnings( { "unchecked" }) public String toCSVString(NumberFormat nf) { List<K1> firstKeys = new ArrayList<>(firstKeySet()); List<K2> secondKeys = new ArrayList<>(secondKeySet()); Collections.sort((List<? extends Comparable>) firstKeys); Collections.sort((List<? extends Comparable>) secondKeys); StringBuilder b = new StringBuilder(); String[] headerRow = new String[secondKeys.size() + 1]; headerRow[0] = ""; for (int j = 0; j < secondKeys.size(); j++) { headerRow[j + 1] = secondKeys.get(j).toString(); } b.append(StringUtils.toCSVString(headerRow)).append('\n'); for (K1 rowLabel : firstKeys) { String[] row = new String[secondKeys.size() + 1]; row[0] = rowLabel.toString(); for (int j = 0; j < secondKeys.size(); j++) { K2 colLabel = secondKeys.get(j); row[j + 1] = nf.format(getCount(rowLabel, colLabel)); } b.append(StringUtils.toCSVString(row)).append('\n'); } return b.toString(); } @Override public Set<K2> secondKeySet() { Set<K2> result = Generics.newHashSet(); for (K1 k1 : firstKeySet()) { for (K2 k2 : getCounter(k1).keySet()) { result.add(k2); } } return result; } @Override public boolean isEmpty() { return map.isEmpty(); } public ClassicCounter<Pair<K1, K2>> flatten() { ClassicCounter<Pair<K1, K2>> result = new ClassicCounter<>(); result.setDefaultReturnValue(defaultValue); for (K1 key1 : firstKeySet()) { ClassicCounter<K2> inner = getCounter(key1); for (K2 key2 : inner.keySet()) { result.setCount(new Pair<>(key1, key2), inner.getCount(key2)); } } return result; } public void addAll(TwoDimensionalCounterInterface<K1, K2> c) { for (K1 key : c.firstKeySet()) { Counter<K2> inner = c.getCounter(key); ClassicCounter<K2> myInner = getCounter(key); Counters.addInPlace(myInner, inner); total += inner.totalCount(); } } public void addAll(K1 key, Counter<K2> c) { ClassicCounter<K2> myInner = getCounter(key); Counters.addInPlace(myInner, c); total += c.totalCount(); } public void subtractAll(K1 key, Counter<K2> c) { ClassicCounter<K2> myInner = getCounter(key); Counters.subtractInPlace(myInner, c); total -= c.totalCount(); } public void subtractAll(TwoDimensionalCounterInterface<K1, K2> c, boolean removeKeys) { for (K1 key : c.firstKeySet()) { Counter<K2> inner = c.getCounter(key); ClassicCounter<K2> myInner = getCounter(key); Counters.subtractInPlace(myInner, inner); if (removeKeys) Counters.retainNonZeros(myInner); total -= inner.totalCount(); } } /** * Returns the counters with keys as the first key and count as the * total count of the inner counter for that key * * @return counter of type K1 */ public Counter<K1> sumInnerCounter() { Counter<K1> summed = new ClassicCounter<>(); for (K1 key : this.firstKeySet()) { summed.incrementCount(key, this.getCounter(key).totalCount()); } return summed; } public void removeZeroCounts() { Set<K1> firstKeySet = Generics.newHashSet(firstKeySet()); for (K1 k1 : firstKeySet) { ClassicCounter<K2> c = getCounter(k1); Counters.retainNonZeros(c); if (c.size() == 0) map.remove(k1); // it's empty, get rid of it! } } @Override public void remove(K1 key) { ClassicCounter<K2> counter = map.get(key); if (counter != null) { total -= counter.totalCount(); } map.remove(key); } /** * clears the map, total and default value */ public void clear(){ map.clear(); total = 0; defaultValue = 0; } public void clean() { for (K1 key1 : Generics.newHashSet(map.keySet())) { ClassicCounter<K2> c = map.get(key1); for (K2 key2 : Generics.newHashSet(c.keySet())) { if (SloppyMath.isCloseTo(0.0, c.getCount(key2))) { c.remove(key2); } } if (c.keySet().isEmpty()) { map.remove(key1); } } } public MapFactory<K1, ClassicCounter<K2>> getOuterMapFactory() { return outerMF; } public MapFactory<K2, MutableDouble> getInnerMapFactory() { return innerMF; } public TwoDimensionalCounter() { this(MapFactory.<K1, ClassicCounter<K2>> hashMapFactory(), MapFactory.<K2, MutableDouble> hashMapFactory()); } public TwoDimensionalCounter(MapFactory<K1, ClassicCounter<K2>> outerFactory, MapFactory<K2, MutableDouble> innerFactory) { innerMF = innerFactory; outerMF = outerFactory; map = outerFactory.newMap(); total = 0.0; } public static <K1, K2> TwoDimensionalCounter<K1, K2> identityHashMapCounter() { return new TwoDimensionalCounter<>(MapFactory.<K1, ClassicCounter<K2>>identityHashMapFactory(), MapFactory.<K2, MutableDouble>identityHashMapFactory()); } public void recomputeTotal(){ total = 0; for(Entry<K1, ClassicCounter<K2>> c: map.entrySet()){ total += c.getValue().totalCount(); } } public static void main(String[] args) { TwoDimensionalCounter<String, String> cc = new TwoDimensionalCounter<>(); cc.setCount("a", "c", 1.0); cc.setCount("b", "c", 1.0); cc.setCount("a", "d", 1.0); cc.setCount("a", "d", -1.0); cc.setCount("b", "d", 1.0); System.out.println(cc); cc.incrementCount("b", "d", 1.0); System.out.println(cc); TwoDimensionalCounter<String, String> cc2 = TwoDimensionalCounter.reverseIndexOrder(cc); System.out.println(cc2); } }
rupenp/CoreNLP
src/edu/stanford/nlp/stats/TwoDimensionalCounter.java
Java
gpl-2.0
12,954
/* * Copyright (c) 2012, Steve Hannah/Codename One and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Codename One through http://www.codenameone.com/ if you * need additional information or have any questions. */ package com.codename1.javascript; import com.codename1.ui.events.ActionEvent; /** * An event that encapsulates a Javascript method call. When commands are * received in a JavascriptContext via the BrowserNavigationCallback mechanism, * the requests are parsed and wrapped in a JavascriptEvent, which is then fired * and ultimately handled by another event handler to actually call the method. * * <p><strong>NOTE:</strong> The {@link com.codename1.javascript } package is now deprecated. The preferred method of * Java/Javascript interop is to use {@link BrowserComponent#execute(java.lang.String) }, {@link BrowserComponent#execute(java.lang.String, com.codename1.util.SuccessCallback) }, * {@link BrowserComponent#executeAndWait(java.lang.String) }, etc.. as these work asynchronously (except in the XXXAndWait() variants, which * use invokeAndBlock() to make the calls synchronously.</p> * * @author shannah */ class JavascriptEvent extends ActionEvent { Object[] args; String method; public JavascriptEvent(JSObject source, String method, Object[] args){ super(source,ActionEvent.Type.JavaScript); this.args = args; this.method = method; } public Object[] getArgs(){ return args; } public String getMethod(){ return method; } public JSObject getSelf(){ return (JSObject)this.getSource(); } }
codenameone/CodenameOne
CodenameOne/src/com/codename1/javascript/JavascriptEvent.java
Java
gpl-2.0
2,627
/*************************************************************************** main.cpp - Benchmark, derived form app/main.cpp ------------------- begin : 2011-11-15 copyright : (C) 2011 Radim Blazek email : radim dot blazek at gmail dot com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <QCoreApplication> #include <QDir> #include <QFile> #include <QFileInfo> #include <QSettings> #include <QString> #include <QStringList> #include <QTest> #include <cstdio> #include <stdio.h> #include <stdlib.h> #ifdef WIN32 // Open files in binary mode #include <fcntl.h> /* _O_BINARY */ #ifdef MSVC #undef _fmode int _fmode = _O_BINARY; #else // Only do this if we are not building on windows with msvc. // Recommended method for doing this with msvc is with a call to _set_fmode // which is the first thing we do in main(). // Similarly, with MinGW set _fmode in main(). #endif //_MSC_VER #else #include <getopt.h> #endif #ifdef Q_OS_MACX #include <ApplicationServices/ApplicationServices.h> #if MAC_OS_X_VERSION_MAX_ALLOWED < 1050 typedef SInt32 SRefCon; #endif #endif #include "qgsbench.h" #include "qgsapplication.h" #include <qgsconfig.h> #include <qgsversion.h> #include "qgsexception.h" #include "qgsproject.h" #include "qgsproviderregistry.h" #include "qgsrectangle.h" #include "qgslogger.h" /** print usage text */ void usage( std::string const & appName ) { std::cerr << "QGIS Benchmark - " << VERSION << " '" << RELEASE_NAME << "' (" << QGSVERSION << ")\n" << "QGIS (QGIS) Benchmark is console application for QGIS benchmarking\n" << "Usage: " << appName << " [options] [FILES]\n" << " options:\n" << "\t[--iterations iterations]\tnumber of rendering cycles, default 1\n" << "\t[--snapshot filename]\temit snapshot of loaded datasets to given file\n" << "\t[--log filename]\twrite log (JSON) to given file\n" << "\t[--width width]\twidth of snapshot to emit\n" << "\t[--height height]\theight of snapshot to emit\n" << "\t[--project projectfile]\tload the given QGIS project\n" << "\t[--extent xmin,ymin,xmax,ymax]\tset initial map extent\n" << "\t[--optionspath path]\tuse the given QSettings path\n" << "\t[--configpath path]\tuse the given path for all user configuration\n" << "\t[--prefix path]\tpath to a different build of qgis, may be used to test old versions\n" << "\t[--quality]\trenderer hint(s), comma separated, possible values: Antialiasing,TextAntialiasing,SmoothPixmapTransform,NonCosmeticDefaultPen\n" << "\t[--help]\t\tthis text\n\n" << " FILES:\n" << " Files specified on the command line can include rasters,\n" << " vectors, and QGIS project files (.qgs): \n" << " 1. Rasters - Supported formats include GeoTiff, DEM \n" << " and others supported by GDAL\n" << " 2. Vectors - Supported formats include ESRI Shapefiles\n" << " and others supported by OGR and PostgreSQL layers using\n" << " the PostGIS extension\n" ; // OK } // usage() ///////////////////////////////////////////////////////////////// // Command line options 'behaviour' flag setup //////////////////////////////////////////////////////////////// // These two are global so that they can be set by the OpenDocuments // AppleEvent handler as well as by the main routine argv processing // This behaviour will cause QGIS to autoload a project static QString myProjectFileName = ""; // This is the 'leftover' arguments collection static QStringList myFileList; int main( int argc, char *argv[] ) { #ifdef WIN32 // Windows #ifdef _MSC_VER _set_fmode( _O_BINARY ); #else //MinGW _fmode = _O_BINARY; #endif // _MSC_VER #endif // WIN32 ///////////////////////////////////////////////////////////////// // Command line options 'behaviour' flag setup //////////////////////////////////////////////////////////////// // // Parse the command line arguments, looking to see if the user has asked for any // special behaviours. Any remaining non command arguments will be kept aside to // be passed as a list of layers and / or a project that should be loaded. // int myIterations = 1; QString mySnapshotFileName = ""; QString myLogFileName = ""; QString myPrefixPath = ""; int mySnapshotWidth = 800; int mySnapshotHeight = 600; QString myQuality = ""; // This behaviour will set initial extent of map canvas, but only if // there are no command line arguments. This gives a usable map // extent when qgis starts with no layers loaded. When layers are // loaded, we let the layers define the initial extent. QString myInitialExtent = ""; if ( argc == 1 ) myInitialExtent = "-1,-1,1,1"; // The user can specify a path which will override the default path of custom // user settings (~/.qgis) and it will be used for QSettings INI file QString configpath; #ifndef WIN32 //////////////////////////////////////////////////////////////// // USe the GNU Getopts utility to parse cli arguments // Invokes ctor `GetOpt (int argc, char **argv, char *optstring);' /////////////////////////////////////////////////////////////// int optionChar; while ( 1 ) { static struct option long_options[] = { /* These options set a flag. */ {"help", no_argument, 0, '?'}, /* These options don't set a flag. * We distinguish them by their indices. */ {"iterations", required_argument, 0, 'i'}, {"snapshot", required_argument, 0, 's'}, {"log", required_argument, 0, 'l'}, {"width", required_argument, 0, 'w'}, {"height", required_argument, 0, 'h'}, {"project", required_argument, 0, 'p'}, {"extent", required_argument, 0, 'e'}, {"optionspath", required_argument, 0, 'o'}, {"configpath", required_argument, 0, 'c'}, {"prefix", required_argument, 0, 'r'}, {"quality", required_argument, 0, 'q'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; optionChar = getopt_long( argc, argv, "islwhpeocrq", long_options, &option_index ); /* Detect the end of the options. */ if ( optionChar == -1 ) break; switch ( optionChar ) { case 0: /* If this option set a flag, do nothing else now. */ if ( long_options[option_index].flag != 0 ) break; printf( "option %s", long_options[option_index].name ); if ( optarg ) printf( " with arg %s", optarg ); printf( "\n" ); break; case 'i': myIterations = QString( optarg ).toInt(); break; case 's': mySnapshotFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() ); break; case 'l': myLogFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() ); break; case 'w': mySnapshotWidth = QString( optarg ).toInt(); break; case 'h': mySnapshotHeight = QString( optarg ).toInt(); break; case 'p': myProjectFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() ); break; case 'e': myInitialExtent = optarg; break; case 'o': QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optarg ); break; case 'c': configpath = optarg; break; case 'r': myPrefixPath = optarg; break; case 'q': myQuality = optarg; break; case '?': usage( argv[0] ); return 2; // XXX need standard exit codes break; default: QgsDebugMsg( QString( "%1: getopt returned character code %2" ).arg( argv[0] ).arg( optionChar ) ); return 1; // XXX need standard exit codes } } // Add any remaining args to the file list - we will attempt to load them // as layers in the map view further down.... QgsDebugMsg( QString( "Files specified on command line: %1" ).arg( optind ) ); if ( optind < argc ) { while ( optind < argc ) { #ifdef QGISDEBUG int idx = optind; QgsDebugMsg( QString( "%1: %2" ).arg( idx ).arg( argv[idx] ) ); #endif myFileList.append( QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[optind++] ) ).absoluteFilePath() ) ); } } #else for ( int i = 1; i < argc; i++ ) { QString arg = argv[i]; if ( arg == "--help" || arg == "-?" ) { usage( argv[0] ); return 2; } else if ( i + 1 < argc && ( arg == "--iterations" || arg == "-i" ) ) { myIterations = QString( argv[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) ) { mySnapshotFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == "--log" || arg == "-l" ) ) { myLogFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) ) { mySnapshotWidth = QString( argv[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) ) { mySnapshotHeight = QString( argv[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) ) { myProjectFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) ) { myInitialExtent = argv[++i]; } else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) ) { QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, argv[++i] ); } else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) ) { configpath = argv[++i]; QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, configpath ); } else if ( i + 1 < argc && ( arg == "--prefix" ) ) { myPrefixPath = argv[++i]; } else if ( i + 1 < argc && ( arg == "--quality" || arg == "-q" ) ) { myQuality = argv[++i]; } else { myFileList.append( QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[i] ) ).absoluteFilePath() ) ); } } #endif //WIN32 ///////////////////////////////////////////////////////////////////// // Now we have the handlers for the different behaviours... //////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Initialise the application and the translation stuff ///////////////////////////////////////////////////////////////////// if ( !configpath.isEmpty() ) { // tell QSettings to use INI format and save the file in custom config path QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, configpath ); } // TODO: Qt: there should be exactly one QCoreApplication object for console app. // but QgsApplication inherits from QApplication (GUI) // it is working, but maybe we should make QgsCoreApplication, which // could also be used by mapserver // Note (mkuhn,20.4.2013): Labeling does not work with QCoreApplication, because // fontconfig needs some X11 dependencies which are initialized in QApplication (GUI) // using it with QCoreApplication only crashes at the moment. // Only use QgsApplication( int, char **, bool GUIenabled, QString) for newer versions // so that this program may be run with old libraries //QgsApplication myApp( argc, argv, false, configpath ); QCoreApplication *myApp; #if VERSION_INT >= 10900 myApp = new QgsApplication( argc, argv, false ); #else myApp = new QCoreApplication( argc, argv ); #endif if ( myPrefixPath.isEmpty() ) { QDir dir( QCoreApplication::applicationDirPath() ); dir.cdUp(); myPrefixPath = dir.absolutePath(); } QgsApplication::setPrefixPath( myPrefixPath, true ); // Set up the QSettings environment must be done after qapp is created QgsApplication::setOrganizationName( "QGIS" ); QgsApplication::setOrganizationDomain( "qgis.org" ); QgsApplication::setApplicationName( "QGIS2" ); QgsProviderRegistry::instance( QgsApplication::pluginPath() ); #ifdef Q_OS_MACX // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH // is not already defined, use the GDAL plugins in the application bundle. QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) ); if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) ) { setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 ); } #endif QSettings mySettings; // For non static builds on mac and win (static builds are not supported) // we need to be sure we can find the qt image // plugins. In mac be sure to look in the // application bundle... #ifdef Q_WS_WIN QCoreApplication::addLibraryPath( QApplication::applicationDirPath() + QDir::separator() + "qtplugins" ); #endif #ifdef Q_OS_MACX //qDebug("Adding qt image plugins to plugin search path..."); CFURLRef myBundleRef = CFBundleCopyBundleURL( CFBundleGetMainBundle() ); CFStringRef myMacPath = CFURLCopyFileSystemPath( myBundleRef, kCFURLPOSIXPathStyle ); const char *mypPathPtr = CFStringGetCStringPtr( myMacPath, CFStringGetSystemEncoding() ); CFRelease( myBundleRef ); CFRelease( myMacPath ); QString myPath( mypPathPtr ); // if we are not in a bundle assume that the app is built // as a non bundle app and that image plugins will be // in system Qt frameworks. If the app is a bundle // lets try to set the qt plugin search path... QFileInfo myInfo( myPath ); if ( myInfo.isBundle() ) { // First clear the plugin search paths so we can be sure // only plugins from the bundle are being used QStringList myPathList; QCoreApplication::setLibraryPaths( myPathList ); // Now set the paths inside the bundle myPath += "/Contents/plugins"; QCoreApplication::addLibraryPath( myPath ); } #endif QgsBench *qbench = new QgsBench( mySnapshotWidth, mySnapshotHeight, myIterations ); ///////////////////////////////////////////////////////////////////// // If no --project was specified, parse the args to look for a // // .qgs file and set myProjectFileName to it. This allows loading // // of a project file by clicking on it in various desktop managers // // where an appropriate mime-type has been set up. // ///////////////////////////////////////////////////////////////////// if ( myProjectFileName.isEmpty() ) { // check for a .qgs for ( int i = 0; i < argc; i++ ) { QString arg = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[i] ) ).absoluteFilePath() ); if ( arg.contains( ".qgs" ) ) { myProjectFileName = arg; break; } } } ///////////////////////////////////////////////////////////////////// // Load a project file if one was specified ///////////////////////////////////////////////////////////////////// if ( ! myProjectFileName.isEmpty() ) { if ( ! qbench->openProject( myProjectFileName ) ) { fprintf( stderr, "Cannot load project\n" ); return 1; } } if ( ! myQuality.isEmpty() ) { QPainter::RenderHints hints; QStringList list = myQuality.split( ',' ); foreach ( QString q, list ) { if ( q == "Antialiasing" ) hints |= QPainter::Antialiasing; else if ( q == "TextAntialiasing" ) hints |= QPainter::TextAntialiasing; else if ( q == "SmoothPixmapTransform" ) hints |= QPainter::SmoothPixmapTransform; else if ( q == "NonCosmeticDefaultPen" ) hints |= QPainter::NonCosmeticDefaultPen; else { fprintf( stderr, "Unknown quality option\n" ); return 1; } } QgsDebugMsg( QString( "hints: %1" ).arg( hints ) ); qbench->setRenderHints( hints ); } ///////////////////////////////////////////////////////////////////// // autoload any file names that were passed in on the command line ///////////////////////////////////////////////////////////////////// QgsDebugMsg( QString( "Number of files in myFileList: %1" ).arg( myFileList.count() ) ); for ( QStringList::Iterator myIterator = myFileList.begin(); myIterator != myFileList.end(); ++myIterator ) { QgsDebugMsg( QString( "Trying to load file : %1" ).arg(( *myIterator ) ) ); QString myLayerName = *myIterator; // don't load anything with a .qgs extension - these are project files if ( !myLayerName.contains( ".qgs" ) ) { fprintf( stderr, "Data files not yet supported\n" ); return 1; //qbench->openLayer( myLayerName ); } } ///////////////////////////////////////////////////////////////////// // Set initial extent if requested ///////////////////////////////////////////////////////////////////// if ( ! myInitialExtent.isEmpty() ) { double coords[4]; int pos, posOld = 0; bool ok = true; // XXX is it necessary to switch to "C" locale? // parse values from string // extent is defined by string "xmin,ymin,xmax,ymax" for ( int i = 0; i < 3; i++ ) { // find comma and get coordinate pos = myInitialExtent.indexOf( ',', posOld ); if ( pos == -1 ) { ok = false; break; } coords[i] = QString( myInitialExtent.mid( posOld, pos - posOld ) ).toDouble( &ok ); if ( !ok ) break; posOld = pos + 1; } // parse last coordinate if ( ok ) coords[3] = QString( myInitialExtent.mid( posOld ) ).toDouble( &ok ); if ( !ok ) { QgsDebugMsg( "Error while parsing initial extent!" ); } else { // set extent from parsed values QgsRectangle rect( coords[0], coords[1], coords[2], coords[3] ); qbench->setExtent( rect ); } } qbench->render(); if ( mySnapshotFileName != "" ) { qbench->saveSnapsot( mySnapshotFileName ); } if ( myLogFileName != "" ) { qbench->saveLog( myLogFileName ); } qbench->printLog(); delete qbench; delete myApp; QCoreApplication::exit( 0 ); }
innotechsoftware/Quantum-GIS
tests/bench/main.cpp
C++
gpl-2.0
19,308
/**************************************************************************** ** ** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License versions 2.0 or 3.0 as published by the Free ** Software Foundation and appearing in the file LICENSE.GPL included in ** the packaging of this file. Please review the following information ** to ensure GNU General Public Licensing requirements will be met: ** http://www.fsf.org/licensing/licenses/info/GPLv2.html and ** http://www.gnu.org/copyleft/gpl.html. In addition, as a special ** exception, Nokia gives you certain additional rights. These rights ** are described in the Nokia Qt GPL Exception version 1.3, included in ** the file GPL_EXCEPTION.txt in this package. ** ** Qt for Windows(R) Licensees ** As a special exception, Nokia, as the sole copyright holder for Qt ** Designer, grants users of the Qt/Eclipse Integration plug-in the ** right for the Qt/Eclipse Integration to link to functionality ** provided by Qt Designer and its related libraries. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** ****************************************************************************/ /*! \class QFutureSynchronizer \since 4.4 \brief The QFutureSynchronizer class is a convenience class that simplifies QFuture synchronization. QFutureSynchronizer is a template class that simplifies synchronization of one or more QFuture objects. Futures are added using the addFuture() or setFuture() functions. The futures() function returns a list of futures. Use clearFutures() to remove all futures from the QFutureSynchronizer. The waitForFinished() function waits for all futures to finish. The destructor of QFutureSynchronizer calls waitForFinished(), providing an easy way to ensure that all futures have finished before returning from a function: \snippet doc/src/snippets/code/src_corelib_concurrent_qfuturesynchronizer.cpp 0 The behavior of waitForFinished() can be changed using the setCancelOnWait() function. Calling setCancelOnWait(true) will cause waitForFinished() to cancel all futures before waiting for them to finish. You can query the status of the cancel-on-wait feature using the cancelOnWait() function. \sa QFuture, QFutureWatcher, {threads.html#qtconcurrent-intro}{Qt Concurrent} */ /*! \fn QFutureSynchronizer::QFutureSynchronizer() Constructs a QFutureSynchronizer. */ /*! \fn QFutureSynchronizer::QFutureSynchronizer(const QFuture<T> &future) Constructs a QFutureSynchronizer and begins watching \a future by calling addFuture(). \sa addFuture() */ /*! \fn QFutureSynchronizer::~QFutureSynchronizer() Calls waitForFinished() function to ensure that all futures have finished before destroying this QFutureSynchronizer. \sa waitForFinished() */ /*! \fn void QFutureSynchronizer::setFuture(const QFuture<T> &future) Sets \a future to be the only future managed by this QFutureSynchronizer. This is a convenience function that calls waitForFinished(), then clearFutures(), and finally passes \a future to addFuture(). \sa addFuture(), waitForFinished(), clearFutures() */ /*! \fn void QFutureSynchronizer::addFuture(const QFuture<T> &future) Adds \a future to the list of managed futures. \sa futures() */ /*! \fn void QFutureSynchronizer::waitForFinished() Waits for all futures to finish. If cancelOnWait() returns true, each future is canceled before waiting for them to finish. \sa cancelOnWait(), setCancelOnWait() */ /*! \fn void QFutureSynchronizer::clearFutures() Removes all managed futures from this QFutureSynchronizer. \sa addFuture(), setFuture() */ /*! \fn QList<QFuture<T> > QFutureSynchronizer::futures() const Returns a list of all managed futures. \sa addFuture(), setFuture() */ /*! \fn void QFutureSynchronizer::setCancelOnWait(bool enabled) Enables or disables the cancel-on-wait feature based on the \a enabled argument. If \a enabled is true, the waitForFinished() function will cancel all futures before waiting for them to finish. \sa waitForFinished() */ /*! \fn bool QFutureSynchronizer::cancelOnWait() const Returns true if the cancel-on-wait feature is enabled; otherwise returns false. If cancel-on-wait is enabled, the waitForFinished() function will cancel all futures before waiting for them to finish. \sa waitForFinished() */
FilipBE/qtextended
qtopiacore/qt/src/corelib/concurrent/qfuturesynchronizer.cpp
C++
gpl-2.0
5,181
/* * Copyright (C) 2012-2013 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "EpgSearchFilter.h" #include "FileItem.h" #include "ServiceBroker.h" #include "addons/kodi-addon-dev-kit/include/kodi/xbmc_pvr_types.h" #include "utils/TextSearch.h" #include "utils/log.h" #include "pvr/PVRManager.h" #include "pvr/channels/PVRChannelGroupsContainer.h" #include "pvr/epg/EpgContainer.h" #include "pvr/recordings/PVRRecordings.h" #include "pvr/timers/PVRTimers.h" using namespace PVR; CPVREpgSearchFilter::CPVREpgSearchFilter() { Reset(); } void CPVREpgSearchFilter::Reset() { m_strSearchTerm.clear(); m_bIsCaseSensitive = false; m_bSearchInDescription = false; m_iGenreType = EPG_SEARCH_UNSET; m_iGenreSubType = EPG_SEARCH_UNSET; m_iMinimumDuration = EPG_SEARCH_UNSET; m_iMaximumDuration = EPG_SEARCH_UNSET; m_startDateTime.SetFromUTCDateTime(CServiceBroker::GetPVRManager().EpgContainer().GetFirstEPGDate()); if (!m_startDateTime.IsValid()) m_startDateTime.SetFromUTCDateTime(CDateTime::GetUTCDateTime()); // default to 'now' m_endDateTime.SetFromUTCDateTime(CServiceBroker::GetPVRManager().EpgContainer().GetLastEPGDate()); if (!m_endDateTime.IsValid()) m_endDateTime.SetFromUTCDateTime(m_startDateTime + CDateTimeSpan(10, 0, 0, 0)); // default to start + 10 days m_bIncludeUnknownGenres = false; m_bRemoveDuplicates = false; /* pvr specific filters */ m_bIsRadio = false; m_iChannelNumber = EPG_SEARCH_UNSET; m_bFreeToAirOnly = false; m_iChannelGroup = EPG_SEARCH_UNSET; m_bIgnorePresentTimers = true; m_bIgnorePresentRecordings = true; m_iUniqueBroadcastId = EPG_TAG_INVALID_UID; } bool CPVREpgSearchFilter::MatchGenre(const CPVREpgInfoTagPtr &tag) const { bool bReturn(true); if (m_iGenreType != EPG_SEARCH_UNSET) { bool bIsUnknownGenre(tag->GenreType() > EPG_EVENT_CONTENTMASK_USERDEFINED || tag->GenreType() < EPG_EVENT_CONTENTMASK_MOVIEDRAMA); bReturn = ((m_bIncludeUnknownGenres && bIsUnknownGenre) || tag->GenreType() == m_iGenreType); } return bReturn; } bool CPVREpgSearchFilter::MatchDuration(const CPVREpgInfoTagPtr &tag) const { bool bReturn(true); if (m_iMinimumDuration != EPG_SEARCH_UNSET) bReturn = (tag->GetDuration() > m_iMinimumDuration * 60); if (bReturn && m_iMaximumDuration != EPG_SEARCH_UNSET) bReturn = (tag->GetDuration() < m_iMaximumDuration * 60); return bReturn; } bool CPVREpgSearchFilter::MatchStartAndEndTimes(const CPVREpgInfoTagPtr &tag) const { return (tag->StartAsLocalTime() >= m_startDateTime && tag->EndAsLocalTime() <= m_endDateTime); } void CPVREpgSearchFilter::SetSearchPhrase(const std::string &strSearchPhrase) { // match the exact phrase m_strSearchTerm = "\""; m_strSearchTerm.append(strSearchPhrase); m_strSearchTerm.append("\""); } bool CPVREpgSearchFilter::MatchSearchTerm(const CPVREpgInfoTagPtr &tag) const { bool bReturn(true); if (!m_strSearchTerm.empty()) { CTextSearch search(m_strSearchTerm, m_bIsCaseSensitive, SEARCH_DEFAULT_OR); bReturn = search.Search(tag->Title()) || search.Search(tag->PlotOutline()) || (m_bSearchInDescription && search.Search(tag->Plot())); } return bReturn; } bool CPVREpgSearchFilter::MatchBroadcastId(const CPVREpgInfoTagPtr &tag) const { if (m_iUniqueBroadcastId != EPG_TAG_INVALID_UID) return (tag->UniqueBroadcastID() == m_iUniqueBroadcastId); return true; } bool CPVREpgSearchFilter::FilterEntry(const CPVREpgInfoTagPtr &tag) const { return (MatchGenre(tag) && MatchBroadcastId(tag) && MatchDuration(tag) && MatchStartAndEndTimes(tag) && MatchSearchTerm(tag) && MatchTimers(tag) && MatchRecordings(tag)) && (!tag->HasChannel() || (MatchChannelType(tag) && MatchChannelNumber(tag) && MatchChannelGroup(tag) && MatchFreeToAir(tag))); } int CPVREpgSearchFilter::RemoveDuplicates(CFileItemList &results) { unsigned int iSize = results.Size(); for (unsigned int iResultPtr = 0; iResultPtr < iSize; iResultPtr++) { const CPVREpgInfoTagPtr epgentry_1(results.Get(iResultPtr)->GetEPGInfoTag()); if (!epgentry_1) continue; for (unsigned int iTagPtr = 0; iTagPtr < iSize; iTagPtr++) { if (iResultPtr == iTagPtr) continue; const CPVREpgInfoTagPtr epgentry_2(results.Get(iTagPtr)->GetEPGInfoTag()); if (!epgentry_2) continue; if (epgentry_1->Title() != epgentry_2->Title() || epgentry_1->Plot() != epgentry_2->Plot() || epgentry_1->PlotOutline() != epgentry_2->PlotOutline()) continue; results.Remove(iTagPtr); iResultPtr--; iTagPtr--; iSize--; } } return iSize; } bool CPVREpgSearchFilter::MatchChannelType(const CPVREpgInfoTagPtr &tag) const { return (CServiceBroker::GetPVRManager().IsStarted() && tag->Channel()->IsRadio() == m_bIsRadio); } bool CPVREpgSearchFilter::MatchChannelNumber(const CPVREpgInfoTagPtr &tag) const { bool bReturn(true); if (m_iChannelNumber != EPG_SEARCH_UNSET && CServiceBroker::GetPVRManager().IsStarted()) { CPVRChannelGroupPtr group = (m_iChannelGroup != EPG_SEARCH_UNSET) ? CServiceBroker::GetPVRManager().ChannelGroups()->GetByIdFromAll(m_iChannelGroup) : CServiceBroker::GetPVRManager().ChannelGroups()->GetGroupAllTV(); if (!group) group = CServiceBroker::GetPVRManager().ChannelGroups()->GetGroupAllTV(); bReturn = (m_iChannelNumber == (int) group->GetChannelNumber(tag->Channel())); } return bReturn; } bool CPVREpgSearchFilter::MatchChannelGroup(const CPVREpgInfoTagPtr &tag) const { bool bReturn(true); if (m_iChannelGroup != EPG_SEARCH_UNSET && CServiceBroker::GetPVRManager().IsStarted()) { CPVRChannelGroupPtr group = CServiceBroker::GetPVRManager().ChannelGroups()->GetByIdFromAll(m_iChannelGroup); bReturn = (group && group->IsGroupMember(tag->Channel())); } return bReturn; } bool CPVREpgSearchFilter::MatchFreeToAir(const CPVREpgInfoTagPtr &tag) const { return (!m_bFreeToAirOnly || !tag->Channel()->IsEncrypted()); } bool CPVREpgSearchFilter::MatchTimers(const CPVREpgInfoTagPtr &tag) const { return (!m_bIgnorePresentTimers || !CServiceBroker::GetPVRManager().Timers()->GetTimerForEpgTag(tag)); } bool CPVREpgSearchFilter::MatchRecordings(const CPVREpgInfoTagPtr &tag) const { return (!m_bIgnorePresentRecordings || !CServiceBroker::GetPVRManager().Recordings()->GetRecordingForEpgTag(tag)); }
notspiff/xbmc
xbmc/pvr/epg/EpgSearchFilter.cpp
C++
gpl-2.0
7,292
// { dg-do compile { target c++14 } } // Copyright (C) 2014-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // NB: This file is for testing type_traits with NO OTHER INCLUDES. #include <type_traits> using namespace std; static_assert (is_same<typename add_pointer<int>::type, add_pointer_t<int>>(), "add_pointer_t" ); static_assert (is_same<typename add_pointer<long*>::type, add_pointer_t<long*>>(), "add_pointer_t" );
Gurgel100/gcc
libstdc++-v3/testsuite/20_util/add_pointer/requirements/alias_decl.cc
C++
gpl-2.0
1,181
FactoryGirl.define do factory :note do latitude 1 * GeoRecord::SCALE longitude 1 * GeoRecord::SCALE # tile QuadTile.tile_for_point(1,1) factory :note_with_comments do transient do comments_count 1 end after(:create) do |note, evaluator| create_list(:note_comment, evaluator.comments_count, :note => note) end end end end
Zverik/openstreetmap-website
test/factories/notes.rb
Ruby
gpl-2.0
387
/* * Copyright (c) 2009 Dmitry Kazakov <dimula73@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kis_tile_data.h" #include "kis_tile_data_store.h" const qint32 KisTileData::WIDTH = __TILE_DATA_WIDTH; const qint32 KisTileData::HEIGHT = __TILE_DATA_HEIGHT; KisTileMemoryPool4BPP KisTileData::m_pool4BPP; KisTileMemoryPool8BPP KisTileData::m_pool8BPP; KisTileData::KisTileData(qint32 pixelSize, const quint8 *defPixel, KisTileDataStore *store) : m_state(NORMAL), m_mementoFlag(0), m_age(0), m_usersCount(0), m_refCount(0), m_pixelSize(pixelSize), m_store(store) { m_store->checkFreeMemory(); m_data = allocateData(m_pixelSize); fillWithPixel(defPixel); } /** * Duplicating tiledata * + new object loaded in memory * + it's unlocked and has refCount==0 * * NOTE: the memory allocated by the pooler for clones is not counted * by the store in memoryHardLimit. The pooler has it's own slice of * memory and keeps track of the its size itself. So we should be able * to disable the memory check with checkFreeMemory, otherwise, there * is a deadlock. */ KisTileData::KisTileData(const KisTileData& rhs, bool checkFreeMemory) : m_state(NORMAL), m_mementoFlag(0), m_age(0), m_usersCount(0), m_refCount(0), m_pixelSize(rhs.m_pixelSize), m_store(rhs.m_store) { if(checkFreeMemory) { m_store->checkFreeMemory(); } m_data = allocateData(m_pixelSize); memcpy(m_data, rhs.data(), m_pixelSize * WIDTH * HEIGHT); } KisTileData::~KisTileData() { releaseMemory(); } void KisTileData::fillWithPixel(const quint8 *defPixel) { quint8 *it = m_data; for (int i = 0; i < WIDTH*HEIGHT; i++, it += m_pixelSize) { memcpy(it, defPixel, m_pixelSize); } } void KisTileData::releaseMemory() { if (m_data) { freeData(m_data, m_pixelSize); m_data = 0; } KisTileData *clone = 0; while(m_clonesStack.pop(clone)) { delete clone; } Q_ASSERT(m_clonesStack.isEmpty()); } void KisTileData::allocateMemory() { Q_ASSERT(!m_data); m_data = allocateData(m_pixelSize); } quint8* KisTileData::allocateData(const qint32 pixelSize) { switch(pixelSize) { case 4: return (quint8*) m_pool4BPP.pop(); break; case 8: return (quint8*) m_pool8BPP.pop(); break; default: return (quint8*) malloc(pixelSize * WIDTH * HEIGHT); } } void KisTileData::freeData(quint8* ptr, const qint32 pixelSize) { switch(pixelSize) { case 4: return m_pool4BPP.push(ptr); break; case 8: return m_pool8BPP.push(ptr); break; default: free(ptr); } }
wyuka/calligra
krita/image/tiles3/kis_tile_data.cc
C++
gpl-2.0
3,429
<?php /** * Copyright (C) 2013-2015 Graham Breach * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * For more information, please contact <graham@goat1000.com> */ require_once 'SVGGraphAxis.php'; /** * Class for axis with +ve on both sides of zero */ class AxisDoubleEnded extends Axis{ /** * Constructor calls Axis constructor with 1/5 length */ public function __construct($length, $max_val, $min_val, $min_unit, $fit, $units_before, $units_after, $decimal_digits, $label_callback) { if($min_val < 0) throw new Exception('Negative value for double-ended axis'); parent::__construct($length / 2, $max_val, $min_val, $min_unit, $fit, $units_before, $units_after, $decimal_digits, $label_callback); } /** * Returns the distance along the axis where 0 should be */ public function Zero() { return $this->zero = $this->length; } /** * Returns the grid points as an array of GridPoints */ public function GetGridPoints($min_space, $start) { $points = parent::GetGridPoints($min_space, $start); $new_points = array(); $z = $this->Zero(); foreach($points as $p) { $new_points[] = new GridPoint($p->position + $z, $p->text, $p->value); if($p->value != 0) $new_points[] = new GridPoint((2 * $start) + $z - $p->position, $p->text, $p->value); } usort($new_points, ($this->direction < 0 ? 'gridpoint_rsort' : 'gridpoint_sort')); return $new_points; } /** * Returns the grid subdivision points as an array */ public function GetGridSubdivisions($min_space, $min_unit, $start, $fixed) { $divs = parent::GetGridSubdivisions($min_space, $min_unit, $start, $fixed); $new_divs = array(); $z = $this->Zero(); foreach($divs as $d) { $new_divs[] = new GridPoint($d->position + $z, '', 0); $new_divs[] = new GridPoint((2 * $start) + $z - $d->position, '', 0); } return $new_divs; } }
jwweider/manhattantrainer
sites/all/libraries/SVGGraph/SVGGraphAxisDoubleEnded.php
PHP
gpl-2.0
2,576
// { dg-do compile { target c++17 } } // Copyright (C) 2020-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-error "must be a complete class" "" { target *-*-* } 0 } #include <type_traits> class X; void test01() { std::is_nothrow_invocable<int(X), X>(); // { dg-error "required from here" } std::is_nothrow_invocable<int(int, X), int, X>(); // { dg-error "required from here" } std::is_nothrow_invocable<int(int, X), X, int>(); // { dg-error "required from here" } std::is_nothrow_invocable<int(X&), X&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable<int(int, X&), int, X&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable<int(X&&), X&&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable<int(int, X&&), int, X&&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable<int(const X&&), const X&&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable<int(int, const X&&), int, const X&&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable<int(const X&), const X&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable<int(int, const X&), int, const X&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable<int(const X&), X&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable<int(int, const X&), int, X&>(); // { dg-bogus "required from here" } } void test02() { std::is_nothrow_invocable_r<int, int(X), X>(); // { dg-error "required from here" } std::is_nothrow_invocable_r<int, int(int, X), int, X>(); // { dg-error "required from here" } std::is_nothrow_invocable_r<int, int(int, X), X, int>(); // { dg-error "required from here" } std::is_nothrow_invocable_r<int, int(X&), X&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable_r<int, int(int, X&), int, X&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable_r<int, int(X&&), X&&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable_r<int, int(int, X&&), int, X&&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable_r<int, int(const X&&), const X&&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable_r<int, int(int, const X&&), int, const X&&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable_r<int, int(const X&), const X&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable_r<int, int(int, const X&), int, const X&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable_r<int, int(const X&), X&>(); // { dg-bogus "required from here" } std::is_nothrow_invocable_r<int, int(int, const X&), int, X&>(); // { dg-bogus "required from here" } }
Gurgel100/gcc
libstdc++-v3/testsuite/20_util/is_nothrow_invocable/incomplete_args_neg.cc
C++
gpl-2.0
3,439
<?php /** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo\Total; /** * Class DiscountTest */ class DiscountTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\Sales\Model\Order\Creditmemo\Total\Cost */ protected $total; /** * @var \Magento\Sales\Model\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject */ protected $creditmemoMock; /** * @var \Magento\Sales\Model\Order\Creditmemo\Item|\PHPUnit_Framework_MockObject_MockObject */ protected $creditmemoItemMock; /** * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject */ protected $orderMock; /** * @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject */ protected $orderItemMock; public function setUp() { $this->orderMock = $this->getMock( 'Magento\Sales\Model\Order', ['getBaseShippingDiscountAmount', 'getBaseShippingAmount', 'getShippingAmount'], [], '', false ); $this->orderItemMock = $this->getMock( 'Magento\Sales\Model\Order', [ 'isDummy', 'getDiscountInvoiced', 'getBaseDiscountInvoiced', 'getQtyInvoiced', 'getQty', 'getDiscountRefunded', 'getQtyRefunded' ], [], '', false ); $this->creditmemoMock = $this->getMock( '\Magento\Sales\Model\Order\Creditmemo', [ 'setBaseCost', 'getAllItems', 'getOrder', 'getBaseShippingAmount', 'roundPrice', 'setDiscountAmount', 'setBaseDiscountAmount' ], [], '', false ); $this->creditmemoItemMock = $this->getMock( '\Magento\Sales\Model\Order\Creditmemo\Item', [ 'getHasChildren', 'getBaseCost', 'getQty', 'getOrderItem', 'setDiscountAmount', 'setBaseDiscountAmount', 'isLast' ], [], '', false ); $this->total = new \Magento\Sales\Model\Order\Creditmemo\Total\Discount(); } public function testCollect() { $this->creditmemoMock->expects($this->exactly(2)) ->method('setDiscountAmount') ->willReturnSelf(); $this->creditmemoMock->expects($this->exactly(2)) ->method('setBaseDiscountAmount') ->willReturnSelf(); $this->creditmemoMock->expects($this->once()) ->method('getOrder') ->willReturn($this->orderMock); $this->creditmemoMock->expects($this->once()) ->method('getBaseShippingAmount') ->willReturn(1); $this->orderMock->expects($this->once()) ->method('getBaseShippingDiscountAmount') ->willReturn(1); $this->orderMock->expects($this->exactly(2)) ->method('getBaseShippingAmount') ->willReturn(1); $this->orderMock->expects($this->once()) ->method('getShippingAmount') ->willReturn(1); $this->creditmemoMock->expects($this->once()) ->method('getAllItems') ->willReturn([$this->creditmemoItemMock]); $this->creditmemoItemMock->expects($this->atLeastOnce()) ->method('getOrderItem') ->willReturn($this->orderItemMock); $this->orderItemMock->expects($this->once()) ->method('isDummy') ->willReturn(false); $this->orderItemMock->expects($this->once()) ->method('getDiscountInvoiced') ->willReturn(1); $this->orderItemMock->expects($this->once()) ->method('getBaseDiscountInvoiced') ->willReturn(1); $this->orderItemMock->expects($this->once()) ->method('getQtyInvoiced') ->willReturn(1); $this->orderItemMock->expects($this->once()) ->method('getDiscountRefunded') ->willReturn(1); $this->orderItemMock->expects($this->once()) ->method('getQtyRefunded') ->willReturn(0); $this->creditmemoItemMock->expects($this->once()) ->method('isLast') ->willReturn(false); $this->creditmemoItemMock->expects($this->atLeastOnce()) ->method('getQty') ->willReturn(1); $this->creditmemoItemMock->expects($this->exactly(1)) ->method('setDiscountAmount') ->willReturnSelf(); $this->creditmemoItemMock->expects($this->exactly(1)) ->method('setBaseDiscountAmount') ->willReturnSelf(); $this->creditmemoMock->expects($this->exactly(2)) ->method('roundPrice') ->willReturnMap( [ [1, 'regular', true, 1], [1, 'base', true, 1] ] ); $this->assertEquals($this->total, $this->total->collect($this->creditmemoMock)); } public function testCollectZeroShipping() { $this->creditmemoMock->expects($this->exactly(2)) ->method('setDiscountAmount') ->willReturnSelf(); $this->creditmemoMock->expects($this->exactly(2)) ->method('setBaseDiscountAmount') ->willReturnSelf(); $this->creditmemoMock->expects($this->once()) ->method('getOrder') ->willReturn($this->orderMock); $this->creditmemoMock->expects($this->once()) ->method('getBaseShippingAmount') ->willReturn('0.0000'); $this->orderMock->expects($this->never()) ->method('getBaseShippingDiscountAmount'); $this->orderMock->expects($this->never()) ->method('getBaseShippingAmount'); $this->orderMock->expects($this->never()) ->method('getShippingAmount'); $this->creditmemoMock->expects($this->once()) ->method('getAllItems') ->willReturn([$this->creditmemoItemMock]); $this->creditmemoItemMock->expects($this->atLeastOnce()) ->method('getOrderItem') ->willReturn($this->orderItemMock); $this->orderItemMock->expects($this->once()) ->method('isDummy') ->willReturn(false); $this->orderItemMock->expects($this->once()) ->method('getDiscountInvoiced') ->willReturn(1); $this->orderItemMock->expects($this->once()) ->method('getBaseDiscountInvoiced') ->willReturn(1); $this->orderItemMock->expects($this->once()) ->method('getQtyInvoiced') ->willReturn(1); $this->orderItemMock->expects($this->once()) ->method('getDiscountRefunded') ->willReturn(1); $this->orderItemMock->expects($this->once()) ->method('getQtyRefunded') ->willReturn(0); $this->creditmemoItemMock->expects($this->once()) ->method('isLast') ->willReturn(false); $this->creditmemoItemMock->expects($this->atLeastOnce()) ->method('getQty') ->willReturn(1); $this->creditmemoItemMock->expects($this->exactly(1)) ->method('setDiscountAmount') ->willReturnSelf(); $this->creditmemoItemMock->expects($this->exactly(1)) ->method('setBaseDiscountAmount') ->willReturnSelf(); $this->creditmemoMock->expects($this->exactly(2)) ->method('roundPrice') ->willReturnMap( [ [1, 'regular', true, 1], [1, 'base', true, 1] ] ); $this->assertEquals($this->total, $this->total->collect($this->creditmemoMock)); } }
FPLD/project0
vendor/magento/module-sales/Test/Unit/Model/Order/Creditmemo/Total/DiscountTest.php
PHP
gpl-2.0
7,953
<?php /** * Simple product add to cart * * @author WooThemes * @package WooCommerce/Templates * @version 2.1.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $woocommerce, $product; if ( ! $product->is_purchasable() ) return; ?> <?php /// Availability $availability = $product->get_availability(); if ( $availability['availability'] ) echo apply_filters( 'woocommerce_stock_html', '<p class="stock ' . esc_attr( $availability['class'] ) . '">' . esc_html( $availability['availability'] ) . '</p>', $availability['availability'] ); ?> <?php if ( $product->is_in_stock() ) : ?> <?php do_action('woocommerce_before_add_to_cart_form'); ?> <form class="cart" method="post" enctype='multipart/form-data'> <label class="qtylabel"><?php _e( 'QTY', THB_THEME_NAME ); ?></label> <?php do_action('woocommerce_before_add_to_cart_button'); ?> <?php if ( ! $product->is_sold_individually() ) woocommerce_quantity_input( array( 'min_value' => apply_filters( 'woocommerce_quantity_input_min', 1, $product ), 'max_value' => apply_filters( 'woocommerce_quantity_input_max', $product->backorders_allowed() ? '' : $product->get_stock_quantity(), $product ) ) ); ?> <input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $product->id ); ?>" /> <button type="submit" class="single_add_to_cart_button btn outline"><?php echo $product->single_add_to_cart_text(); ?></button> <?php do_action('woocommerce_after_add_to_cart_button'); ?> </form> <?php do_action('woocommerce_after_add_to_cart_form'); ?> <?php else : ?> <p class="stock out-of-stock"><?php _e( 'This product is currently out of stock and unavailable.',THB_THEME_NAME ); ?></p> <?php endif; ?>
ardiqghenatya/web4
wp-content/themes/north-wp/woocommerce/single-product/add-to-cart/simple.php
PHP
gpl-2.0
1,759
/* YUI 3.7.1 (build 5627) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('charts', function (Y, NAME) { /** * The Chart class is the basic application used to create a chart. * * @module charts * @class Chart * @constructor */ function Chart(cfg) { if(cfg.type != "pie") { return new Y.CartesianChart(cfg); } else { return new Y.PieChart(cfg); } } Y.Chart = Chart; }, '3.7.1', {"requires": ["charts-base"]});
medbenhenda/migration-ez5
ezpublish_legacy/extension/ezjscore/design/standard/lib/yui/3.7.1/build/charts/charts.js
JavaScript
gpl-2.0
533
require 'flag_query' class Admin::FlagsController < Admin::AdminController def index # we may get out of sync, fix it here PostAction.update_flagged_posts_count posts, topics, users = FlagQuery.flagged_posts_report(current_user, params[:filter], params[:offset].to_i, 10) if posts.blank? render json: { posts: [], topics: [], users: [] } else render json: MultiJson.dump({ posts: posts, topics: serialize_data(topics, FlaggedTopicSerializer), users: serialize_data(users, FlaggedUserSerializer) }) end end def agree params.permit(:id, :action_on_post) post = Post.find(params[:id]) post_action_type = PostAction.post_action_type_for_post(post.id) keep_post = params[:action_on_post] == "keep" delete_post = params[:action_on_post] == "delete" PostAction.agree_flags!(post, current_user, delete_post) if delete_post PostDestroyer.new(current_user, post).destroy elsif !keep_post PostAction.hide_post!(post, post_action_type) end render nothing: true end def disagree params.permit(:id) post = Post.find(params[:id]) PostAction.clear_flags!(post, current_user) post.unhide! render nothing: true end def defer params.permit(:id, :delete_post) post = Post.find(params[:id]) PostAction.defer_flags!(post, current_user, params[:delete_post]) PostDestroyer.new(current_user, post).destroy if params[:delete_post] render nothing: true end end
sassafrastech/discourse-diaedu
app/controllers/admin/flags_controller.rb
Ruby
gpl-2.0
1,527
<?php /** * @Project NUKEVIET 3.x * @Author VINADES.,JSC (contact@vinades.vn) * @Copyright (C) 2012 VINADES.,JSC. All rights reserved * @Language 日本語 * @Createdate Apr 15, 2011, 08:22:00 AM */ if( ! defined( 'NV_MAINFILE' ) ) die( 'Stop!!!' ); $lang_translator['author'] = 'VINADES.,JSC (contact@vinades.vn)'; $lang_translator['createdate'] = '15/04/2011, 15:22'; $lang_translator['copyright'] = '@Copyright (C) 2010 VINADES.,JSC. All rights reserved'; $lang_translator['info'] = 'Language translated from http://translate.nukeviet.vn'; $lang_translator['langtype'] = 'lang_module'; $lang_block['htmlcontent'] = 'ブロックに内容を入力してください。'; ?>
anhnthpu/nukevietCAS
language/ja/block.global.html.php
PHP
gpl-2.0
680
package edu.jhu.agiga; import java.io.IOException; import java.io.Writer; import java.io.Serializable; import java.util.List; import edu.jhu.agiga.AgigaConstants.DependencyForm; import edu.stanford.nlp.ling.WordLemmaTag; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.trees.TreeGraphNode; import edu.stanford.nlp.trees.TypedDependency; /** * AgigaSentence provides access to the sentence-level annotations: AgigaToken * objects, AgigaTypedDependency objects for the three dependency forms, the * contituency parse as text, and the Stanford parser API objects for * dependencies and constituency parses. * * This class also provides methods for writing out these various annotations in * human-readable formats and some common machine-readable formats. * * @author mgormley * */ public interface AgigaSentence extends Serializable { @Override public boolean equals(Object other); @Override public int hashCode(); public int getSentIdx(); public List<AgigaToken> getTokens(); public String getParseText(); public List<AgigaTypedDependency> getAgigaDeps(DependencyForm form); public List<AgigaTypedDependency> getBasicDeps(); public List<AgigaTypedDependency> getColDeps(); public List<AgigaTypedDependency> getColCcprocDeps(); // -------- Stanford API methods -------- public List<WordLemmaTag> getStanfordWordLemmaTags(); public List<TypedDependency> getStanfordTypedDependencies(DependencyForm form); public List<TreeGraphNode> getStanfordTreeGraphNodes(DependencyForm form); public Tree getStanfordContituencyTree(); // -------- Printing methods -------- public void writeWords(Writer writer) throws IOException; public void writeLemmas(Writer writer) throws IOException; public void writeTokens(Writer writer, boolean useLemmas, boolean useNormNer) throws IOException; public void writePosTags(Writer writer) throws IOException; public void writeNerTags(Writer writer) throws IOException; public void writeTags(Writer writer, boolean useLemmas, boolean useNormNer, boolean useNerTags) throws IOException; public void writeConnlStyleDeps(Writer writer, DependencyForm form) throws IOException; public void writeParseText(Writer writer) throws IOException; }
mgormley/agiga
src/main/java/edu/jhu/agiga/AgigaSentence.java
Java
gpl-2.0
2,312
<?php /******************************************************************************* * * filename : Reports/AdvancedDeposit.php * last change : 2013-02-21 * description : Creates a PDF customized Deposit Report . * * ChurchInfo is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * ******************************************************************************/ require "../Include/Config.php"; require "../Include/Functions.php"; require "../Include/ReportFunctions.php"; require "../Include/ReportConfig.php"; // Security if (!$_SESSION['bFinance'] && !$_SESSION['bAdmin']) { Redirect("Menu.php"); exit; } // Filter values $sort = FilterInput($_POST["sort"]); $detail_level = FilterInput($_POST["detail_level"]); $datetype = FilterInput($_POST["datetype"]); $output = FilterInput($_POST["output"]); $sDateStart = FilterInput($_POST["DateStart"],"date"); $sDateEnd = FilterInput($_POST["DateEnd"],"date"); $iDepID = FilterInput($_POST["deposit"],"int"); if (!empty($_POST["classList"])) { $classList = $_POST["classList"]; if ($classList[0]) { $sSQL = "SELECT * FROM list_lst WHERE lst_ID = 1 ORDER BY lst_OptionSequence"; $rsClassifications = RunQuery($sSQL); $inClassList = "("; $notInClassList = "("; while ($aRow = mysql_fetch_array($rsClassifications)) { extract($aRow); if (in_array($lst_OptionID, $classList)) { if ($inClassList == "(") { $inClassList .= $lst_OptionID; } else { $inClassList .= "," . $lst_OptionID; } } else { if ($notInClassList == "(") { $notInClassList .= $lst_OptionID; } else { $notInClassList .= "," . $lst_OptionID; } } } $inClassList .= ")"; $notInClassList .= ")"; } } if (!empty($_POST["family"])) { $familyList = $_POST["family"]; } if (!$sort) $sort = "deposit"; if (!$detail_level) $detail_level = "detail"; if (!$output) $output = "pdf"; // If CSVAdminOnly option is enabled and user is not admin, redirect to the menu. if (!$_SESSION['bAdmin'] && $bCSVAdminOnly && $output != "pdf") { Redirect("Menu.php"); exit; } // Build SQL Query // Build SELECT SQL Portion $sSQL = "SELECT DISTINCT fam_ID, fam_Name, fam_Address1, fam_Address2, fam_City, fam_State, fam_Zip, fam_Country, plg_date, plg_amount, plg_method, plg_comment, plg_depID, plg_CheckNo, fun_ID, fun_Name, dep_Date FROM pledge_plg"; $sSQL .= " LEFT JOIN family_fam ON plg_FamID=fam_ID"; $sSQL .= " INNER JOIN deposit_dep ON plg_depID = dep_ID"; $sSQL .= " LEFT JOIN donationfund_fun ON plg_fundID=fun_ID"; if ($classList[0]) { $sSQL .= " LEFT JOIN person_per ON fam_ID=per_fam_ID"; } $sSQL .= " WHERE plg_PledgeOrPayment='Payment'"; // Add SQL criteria // Report Dates OR Deposit ID if ($iDepID > 0) $sSQL .= " AND plg_depID='$iDepID' "; else { $today = date("Y-m-d"); if (!$sDateEnd && $sDateStart) $sDateEnd = $sDateStart; if (!$sDateStart && $sDateEnd) $sDateStart = $sDateEnd; if (!$sDateStart && !$sDateEnd){ $sDateStart = $today; $sDateEnd = $today; } if ($sDateStart > $sDateEnd){ $temp = $sDateStart; $sDateStart = $sDateEnd; $sDateEnd = $temp; } if ($datetype == "Payment") $sSQL .= " AND plg_date BETWEEN '$sDateStart' AND '$sDateEnd' "; else $sSQL .= " AND dep_Date BETWEEN '$sDateStart' AND '$sDateEnd' "; } // Filter by Fund if (!empty($_POST["funds"])) { $count = 0; foreach ($_POST["funds"] as $fundID) { $fund[$count++] = FilterInput($fundID,'int'); } if ($count == 1) { if ($fund[0]) $sSQL .= " AND plg_fundID='$fund[0]' "; } else { $sSQL .= " AND (plg_fundID ='$fund[0]'"; for($i = 1; $i < $count; $i++) { $sSQL .= " OR plg_fundID='$fund[$i]'"; } $sSQL .= ") "; } } // Filter by Family if ($familyList) { $count = 0; foreach ($familyList as $famID) { $fam[$count++] = FilterInput($famID,'int'); } if ($count == 1) { if ($fam[0]) { $sSQL .= " AND plg_FamID='$fam[0]' "; } } else { $sSQL .= " AND (plg_FamID='$fam[0]'"; for($i = 1; $i < $count; $i++) { $sSQL .= " OR plg_FamID='$fam[$i]'"; } $sSQL .= " ) "; } } if ($classList[0]) { $sSQL .= " AND per_cls_ID IN " . $inClassList . " AND per_fam_ID NOT IN (SELECT DISTINCT per_fam_ID FROM person_per WHERE per_cls_ID IN " . $notInClassList . ")"; } // Filter by Payment Method if (!empty($_POST["method"])) { $count = 0; foreach ($_POST["method"] as $MethodItem) { $aMethod[$count++] = FilterInput($MethodItem); } if ($count == 1) { if ($aMethod[0]) $sSQL .= " AND plg_method='$aMethod[0]' "; } else { $sSQL .= " AND (plg_method='$aMethod[0]' "; for($i = 1; $i < $count; $i++) { $sSQL .= " OR plg_method='$aMethod[$i]'"; } $sSQL .= ") "; } } // Add SQL ORDER if ($sort == "deposit") $sSQL .= " ORDER BY plg_depID, fun_Name, fam_Name, fam_ID"; elseif ($sort == "fund") $sSQL .= " ORDER BY fun_Name, fam_Name, fam_ID, plg_depID "; elseif ($sort == "family") $sSQL .= " ORDER BY fam_Name, fam_ID, fun_Name, plg_depID"; //var_dump($sSQL); //Execute SQL Statement $rsReport = RunQuery($sSQL); // Exit if no rows returned $iCountRows = mysql_num_rows($rsReport); if ($iCountRows < 1){ header("Location: ../FinancialReports.php?ReturnMessage=NoRows&ReportType=Advanced%20Deposit%20Report"); } // Create PDF Report -- PDF // *************************** if ($output == "pdf") { // Set up bottom border value $bottom_border = 250; $summaryIntervalY = 4; $page = 1; class PDF_TaxReport extends ChurchInfoReport { // Constructor function PDF_TaxReport() { parent::FPDF("P", "mm", $this->paperFormat); $this->SetFont("Times",'',10); $this->SetMargins(20,15); $this->Open(); $this->SetAutoPageBreak(false); } function PrintRightJustified ($x, $y, $str) { $iLen = strlen ($str); $nMoveBy = 2 * $iLen; $this->SetXY ($x - $nMoveBy, $y); $this->Write (8, $str); } function StartFirstPage () { global $sDateStart, $sDateEnd, $sort, $iDepID, $datetype; $this->AddPage(); $curY = 20; $curX = 60; $this->SetFont('Times','B', 14); $this->WriteAt ($curX, $curY, $this->sChurchName . " Deposit Report"); $curY += 2 * $this->incrementY; $this->SetFont('Times','B', 10); $curX = $this->leftX; $this->WriteAt ($curX, $curY, "Data sorted by " . ucwords($sort)); $curY += $this->incrementY; if (!$iDepID) { $this->WriteAt ($curX, $curY, "$datetype Dates: $sDateStart through $sDateEnd"); $curY += $this->incrementY; } if ($iDepID || $_POST['family'][0] || $_POST['funds'][0] || $_POST['method'][0]){ $heading = "Filtered by "; if ($iDepID) $heading .= "Deposit #$iDepID, "; if ($_POST['family'][0]) $heading .= "Selected Families, "; if ($_POST['funds'][0]) $heading .= "Selected Funds, "; if ($_POST['method'][0]) $heading .= "Selected Payment Methods, "; $heading = substr($heading,0,-2); } else { $heading = "Showing all records for report dates."; } $this->WriteAt ($curX, $curY, $heading); $curY += 2 * $this->incrementY; $this->SetFont("Times",'',10); return ($curY); } function PageBreak ($page) { // Finish footer of previous page if neccessary and add new page global $curY, $bottom_border, $detail_level; if ($curY > $bottom_border){ $this->FinishPage($page); $page++; $this->AddPage(); $curY = 20; if ($detail_level == "detail") $curY = $this->Headings($curY); } return $page; } function Headings ($curY) { global $sort, $summaryIntervalY; if ($sort == "deposit"){ $curX = $this->leftX; $this->SetFont('Times','BU', 10); $this->WriteAt ($curX, $curY, "Chk No."); $this->WriteAt (40, $curY, "Fund"); $this->WriteAt (80, $curY, "Recieved From"); $this->WriteAt (135, $curY, "Memo"); $this->WriteAt (181, $curY, "Amount"); $curY += 2 * $summaryIntervalY; } elseif ($sort == "fund") { $curX = $this->leftX; $this->SetFont('Times','BU', 10); $this->WriteAt ($curX, $curY, "Chk No."); $this->WriteAt (40, $curY, "Deposit No./ Date"); $this->WriteAt (80, $curY, "Recieved From"); $this->WriteAt (135, $curY, "Memo"); $this->WriteAt (181, $curY, "Amount"); $curY += 2 * $summaryIntervalY; } elseif ($sort == "family") { $curX = $this->leftX; $this->SetFont('Times','BU', 10); $this->WriteAt ($curX, $curY, "Chk No."); $this->WriteAt (40, $curY, "Deposit No./Date"); $this->WriteAt (80, $curY, "Fund"); $this->WriteAt (135, $curY, "Memo"); $this->WriteAt (181, $curY, "Amount"); $curY += 2 * $summaryIntervalY; } return ($curY); } function FinishPage ($page) { $footer = "Page $page Generated on " . date("Y-m-d H:i:s"); $this->SetFont("Times",'I',9); $this->WriteAt (80, 258, $footer); } } // Instantiate the directory class and build the report. $pdf = new PDF_TaxReport(); // Read in report settings from database $rsConfig = mysql_query("SELECT cfg_name, IFNULL(cfg_value, cfg_default) AS value FROM config_cfg WHERE cfg_section='ChurchInfoReport'"); if ($rsConfig) { while (list($cfg_name, $cfg_value) = mysql_fetch_row($rsConfig)) { $pdf->$cfg_name = $cfg_value; } } $curY = $pdf->StartFirstPage (); $curX = 0; $currentDepositID = 0; $currentFundID = 0; $totalAmount = 0; $totalFund = array(); $countFund = 0; $countDeposit = 0; $countReport = 0; $currentFundAmount = 0; $currentDepositAmount = 0; $currentReportAmount = 0; // ********************** // Sort by Deposit Report // ********************** if ($sort == "deposit") { if ($detail_level == "detail") $curY = $pdf->Headings($curY); while ($aRow = mysql_fetch_array($rsReport)) { extract ($aRow); if (!$fun_ID){ $fun_ID = -1; $fun_Name = "Undesignated"; } if (!$fam_ID) { $fam_ID = -1; $fam_Name = "Unassigned"; } // First Deposit Heading if (!$currentDepositID && $detail_level != "summary"){ $sDepositTitle = "Deposit #$plg_depID ($dep_Date)"; $pdf->SetFont("Times",'B',10); $pdf->WriteAt(20,$curY, $sDepositTitle); $curY += 1.5 * $summaryIntervalY; } // Check for new fund if (($currentFundID != $fun_ID || $currentDepositID != $plg_depID) && $currentFundID && $detail_level != "summary") { // New Fund. Print Previous Fund Summary if ($countFund > 1) $item = gettext("items"); else $item = gettext("item"); $sFundSummary = "$currentFundName Total - $countFund $item: $" . number_format($currentFundAmount, 2, '.', ','); $curY +=2; $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'I',10); $pdf->Cell (176, $summaryIntervalY, $sFundSummary,0,0,"R"); $curY += 1.75 * $summaryIntervalY; $countFund = 0; $currentFundAmount = 0; $page = $pdf->PageBreak($page); } // Check for new deposit if ($currentDepositID != $plg_depID && $currentDepositID) { // New Deposit ID. Print Previous Deposit Summary if ($countDeposit > 1) $item = gettext("items"); else $item = gettext("item"); $sDepositSummary = "Deposit #$currentDepositID Total - $countDeposit $item: $" . number_format($currentDepositAmount, 2, '.', ','); $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'B',10); $pdf->Cell (176, $summaryIntervalY, $sDepositSummary,0,0,"R"); $curY += 2 * $summaryIntervalY; if ($detail_level != "summary") $pdf->line(40,$curY-2,195,$curY-2); $page = $pdf->PageBreak($page); // New Deposit Title if ($detail_level != "summary") { $sDepositTitle = "Deposit #$plg_depID ($dep_Date)"; $pdf->SetFont("Times",'B',10); $pdf->WriteAt(20,$curY, $sDepositTitle); $curY += 1.5 * $summaryIntervalY; } $countDeposit = 0; $currentDepositAmount = 0; } // Print Deposit Detail if ($detail_level == "detail"){ // Format Data if ($plg_method == "CREDITCARD") $plg_method = "CREDIT"; if ($plg_method == "BANKDRAFT") $plg_method = "DRAFT"; if ($plg_method != "CHECK") $plg_CheckNo = $plg_method; if (strlen($plg_CheckNo) > 8) $plg_CheckNo = "...".substr($plg_CheckNo,-8,8); if (strlen($fun_Name) > 22) $sfun_Name = substr($fun_Name,0,21) . "..."; else $sfun_Name = $fun_Name; if (strlen($plg_comment) > 29) $plg_comment = substr($plg_comment,0,28) . "..."; $fam_Name = $fam_Name . " - " . $fam_Address1; if (strlen($fam_Name) > 31) $fam_Name = substr($fam_Name,0,30) . "..."; // Print Data $pdf->SetFont('Times','', 10); $pdf->SetXY($pdf->leftX,$curY); $pdf->Cell (16, $summaryIntervalY, $plg_CheckNo,0,0,"R"); $pdf->Cell (40, $summaryIntervalY, $sfun_Name); $pdf->Cell (55, $summaryIntervalY, $fam_Name); $pdf->Cell (40, $summaryIntervalY, $plg_comment); $pdf->SetFont('Courier','', 9); $pdf->Cell (25, $summaryIntervalY, $plg_amount,0,0,"R"); $pdf->SetFont('Times','', 10); $curY += $summaryIntervalY; $page = $pdf->PageBreak($page); } // Update running totals $totalAmount += $plg_amount; if (array_key_exists ($fun_Name, $totalFund)) $totalFund[$fun_Name] += $plg_amount; else $totalFund[$fun_Name] = $plg_amount; $countFund ++; $countDeposit ++; $countReport ++; $currentFundAmount += $plg_amount; $currentDepositAmount += $plg_amount; $currentReportAmount += $plg_amount; $currentDepositID = $plg_depID; $currentFundID = $fun_ID; $currentFundName = $fun_Name; $currentDepositDate = $dep_Date; } // Print Final Summary // Print Fund Summary if ($detail_level != "summary") { if ($countFund > 1) $item = gettext("items"); else $item = gettext("item"); $sFundSummary = "$fun_Name Total - $countFund $item: $" . number_format($currentFundAmount, 2, '.', ','); $curY += 2; $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'I',10); $pdf->Cell (176, $summaryIntervalY, $sFundSummary,0,0,"R"); $curY += 1.75 * $summaryIntervalY; $page = $pdf->PageBreak($page); } // Print Deposit Summary if ($countDeposit > 1) $item = gettext("items"); else $item = gettext("item"); $sDepositSummary = "Deposit #$currentDepositID Total - $countDeposit $item: $" . number_format($currentDepositAmount, 2, '.', ','); $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'B',10); $pdf->Cell (176, $summaryIntervalY, $sDepositSummary,0,0,"R"); $curY += 2 * $summaryIntervalY; $page = $pdf->PageBreak($page); } elseif ($sort == "fund") { // ********************** // Sort by Fund Report // ********************** if ($detail_level == "detail") $curY = $pdf->Headings($curY); while ($aRow = mysql_fetch_array($rsReport)) { extract ($aRow); if (!$fun_ID){ $fun_ID = -1; $fun_Name = "Undesignated"; } if (!$fam_ID) { $fam_ID = -1; $fam_Name = "Unassigned"; } // First Fund Heading if (!$currentFundName && $detail_level != "summary"){ $sFundTitle = "Fund: $fun_Name"; $pdf->SetFont("Times",'B',10); $pdf->WriteAt(20,$curY, $sFundTitle); $curY += 1.5 * $summaryIntervalY; } // Check for new Family if (($currentFamilyID != $fam_ID || $currentFundID != $fun_ID) && $currentFamilyID && $detail_level != "summary") { // New Family. Print Previous Family Summary if ($countFamily > 1) $item = gettext("items"); else $item = gettext("item"); $sFamilySummary = "$currentFamilyName - $currentFamilyAddress - $countFamily $item: $" . number_format($currentFamilyAmount, 2, '.', ','); $curY +=2; $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'I',10); $pdf->Cell (176, $summaryIntervalY, $sFamilySummary,0,0,"R"); $curY += 1.75 * $summaryIntervalY; $countFamily = 0; $currentFamilyAmount = 0; $page = $pdf->PageBreak($page); } // Check for new Fund if ($currentFundID != $fun_ID && $currentFundID) { // New Fund ID. Print Previous Fund Summary if ($countFund > 1) $item = gettext("items"); else $item = gettext("item"); $sFundSummary = "$currentFundName Total - $countFund $item: $" . number_format($currentFundAmount, 2, '.', ','); $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'B',10); $pdf->Cell (176, $summaryIntervalY, $sFundSummary,0,0,"R"); $curY += 2 * $summaryIntervalY; if ($detail_level != "summary") $pdf->line(40,$curY-2,195,$curY-2); $page = $pdf->PageBreak($page); // New Fund Title if ($detail_level != "summary") { $sFundTitle = "Fund: $fun_Name"; $pdf->SetFont("Times",'B',10); $pdf->WriteAt(20,$curY, $sFundTitle); $curY += 1.5 * $summaryIntervalY; } $countFund = 0; $currentFundAmount = 0; } // Print Deposit Detail if ($detail_level == "detail"){ // Format Data if ($plg_method == "CREDITCARD") $plg_method = "CREDIT"; if ($plg_method == "BANKDRAFT") $plg_method = "DRAFT"; if ($plg_method != "CHECK") $plg_CheckNo = $plg_method; if (strlen($plg_CheckNo) > 8) $plg_CheckNo = "...".substr($plg_CheckNo,-8,8); $sDeposit = "Dep #$plg_depID $dep_Date"; if (strlen($sDeposit) > 22) $sDeposit = substr($sDeposit,0,21) . "..."; if (strlen($plg_comment) > 29) $plg_comment = substr($plg_comment,0,28) . "..."; $fam_Name = $fam_Name . " - " . $fam_Address1; if (strlen($fam_Name) > 31) $fam_Name = substr($fam_Name,0,30) . "..."; // Print Data $pdf->SetFont('Times','', 10); $pdf->SetXY($pdf->leftX,$curY); $pdf->Cell (16, $summaryIntervalY, $plg_CheckNo,0,0,"R"); $pdf->Cell (40, $summaryIntervalY, $sDeposit); $pdf->Cell (55, $summaryIntervalY, $fam_Name); $pdf->Cell (40, $summaryIntervalY, $plg_comment); $pdf->SetFont('Courier','', 9); $pdf->Cell (25, $summaryIntervalY, $plg_amount,0,0,"R"); $pdf->SetFont('Times','', 10); $curY += $summaryIntervalY; $page = $pdf->PageBreak($page); } // Update running totals $totalAmount += $plg_amount; if (array_key_exists ($fun_Name, $totalFund)) $totalFund[$fun_Name] += $plg_amount; else $totalFund[$fun_Name] = $plg_amount; $countFund ++; $countFamily ++; $countReport ++; $currentFundAmount += $plg_amount; $currentFamilyAmount += $plg_amount; $currentReportAmount += $plg_amount; $currentFamilyID = $fam_ID; $currentFamilyName = $fam_Name; $currentFundID = $fun_ID; $currentFundName = $fun_Name; $currentFamilyAddress = $fam_Address1; } // Print Final Summary // Print Family Summary if ($detail_level != "summary") { if ($countFamily > 1) $item = gettext("items"); else $item = gettext("item"); $sFamilySummary = "$currentFamilyName - $currentFamilyAddress - $countFamily $item: $" . number_format($currentFamilyAmount, 2, '.', ','); $curY +=2; $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'I',10); $pdf->Cell (176, $summaryIntervalY, $sFamilySummary,0,0,"R"); $curY += 1.75 * $summaryIntervalY; $page = $pdf->PageBreak($page); } // Print Fund Summary if ($countFund > 1) $item = gettext("items"); else $item = gettext("item"); $sFundSummary = "$currentFundName Total - $countFund $item: $" . number_format($currentFundAmount, 2, '.', ','); $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'B',10); $pdf->Cell (176, $summaryIntervalY, $sFundSummary,0,0,"R"); $curY += 2 * $summaryIntervalY; if ($detail_level != "summary") $pdf->line(40,$curY-2,195,$curY-2); $page = $pdf->PageBreak($page); } elseif ($sort == "family") { // ********************** // Sort by Family Report // ********************** while ($aRow = mysql_fetch_array($rsReport)) { extract ($aRow); if (!$fun_ID){ $fun_ID = -1; $fun_Name = "Undesignated"; } if (!$fam_ID) { $fam_ID = -1; $fam_Name = "Unassigned"; $fam_Address1 = ""; } // First Family Heading if (!$currentFamilyID && $detail_level != "summary"){ $sFamilyTitle = "$fam_Name - $fam_Address1"; $pdf->SetFont("Times",'B',10); $pdf->WriteAt(20,$curY, $sFamilyTitle); $curY += 1.5 * $summaryIntervalY; } // Check for new Fund if (($currentFundID != $fun_ID || $currentFamilyID != $fam_ID) && $currentFundID && $detail_level != "summary") { // New Fund. Print Previous Fund Summary if ($countFund > 1) $item = gettext("items"); else $item = gettext("item"); $sFundSummary = "$currentFundName - $countFund $item: $" . number_format($currentFundAmount, 2, '.', ','); $curY +=2; $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'I',10); $pdf->Cell (176, $summaryIntervalY, $sFundSummary,0,0,"R"); $curY += 1.75 * $summaryIntervalY; $countFund = 0; $currentFundAmount = 0; $page = $pdf->PageBreak($page); } // Check for new Family if ($currentFamilyID != $fam_ID && $currentFamilyID) { // New Family. Print Previous Family Summary if ($countFamily > 1) $item = gettext("items"); else $item = gettext("item"); $sFamilySummary = "$currentFamilyName - $currentFamilyAddress - $countFamily $item: $" . number_format($currentFamilyAmount, 2, '.', ','); $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'B',10); $pdf->Cell (176, $summaryIntervalY, $sFamilySummary,0,0,"R"); $curY += 2 * $summaryIntervalY; if ($detail_level != "summary") $pdf->line(40,$curY-2,195,$curY-2); $page = $pdf->PageBreak($page); // New Family Title if ($detail_level != "summary") { $sFamilyTitle = "$fam_Name - $fam_Address1"; $pdf->SetFont("Times",'B',10); $pdf->WriteAt(20,$curY, $sFamilyTitle); $curY += 1.5 * $summaryIntervalY; } $countFamily = 0; $currentFamilyAmount = 0; } // Print Deposit Detail if ($detail_level == "detail"){ // Format Data if ($plg_method == "CREDITCARD") $plg_method = "CREDIT"; if ($plg_method == "BANKDRAFT") $plg_method = "DRAFT"; if ($plg_method != "CHECK") $plg_CheckNo = $plg_method; if (strlen($plg_CheckNo) > 8) $plg_CheckNo = "...".substr($plg_CheckNo,-8,8); $sDeposit = "Dep #$plg_depID $dep_Date"; if (strlen($sDeposit) > 22) $sDeposit = substr($sDeposit,0,21) . "..."; if (strlen($plg_comment) > 29) $plg_comment = substr($plg_comment,0,28) . "..."; $sFundName = $fun_Name; if (strlen($sFundName) > 31) $sFundName = substr($sFundName,0,30) . "..."; // Print Data $pdf->SetFont('Times','', 10); $pdf->SetXY($pdf->leftX,$curY); $pdf->Cell (16, $summaryIntervalY, $plg_CheckNo,0,0,"R"); $pdf->Cell (40, $summaryIntervalY, $sDeposit); $pdf->Cell (55, $summaryIntervalY, $sFundName); $pdf->Cell (40, $summaryIntervalY, $plg_comment); $pdf->SetFont('Courier','', 9); $pdf->Cell (25, $summaryIntervalY, $plg_amount,0,0,"R"); $pdf->SetFont('Times','', 10); $curY += $summaryIntervalY; $page = $pdf->PageBreak($page); } // Update running totals $totalAmount += $plg_amount; if (array_key_exists ($fun_Name, $totalFund)) $totalFund[$fun_Name] += $plg_amount; else $totalFund[$fun_Name] = $plg_amount; $countFund ++; $countFamily ++; $countReport ++; $currentFundAmount += $plg_amount; $currentFamilyAmount += $plg_amount; $currentReportAmount += $plg_amount; $currentFamilyID = $fam_ID; $currentFamilyName = $fam_Name; $currentFundID = $fun_ID; $currentFundName = $fun_Name; $currentFamilyAddress = $fam_Address1; } // Print Final Summary // Print Fund Summary if ($detail_level != "summary") { if ($countFund > 1) $item = gettext("items"); else $item = gettext("item"); $sFundSummary = "$currentFundName - $countFund $item: $" . number_format($currentFundAmount, 2, '.', ','); $curY +=2; $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'I',10); $pdf->Cell (176, $summaryIntervalY, $sFundSummary,0,0,"R"); $curY += 1.75 * $summaryIntervalY; $page = $pdf->PageBreak($page); } // Print Family Summary if ($countFamily > 1) $item = gettext("items"); else $item = gettext("item"); $sFamilySummary = "$currentFamilyName - $currentFamilyAddress - $countFamily $item: $" . number_format($currentFamilyAmount, 2, '.', ','); $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'B',10); $pdf->Cell (176, $summaryIntervalY, $sFamilySummary,0,0,"R"); $curY += 2 * $summaryIntervalY; if ($detail_level != "summary") $pdf->line(40,$curY-2,195,$curY-2); $page = $pdf->PageBreak($page); } // Print Report Summary if ($countReport > 1) $item = gettext("items"); else $item = gettext("item"); $sReportSummary = "Report Total ($countReport $item): $" . number_format($currentReportAmount, 2, '.', ','); $pdf->SetXY(20,$curY); $pdf->SetFont("Times",'B',10); $pdf->Cell (176, $summaryIntervalY, $sReportSummary,0,0,"R"); $pdf->line(40,$curY-2,195,$curY-2); $curY += 2.5 * $summaryIntervalY; $page = $pdf->PageBreak($page); // Print Fund Totals $pdf->SetFont('Times','B', 10); $pdf->SetXY ($curX, $curY); $pdf->WriteAt (20, $curY, 'Deposit totals by fund'); $pdf->SetFont('Courier','', 10); $curY += 1.5 * $summaryIntervalY; ksort ($totalFund); reset ($totalFund); while ($FundTotal = current($totalFund)){ if (strlen(key($totalFund) > 22)) $sfun_Name = substr(key($totalFund),0,21) . "..."; else $sfun_Name = key($totalFund); $pdf->SetXY(20,$curY); $pdf->Cell(45,$summaryIntervalY, $sfun_Name); $pdf->Cell (25, $summaryIntervalY, number_format($FundTotal, 2, '.', ','),0,0,"R"); $curY += $summaryIntervalY; $page = $pdf->PageBreak($page); next($totalFund); } $pdf->FinishPage($page); $pdf->Output("DepositReport-" . date("Ymd-Gis") . ".pdf", "D"); // Output a text file // ################## } elseif ($output == "csv") { // Settings $delimiter = ","; $eol = "\r\n"; // Build headings row eregi ("SELECT (.*) FROM ", $sSQL, $result); $headings = explode(",",$result[1]); $buffer = ""; foreach ($headings as $heading) { $buffer .= trim($heading) . $delimiter; } // Remove trailing delimiter and add eol $buffer = substr($buffer,0,-1) . $eol; // Add data while ($row = mysql_fetch_row($rsReport)) { foreach ($row as $field) { $field = str_replace($delimiter, " ", $field); // Remove any delimiters from data $buffer .= $field . $delimiter; } // Remove trailing delimiter and add eol $buffer = substr($buffer,0,-1) . $eol; } // Export file header("Content-type: text/x-csv"); header("Content-Disposition: attachment; filename='ChurchInfo" . date("Ymd-Gis") . ".csv"); echo $buffer; } ?>
ecc12/churchinfo
htdocs/Reports/AdvancedDeposit.php
PHP
gpl-3.0
26,737
#include <iostream> using namespace std; class lectures { protected: int rollno, marks1, marks2; public: void get() { rollno = 007; marks1 = 75; marks2 = 50; } }; class sports { protected: int sportsmarks; public: void getsportsmarks() { sportsmarks = 100; } }; class result : public lectures, public sports // Result class inherited from lectures and sports { private: int total, average; public: void display() { total = (marks1+marks2+sportsmarks); average = total/3.0; cout << "\nRoll No : " << rollno; cout << "\nTotal: " << total; cout << "\nAverage : " << average; } }; int main() { result obj; obj.get(); obj.getsportsmarks(); obj.display(); return 0; } /* OUTPUT Roll No: 007 Total: 225 Average: 75 */
algobook/Algo_Ds_Notes
Inheritance(C++)/Multiple.cpp
C++
gpl-3.0
964
YUI.add('moodle-mod_quiz-dragdrop', function (Y, NAME) { /** * Drag and Drop for Quiz sections and slots. * * @module moodle-mod-quiz-dragdrop */ var CSS = { ACTIONAREA: '.actions', ACTIVITY: 'activity', ACTIVITYINSTANCE: 'activityinstance', CONTENT: 'content', COURSECONTENT: 'mod-quiz-edit-content', EDITINGMOVE: 'editing_move', ICONCLASS: 'iconsmall', JUMPMENU: 'jumpmenu', LEFT: 'left', LIGHTBOX: 'lightbox', MOVEDOWN: 'movedown', MOVEUP: 'moveup', PAGE : 'page', PAGECONTENT: 'page-content', RIGHT: 'right', SECTION: 'section', SECTIONADDMENUS: 'section_add_menus', SECTIONHANDLE: 'section-handle', SLOTS: 'slots', SUMMARY: 'summary', SECTIONDRAGGABLE: 'sectiondraggable' }, // The CSS selectors we use. SELECTOR = { PAGE: 'li.page', SLOT: 'li.slot' }; /** * Section drag and drop. * * @class M.mod_quiz.dragdrop.section * @constructor * @extends M.core.dragdrop */ var DRAGSECTION = function() { DRAGSECTION.superclass.constructor.apply(this, arguments); }; Y.extend(DRAGSECTION, M.core.dragdrop, { sectionlistselector: null, initializer: function() { // Set group for parent class this.groups = [ CSS.SECTIONDRAGGABLE ]; this.samenodeclass = M.mod_quiz.edit.get_sectionwrapperclass(); this.parentnodeclass = M.mod_quiz.edit.get_containerclass(); // Check if we are in single section mode if (Y.Node.one('.' + CSS.JUMPMENU)) { return false; } // Initialise sections dragging this.sectionlistselector = M.mod_quiz.edit.get_section_wrapper(Y); if (this.sectionlistselector) { this.sectionlistselector = '.' + CSS.COURSECONTENT + ' ' + this.sectionlistselector; this.setup_for_section(this.sectionlistselector); // Make each li element in the lists of sections draggable var del = new Y.DD.Delegate({ container: '.' + CSS.COURSECONTENT, nodes: '.' + CSS.SECTIONDRAGGABLE, target: true, handles: ['.' + CSS.LEFT], dragConfig: {groups: this.groups} }); del.dd.plug(Y.Plugin.DDProxy, { // Don't move the node at the end of the drag moveOnEnd: false }); del.dd.plug(Y.Plugin.DDConstrained, { // Keep it inside the .mod-quiz-edit-content constrain: '#' + CSS.PAGECONTENT, stickY: true }); del.dd.plug(Y.Plugin.DDWinScroll); } }, /** * Apply dragdrop features to the specified selector or node that refers to section(s) * * @method setup_for_section * @param {String} baseselector The CSS selector or node to limit scope to */ setup_for_section: function(baseselector) { Y.Node.all(baseselector).each(function(sectionnode) { // Determine the section ID var sectionid = Y.Moodle.core_course.util.section.getId(sectionnode); // We skip the top section as it is not draggable if (sectionid > 0) { // Remove move icons var movedown = sectionnode.one('.' + CSS.RIGHT + ' a.' + CSS.MOVEDOWN); var moveup = sectionnode.one('.' + CSS.RIGHT + ' a.' + CSS.MOVEUP); // Add dragger icon var title = M.util.get_string('movesection', 'moodle', sectionid); var cssleft = sectionnode.one('.' + CSS.LEFT); if ((movedown || moveup) && cssleft) { cssleft.setStyle('cursor', 'move'); cssleft.appendChild(this.get_drag_handle(title, CSS.SECTIONHANDLE, 'icon', true)); if (moveup) { moveup.remove(); } if (movedown) { movedown.remove(); } // This section can be moved - add the class to indicate this to Y.DD. sectionnode.addClass(CSS.SECTIONDRAGGABLE); } } }, this); }, /* * Drag-dropping related functions */ drag_start: function(e) { // Get our drag object var drag = e.target; // Creat a dummy structure of the outer elemnents for clean styles application var containernode = Y.Node.create('<' + M.mod_quiz.edit.get_containernode() + '></' + M.mod_quiz.edit.get_containernode() + '>'); containernode.addClass(M.mod_quiz.edit.get_containerclass()); var sectionnode = Y.Node.create('<' + M.mod_quiz.edit.get_sectionwrappernode() + '></' + M.mod_quiz.edit.get_sectionwrappernode() + '>'); sectionnode.addClass( M.mod_quiz.edit.get_sectionwrapperclass()); sectionnode.setStyle('margin', 0); sectionnode.setContent(drag.get('node').get('innerHTML')); containernode.appendChild(sectionnode); drag.get('dragNode').setContent(containernode); drag.get('dragNode').addClass(CSS.COURSECONTENT); }, drag_dropmiss: function(e) { // Missed the target, but we assume the user intended to drop it // on the last last ghost node location, e.drag and e.drop should be // prepared by global_drag_dropmiss parent so simulate drop_hit(e). this.drop_hit(e); }, get_section_index: function(node) { var sectionlistselector = '.' + CSS.COURSECONTENT + ' ' + M.mod_quiz.edit.get_section_selector(Y), sectionList = Y.all(sectionlistselector), nodeIndex = sectionList.indexOf(node), zeroIndex = sectionList.indexOf(Y.one('#section-0')); return (nodeIndex - zeroIndex); }, drop_hit: function(e) { var drag = e.drag; // Get references to our nodes and their IDs. var dragnode = drag.get('node'), dragnodeid = Y.Moodle.core_course.util.section.getId(dragnode), loopstart = dragnodeid, dropnodeindex = this.get_section_index(dragnode), loopend = dropnodeindex; if (dragnodeid === dropnodeindex) { return; } if (loopstart > loopend) { // If we're going up, we need to swap the loop order // because loops can't go backwards. loopstart = dropnodeindex; loopend = dragnodeid; } // Get the list of nodes. drag.get('dragNode').removeClass(CSS.COURSECONTENT); var sectionlist = Y.Node.all(this.sectionlistselector); // Add a lightbox if it's not there. var lightbox = M.util.add_lightbox(Y, dragnode); // Handle any variables which we must pass via AJAX. var params = {}, pageparams = this.get('config').pageparams, varname; for (varname in pageparams) { if (!pageparams.hasOwnProperty(varname)) { continue; } params[varname] = pageparams[varname]; } // Prepare request parameters params.sesskey = M.cfg.sesskey; params.courseid = this.get('courseid'); params.quizid = this.get('quizid'); params['class'] = 'section'; params.field = 'move'; params.id = dragnodeid; params.value = dropnodeindex; // Perform the AJAX request. var uri = M.cfg.wwwroot + this.get('ajaxurl'); Y.io(uri, { method: 'POST', data: params, on: { start: function() { lightbox.show(); }, success: function(tid, response) { // Update section titles, we can't simply swap them as // they might have custom title try { var responsetext = Y.JSON.parse(response.responseText); if (responsetext.error) { new M.core.ajaxException(responsetext); } M.mod_quiz.edit.process_sections(Y, sectionlist, responsetext, loopstart, loopend); } catch (e) {} // Update all of the section IDs - first unset them, then set them // to avoid duplicates in the DOM. var index; // Classic bubble sort algorithm is applied to the section // nodes between original drag node location and the new one. var swapped = false; do { swapped = false; for (index = loopstart; index <= loopend; index++) { if (Y.Moodle.core_course.util.section.getId(sectionlist.item(index - 1)) > Y.Moodle.core_course.util.section.getId(sectionlist.item(index))) { // Swap section id. var sectionid = sectionlist.item(index - 1).get('id'); sectionlist.item(index - 1).set('id', sectionlist.item(index).get('id')); sectionlist.item(index).set('id', sectionid); // See what format needs to swap. M.mod_quiz.edit.swap_sections(Y, index - 1, index); // Update flag. swapped = true; } } loopend = loopend - 1; } while (swapped); window.setTimeout(function() { lightbox.hide(); }, 250); }, failure: function(tid, response) { this.ajax_failure(response); lightbox.hide(); } }, context:this }); } }, { NAME: 'mod_quiz-dragdrop-section', ATTRS: { courseid: { value: null }, quizid: { value: null }, ajaxurl: { value: 0 }, config: { value: 0 } } }); M.mod_quiz = M.mod_quiz || {}; M.mod_quiz.init_section_dragdrop = function(params) { new DRAGSECTION(params); }; /** * Resource drag and drop. * * @class M.course.dragdrop.resource * @constructor * @extends M.core.dragdrop */ var DRAGRESOURCE = function() { DRAGRESOURCE.superclass.constructor.apply(this, arguments); }; Y.extend(DRAGRESOURCE, M.core.dragdrop, { initializer: function() { // Set group for parent class this.groups = ['resource']; this.samenodeclass = CSS.ACTIVITY; this.parentnodeclass = CSS.SECTION; //this.resourcedraghandle = this.get_drag_handle(M.util.get_string('movecoursemodule', 'moodle'), CSS.EDITINGMOVE, CSS.ICONCLASS, true); this.resourcedraghandle = this.get_drag_handle(M.str.moodle.move, CSS.EDITINGMOVE, CSS.ICONCLASS, true); this.samenodelabel = { identifier: 'dragtoafter', component: 'quiz' }; this.parentnodelabel = { identifier: 'dragtostart', component: 'quiz' }; // Go through all sections var sectionlistselector = M.mod_quiz.edit.get_section_selector(Y); if (sectionlistselector) { sectionlistselector = '.' + CSS.COURSECONTENT + ' ' + sectionlistselector; this.setup_for_section(sectionlistselector); // Initialise drag & drop for all resources/activities var nodeselector = sectionlistselector.slice(CSS.COURSECONTENT.length + 2) + ' li.' + CSS.ACTIVITY; var del = new Y.DD.Delegate({ container: '.' + CSS.COURSECONTENT, nodes: nodeselector, target: true, handles: ['.' + CSS.EDITINGMOVE], dragConfig: {groups: this.groups} }); del.dd.plug(Y.Plugin.DDProxy, { // Don't move the node at the end of the drag moveOnEnd: false, cloneNode: true }); del.dd.plug(Y.Plugin.DDConstrained, { // Keep it inside the .mod-quiz-edit-content constrain: '#' + CSS.SLOTS }); del.dd.plug(Y.Plugin.DDWinScroll); M.mod_quiz.quizbase.register_module(this); M.mod_quiz.dragres = this; } }, /** * Apply dragdrop features to the specified selector or node that refers to section(s) * * @method setup_for_section * @param {String} baseselector The CSS selector or node to limit scope to */ setup_for_section: function(baseselector) { Y.Node.all(baseselector).each(function(sectionnode) { var resources = sectionnode.one('.' + CSS.CONTENT + ' ul.' + CSS.SECTION); // See if resources ul exists, if not create one. if (!resources) { resources = Y.Node.create('<ul></ul>'); resources.addClass(CSS.SECTION); sectionnode.one('.' + CSS.CONTENT + ' div.' + CSS.SUMMARY).insert(resources, 'after'); } resources.setAttribute('data-draggroups', this.groups.join(' ')); // Define empty ul as droptarget, so that item could be moved to empty list new Y.DD.Drop({ node: resources, groups: this.groups, padding: '20 0 20 0' }); // Initialise each resource/activity in this section this.setup_for_resource('#' + sectionnode.get('id') + ' li.' + CSS.ACTIVITY); }, this); }, /** * Apply dragdrop features to the specified selector or node that refers to resource(s) * * @method setup_for_resource * @param {String} baseselector The CSS selector or node to limit scope to */ setup_for_resource: function(baseselector) { Y.Node.all(baseselector).each(function(resourcesnode) { // Replace move icons var move = resourcesnode.one('a.' + CSS.EDITINGMOVE); if (move) { move.replace(this.resourcedraghandle.cloneNode(true)); } }, this); }, drag_start: function(e) { // Get our drag object var drag = e.target; drag.get('dragNode').setContent(drag.get('node').get('innerHTML')); drag.get('dragNode').all('img.iconsmall').setStyle('vertical-align', 'baseline'); }, drag_dropmiss: function(e) { // Missed the target, but we assume the user intended to drop it // on the last ghost node location, e.drag and e.drop should be // prepared by global_drag_dropmiss parent so simulate drop_hit(e). this.drop_hit(e); }, drop_hit: function(e) { var drag = e.drag; // Get a reference to our drag node var dragnode = drag.get('node'); var dropnode = e.drop.get('node'); // Add spinner if it not there var actionarea = dragnode.one(CSS.ACTIONAREA); var spinner = M.util.add_spinner(Y, actionarea); var params = {}; // Handle any variables which we must pass back through to var pageparams = this.get('config').pageparams; var varname; for (varname in pageparams) { params[varname] = pageparams[varname]; } // Prepare request parameters params.sesskey = M.cfg.sesskey; params.courseid = this.get('courseid'); params.quizid = this.get('quizid'); params['class'] = 'resource'; params.field = 'move'; params.id = Number(Y.Moodle.mod_quiz.util.slot.getId(dragnode)); params.sectionId = Y.Moodle.core_course.util.section.getId(dropnode.ancestor(M.mod_quiz.edit.get_section_wrapper(Y), true)); var previousslot = dragnode.previous(SELECTOR.SLOT); if (previousslot) { params.previousid = Number(Y.Moodle.mod_quiz.util.slot.getId(previousslot)); } var previouspage = dragnode.previous(SELECTOR.PAGE); if (previouspage) { params.page = Number(Y.Moodle.mod_quiz.util.page.getId(previouspage)); } // Do AJAX request var uri = M.cfg.wwwroot + this.get('ajaxurl'); Y.io(uri, { method: 'POST', data: params, on: { start: function() { this.lock_drag_handle(drag, CSS.EDITINGMOVE); spinner.show(); }, success: function(tid, response) { var responsetext = Y.JSON.parse(response.responseText); var params = {element: dragnode, visible: responsetext.visible}; M.mod_quiz.quizbase.invoke_function('set_visibility_resource_ui', params); Y.Moodle.mod_quiz.util.slot.reorder_slots(); this.unlock_drag_handle(drag, CSS.EDITINGMOVE); window.setTimeout(function() { spinner.hide(); }, 250); window.location.reload(true); }, failure: function(tid, response) { this.ajax_failure(response); this.unlock_drag_handle(drag, CSS.SECTIONHANDLE); spinner.hide(); window.location.reload(true); } }, context:this }); }, global_drop_over: function(e) { //Overriding parent method so we can stop the slots being dragged before the first page node. // Check that drop object belong to correct group. if (!e.drop || !e.drop.inGroup(this.groups)) { return; } // Get a reference to our drag and drop nodes. var drag = e.drag.get('node'), drop = e.drop.get('node'); // Save last drop target for the case of missed target processing. this.lastdroptarget = e.drop; // Are we dropping within the same parent node? if (drop.hasClass(this.samenodeclass)) { var where; if (this.goingup) { where = "before"; } else { where = "after"; } drop.insert(drag, where); } else if ((drop.hasClass(this.parentnodeclass) || drop.test('[data-droptarget="1"]')) && !drop.contains(drag)) { // We are dropping on parent node and it is empty if (this.goingup) { drop.append(drag); } else { drop.prepend(drag); } } this.drop_over(e); } }, { NAME: 'mod_quiz-dragdrop-resource', ATTRS: { courseid: { value: null }, quizid: { value: null }, ajaxurl: { value: 0 }, config: { value: 0 } } }); M.mod_quiz = M.mod_quiz || {}; M.mod_quiz.init_resource_dragdrop = function(params) { new DRAGRESOURCE(params); }; }, '@VERSION@', { "requires": [ "base", "node", "io", "dom", "dd", "dd-scroll", "moodle-core-dragdrop", "moodle-core-notification", "moodle-mod_quiz-quizbase", "moodle-mod_quiz-util", "moodle-course-util" ] });
Microsoft/moodle
mod/quiz/yui/build/moodle-mod_quiz-dragdrop/moodle-mod_quiz-dragdrop.js
JavaScript
gpl-3.0
19,635
/* * AxtelKeygen.cpp * * Created on: 5 de Ago de 2012 * Author: ruka */ #include "AxtelKeygen.h" AxtelKeygen::AxtelKeygen(QString ssid, QString mac) : Keygen(ssid, mac) { } QVector<QString> & AxtelKeygen::getKeys() { QString mac = getMacAddress(); if ( mac.length() != 12 ) throw ERROR; results.append(mac.mid(2).toUpper()); return results; }
RobertoEstrada/libKeygen
src/algorithms/AxtelKeygen.cpp
C++
gpl-3.0
382
/* * Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package com.bc.ceres.glayer.swing; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.MouseInputAdapter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.geom.*; /** * A navigation control which appears as a screen overlay. * It can fire rotation, translation and scale events. * * @author Norman Fomferra * @version $Revision$ $Date$ */ public class NavControl extends JComponent { private static final Dimension PREFERRED_SIZE = new Dimension(100, 120); private static final int TIMER_DELAY = 50; private final NavControlModel model; private double pannerHandleOffsetX; private double pannerHandleOffsetY; private double scaleHandleOffsetX; private double scaleHandleOffsetY; private Ellipse2D outerRotationCircle; private Ellipse2D innerRotationCircle; private Ellipse2D outerMoveCircle; private Shape pannerHandle; private Shape[] moveArrowShapes; private Area[] rotationUnitShapes; private RectangularShape scaleHandle; private RectangularShape scaleBar; public NavControl(NavControlModel model) { this.model = model; final MouseHandler mouseHandler = new MouseHandler(); addMouseListener(mouseHandler); addMouseMotionListener(mouseHandler); setBounds(0, 0, PREFERRED_SIZE.width, PREFERRED_SIZE.height); } @Override public Dimension getPreferredSize() { if (isPreferredSizeSet()) { return super.getPreferredSize(); } return PREFERRED_SIZE; } @Override public void setBounds(int x, int y, int width, int height) { super.setBounds(x, y, width, height); updateGeom(); } @Override protected void paintComponent(Graphics g) { final Graphics2D graphics2D = (Graphics2D) g; final AffineTransform oldTransform = graphics2D.getTransform(); graphics2D.setStroke(new BasicStroke(0.6f)); graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.rotate(-Math.PI * 0.5 - Math.toRadians(model.getCurrentAngle()), outerRotationCircle.getCenterX(), outerRotationCircle.getCenterY()); for (int i = 0; i < rotationUnitShapes.length; i++) { graphics2D.setColor(i == 0 ? Color.ORANGE : Color.WHITE); graphics2D.fill(rotationUnitShapes[i]); graphics2D.setColor(Color.BLACK); graphics2D.draw(rotationUnitShapes[i]); } graphics2D.setTransform(oldTransform); for (Shape arrow : moveArrowShapes) { graphics2D.setColor(Color.WHITE); graphics2D.fill(arrow); graphics2D.setColor(Color.BLACK); graphics2D.draw(arrow); } graphics2D.translate(pannerHandleOffsetX, pannerHandleOffsetY); graphics2D.setColor(Color.WHITE); graphics2D.fill(pannerHandle); graphics2D.setColor(Color.BLACK); graphics2D.draw(pannerHandle); graphics2D.setTransform(oldTransform); graphics2D.setColor(Color.WHITE); graphics2D.fill(scaleBar); graphics2D.setColor(Color.BLACK); graphics2D.draw(scaleBar); graphics2D.translate(scaleHandleOffsetX, scaleHandleOffsetY); graphics2D.setColor(Color.WHITE); graphics2D.fill(scaleHandle); graphics2D.setColor(Color.BLACK); graphics2D.draw(scaleHandle); graphics2D.setTransform(oldTransform); } /** * Gives the UI delegate an opportunity to define the precise * shape of this component for the sake of mouse processing. * * @return true if this component logically contains x,y * @see java.awt.Component#contains(int, int) * @see javax.swing.plaf.ComponentUI */ @Override public boolean contains(int x, int y) { return getAction(x, y) != ACTION_NONE; } private void updateGeom() { final double scaleHandleW = Math.max(4, 0.025 * getWidth()); final double scaleHandleH = 4 * scaleHandleW; final double gap = Math.max(4, 0.05 * getHeight()); final Insets insets = getInsets(); double x = insets.left; double y = insets.top; double w = getWidth() - (insets.left + insets.right) - 2; double h = getHeight() - (insets.top + insets.bottom + gap + scaleHandleH) - 2; final double outerRotationDiameter; if (w > h) { x += (w - h) / 2; outerRotationDiameter = h; } else { y += (h - w) / 2; outerRotationDiameter = w; } final double innerRotationDiameter = 0.8 * outerRotationDiameter; final double outerMoveDiameter = 0.4 * outerRotationDiameter; outerRotationCircle = new Ellipse2D.Double(x, y, outerRotationDiameter, outerRotationDiameter); innerRotationCircle = new Ellipse2D.Double(outerRotationCircle.getCenterX() - 0.5 * innerRotationDiameter, outerRotationCircle.getCenterY() - 0.5 * innerRotationDiameter, innerRotationDiameter, innerRotationDiameter); outerMoveCircle = new Ellipse2D.Double(innerRotationCircle.getCenterX() - 0.5 * outerMoveDiameter, innerRotationCircle.getCenterY() - 0.5 * outerMoveDiameter, outerMoveDiameter, outerMoveDiameter); rotationUnitShapes = createRotationUnitShapes(); moveArrowShapes = createMoveArrows(); pannerHandle = createPanner(); ///////////////////////////////////////////////////////// final double scaleBarW = outerRotationDiameter; final double scaleBarH = scaleHandleW; final double scaleBarX = x; final double scaleHandleY = y + outerRotationDiameter + gap; scaleBar = new Rectangle2D.Double(scaleBarX, scaleHandleY + 0.5 * (scaleHandleH - scaleBarH), scaleBarW, scaleBarH); scaleHandle = new Rectangle2D.Double(scaleBarX + 0.5 * (scaleBarW - scaleHandleW), scaleHandleY, scaleHandleW, scaleHandleH); } private Shape createPanner() { final double innerRadius = 0.5 * innerRotationCircle.getWidth(); final double s = 0.25 * innerRadius; final Rectangle2D r1 = new Rectangle2D.Double(-0.5 * s, -0.5 * s, s, s); final Shape r2 = AffineTransform.getRotateInstance(0.25 * Math.PI).createTransformedShape(r1); Area area = new Area(r1); area.add(new Area(r2)); return AffineTransform.getTranslateInstance(innerRotationCircle.getCenterX(), innerRotationCircle.getCenterY()).createTransformedShape(area); } private Shape[] createMoveArrows() { final double innerRadius = 0.5 * innerRotationCircle.getWidth(); final GeneralPath path = new GeneralPath(); path.moveTo(0, 0); path.lineTo(2, 1); path.lineTo(1, 1); path.lineTo(1, 2); path.lineTo(-1, 2); path.lineTo(-1, 1); path.lineTo(-2, 1); path.closePath(); Shape[] arrows = new Shape[4]; for (int i = 0; i < 4; i++) { final AffineTransform at = new AffineTransform(); at.rotate(i * 0.5 * Math.PI, innerRotationCircle.getCenterX(), innerRotationCircle.getCenterY()); at.translate(innerRotationCircle.getCenterX(), innerRotationCircle.getCenterY() - 0.95 * innerRadius); at.scale(0.2 * innerRadius, 0.3 * innerRadius); final Area area = new Area(at.createTransformedShape(path)); area.subtract(new Area(outerMoveCircle)); arrows[i] = area; } return arrows; } private Area[] createRotationUnitShapes() { final Area[] areas = new Area[36]; final Area rhs = new Area(innerRotationCircle); for (int i = 0; i < 36; i++) { final Arc2D.Double arc = new Arc2D.Double(outerRotationCircle.getX(), outerRotationCircle.getY(), outerRotationCircle.getWidth(), outerRotationCircle.getHeight(), i * 10 - 0.5 * 7, 7, Arc2D.PIE); final Area area = new Area(arc); area.subtract(rhs); areas[i] = area; } return areas; } private double getAngle(Point point) { final double a = Math.atan2(-(point.y - innerRotationCircle.getCenterY()), point.x - innerRotationCircle.getCenterX()); return normaliseAngle(a - 0.5 * Math.PI); } private static double normaliseAngle(double a) { while (a < 0.0) { a += 2.0 * Math.PI; } a %= 2.0 * Math.PI; if (a > Math.PI) { a += -2.0 * Math.PI; } return a; } int getAction(int x, int y) { if (super.contains(x, y)) { if (outerRotationCircle.contains(x, y) && !innerRotationCircle.contains(x, y)) { return ACTION_ROT; } else if (pannerHandle.contains(x, y)) { return ACTION_PAN; } else if (scaleHandle.contains(x, y) || scaleBar.contains(x, y)) { return ACTION_SCALE; } else { for (int i = 0; i < moveArrowShapes.length; i++) { Shape moveArrowShape = moveArrowShapes[i]; if (moveArrowShape.contains(x, y)) { return ACTION_MOVE_DIRS[i]; } } } } return ACTION_NONE; } public static interface NavControlModel { double getCurrentAngle(); void handleRotate(double rotationAngle); void handleMove(double moveDirX, double moveDirY); void handleScale(double scaleDir); } private final static int ACTION_NONE = 0; private final static int ACTION_ROT = 1; private final static int ACTION_SCALE = 2; private final static int ACTION_PAN = 3; private final static int ACTION_MOVE_N = 4; private final static int ACTION_MOVE_S = 5; private final static int ACTION_MOVE_W = 6; private final static int ACTION_MOVE_E = 7; private final static int[] ACTION_MOVE_DIRS = {ACTION_MOVE_N, ACTION_MOVE_S, ACTION_MOVE_W, ACTION_MOVE_E}; private static final double[] X_DIRS = new double[]{0, -1, 0, 1}; private static final double[] Y_DIRS = new double[]{1, 0, -1, 0}; private class MouseHandler extends MouseInputAdapter implements ActionListener { private Point point0; private double rotationAngle0; private double moveDirX; private double moveDirY; private double moveAcc; private double scaleDir; private double scaleAcc; private Cursor cursor0; private final Timer actionTrigger; private int action; // see MODE_XXX values private MouseHandler() { actionTrigger = new Timer(TIMER_DELAY, this); action = ACTION_NONE; } public void actionPerformed(ActionEvent e) { if (action == ACTION_PAN || action == ACTION_MOVE_N || action == ACTION_MOVE_S || action == ACTION_MOVE_W || action == ACTION_MOVE_E) { fireAcceleratedMove(); } else if (action == ACTION_SCALE) { fireAcceleratedScale(); } } @Override public void mousePressed(MouseEvent e) { cursor0 = getCursor(); point0 = e.getPoint(); moveAcc = 1.0; scaleAcc = 1.0; action = getAction(e.getX(), e.getY()); if (action == ACTION_ROT) { rotationAngle0 = model.getCurrentAngle(); } else if (action == ACTION_SCALE) { doScale(e); } else if (action == ACTION_MOVE_N) { startMove(0); } else if (action == ACTION_MOVE_S) { startMove(1); } else if (action == ACTION_MOVE_W) { startMove(2); } else if (action == ACTION_MOVE_E) { startMove(3); } if (action != ACTION_NONE) { setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } } @Override public void mouseDragged(MouseEvent e) { if (action == ACTION_ROT) { doRotate(e); } else if (action == ACTION_PAN) { doPan(e); } else if (action == ACTION_SCALE) { doScale(e); } } @Override public void mouseReleased(MouseEvent e) { stopAction(); } private void doScale(MouseEvent e) { final Point point = e.getPoint(); double dx = point.x - scaleBar.getCenterX(); double a = 0.5 * (scaleBar.getWidth() - scaleHandle.getWidth()); if (dx < -a) { dx = -a; } if (dx > +a) { dx = +a; } scaleHandleOffsetX = dx; scaleHandleOffsetY = 0; scaleDir = dx / a; scaleAcc = 1.0; fireAcceleratedScale(); startTriggeringActions(); } private void startTriggeringActions() { actionTrigger.restart(); } private void stopTriggeringActions() { actionTrigger.stop(); } private void doPan(MouseEvent e) { final Point point = e.getPoint(); final double outerMoveRadius = 0.5 * outerMoveCircle.getWidth(); double dx = point.x - outerMoveCircle.getCenterX(); double dy = point.y - outerMoveCircle.getCenterY(); final double r = Math.sqrt(dx * dx + dy * dy); if (r > outerMoveRadius) { dx = outerMoveRadius * dx / r; dy = outerMoveRadius * dy / r; } pannerHandleOffsetX = dx; pannerHandleOffsetY = dy; moveDirX = -dx / outerMoveRadius; moveDirY = -dy / outerMoveRadius; moveAcc = 1.0; fireAcceleratedMove(); startTriggeringActions(); } void startMove(int dir) { moveDirX = X_DIRS[dir]; moveDirY = Y_DIRS[dir]; doMove(); } private void doMove() { moveAcc = 1.0; startTriggeringActions(); } private void doRotate(MouseEvent e) { double a1 = getAngle(point0); double a2 = getAngle(e.getPoint()); double a = Math.toDegrees(normaliseAngle(Math.toRadians(rotationAngle0) + (a2 - a1))); if (e.isControlDown()) { double t = 0.5 * 45.0; a = t * Math.floor(a / t); } model.handleRotate(a); repaint(); } private void fireAcceleratedScale() { model.handleScale(scaleAcc * scaleDir / 4.0); scaleAcc *= 1.1; if (scaleAcc > 4.0) { scaleAcc = 4.0; } } private void fireAcceleratedMove() { model.handleMove(moveAcc * moveDirX, moveAcc * moveDirY); moveAcc *= 1.05; if (moveAcc > 4.0) { moveAcc = 4.0; } } private void stopAction() { setCursor(cursor0); stopTriggeringActions(); cursor0 = null; point0 = null; action = ACTION_NONE; moveDirX = 0; moveDirY = 0; moveAcc = 1.0; pannerHandleOffsetX = 0; pannerHandleOffsetY = 0; scaleDir = 0; scaleAcc = 1.0; scaleHandleOffsetX = 0; scaleHandleOffsetY = 0; repaint(); } } public static void main(String[] args) { final JFrame frame = new JFrame("NavControl"); final JPanel panel = new JPanel(new BorderLayout(3, 3)); panel.setBackground(Color.GRAY); final JLabel label = new JLabel("Angle: "); final NavControl navControl = new NavControl(new NavControlModel() { double angle; @Override public double getCurrentAngle() { return angle; } public void handleRotate(double rotationAngle) { angle = rotationAngle; label.setText("Angle: " + rotationAngle); System.out.println("NavControl: rotationAngle = " + rotationAngle); } public void handleMove(double moveDirX, double moveDirY) { System.out.println("NavControl: moveDirX = " + moveDirX + ", moveDirY = " + moveDirY); } public void handleScale(double scaleDir) { System.out.println("NavControl: scaleDir = " + scaleDir); } }); navControl.setBorder(new EmptyBorder(4, 4, 4, 4)); panel.add(label, BorderLayout.SOUTH); panel.add(navControl, BorderLayout.CENTER); frame.add(panel); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
arraydev/snap-engine
ceres-glayer/src/main/java/com/bc/ceres/glayer/swing/NavControl.java
Java
gpl-3.0
19,053
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2016 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package builtin const timeserverControlSummary = `allows setting system time synchronization servers` const timeserverControlBaseDeclarationSlots = ` timeserver-control: allow-installation: slot-snap-type: - core deny-auto-connection: true ` // http://bazaar.launchpad.net/~ubuntu-security/ubuntu-core-security/trunk/view/head:/data/apparmor/policygroups/ubuntu-core/16.04/timeserver-control const timeserverControlConnectedPlugAppArmor = ` # Description: Can manage timeservers directly separate from config ubuntu-core. # Can enable system clock NTP synchronization via timedated D-Bus interface, # Can read all properties of /org/freedesktop/timedate1 D-Bus object; see # https://www.freedesktop.org/wiki/Software/systemd/timedated/ #include <abstractions/dbus-strict> # Won't work until LP: #1504657 is fixed. Requires reboot until timesyncd # notices the change or systemd restarts it. /etc/systemd/timesyncd.conf rw, # Introspection of org.freedesktop.timedate1 dbus (send) bus=system path=/org/freedesktop/timedate1 interface=org.freedesktop.DBus.Introspectable member=Introspect peer=(label=unconfined), dbus (send) bus=system path=/org/freedesktop/timedate1 interface=org.freedesktop.timedate1 member="SetNTP" peer=(label=unconfined), # Read all properties from timedate1 dbus (send) bus=system path=/org/freedesktop/timedate1 interface=org.freedesktop.DBus.Properties member=Get{,All} peer=(label=unconfined), # Receive timedate1 property changed events dbus (receive) bus=system path=/org/freedesktop/timedate1 interface=org.freedesktop.DBus.Properties member=PropertiesChanged peer=(label=unconfined), # As the core snap ships the timedatectl utility we can also allow # clients to use it now that they have access to the relevant # D-Bus method for controlling network time synchronization via # timedatectl's set-ntp command. /usr/bin/timedatectl{,.real} ixr, ` func init() { registerIface(&commonInterface{ name: "timeserver-control", summary: timeserverControlSummary, implicitOnCore: true, implicitOnClassic: true, baseDeclarationSlots: timeserverControlBaseDeclarationSlots, connectedPlugAppArmor: timeserverControlConnectedPlugAppArmor, reservedForOS: true, }) }
atomatt/snapd
interfaces/builtin/timeserver_control.go
GO
gpl-3.0
3,037
/* -*- c++ -*- */ /* * Copyright 2008-2011,2014 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio 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, or (at your option) * any later version. * * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef FREQUENCY_DISPLAY_PLOT_C #define FREQUENCY_DISPLAY_PLOT_C #include <gnuradio/qtgui/FrequencyDisplayPlot.h> #include <gnuradio/qtgui/qtgui_types.h> #include <qwt_scale_draw.h> #include <QColor> #include <iostream> /*********************************************************************** * Widget to provide mouse pointer coordinate text **********************************************************************/ class FreqDisplayZoomer: public QwtPlotZoomer, public FreqOffsetAndPrecisionClass { public: #if QWT_VERSION < 0x060100 FreqDisplayZoomer(QwtPlotCanvas* canvas, const unsigned int freqPrecision) #else /* QWT_VERSION < 0x060100 */ FreqDisplayZoomer(QWidget* canvas, const unsigned int freqPrecision) #endif /* QWT_VERSION < 0x060100 */ : QwtPlotZoomer(canvas), FreqOffsetAndPrecisionClass(freqPrecision) { setTrackerMode(QwtPicker::AlwaysOn); } virtual void updateTrackerText() { updateDisplay(); } void setUnitType(const std::string &type) { d_unitType = type; } protected: using QwtPlotZoomer::trackerText; virtual QwtText trackerText(QPoint const &p) const { QwtDoublePoint dp = QwtPlotZoomer::invTransform(p); QwtText t(QString("%1 %2, %3 dB") .arg(dp.x(), 0, 'f', getFrequencyPrecision()) .arg(d_unitType.c_str()).arg(dp.y(), 0, 'f', 2)); return t; } private: std::string d_unitType; }; /*********************************************************************** * Main frequency display plotter widget **********************************************************************/ FrequencyDisplayPlot::FrequencyDisplayPlot(int nplots, QWidget* parent) : DisplayPlot(nplots, parent) { d_start_frequency = -1; d_stop_frequency = 1; d_numPoints = 0; d_min_fft_data = new double[d_numPoints]; d_max_fft_data = new double[d_numPoints]; d_xdata = new double[d_numPoints]; d_half_freq = false; d_autoscale_shot = false; setAxisTitle(QwtPlot::xBottom, "Frequency (Hz)"); setAxisScaleDraw(QwtPlot::xBottom, new FreqDisplayScaleDraw(0)); d_ymin = -120; d_ymax = 10; setAxisScaleEngine(QwtPlot::yLeft, new QwtLinearScaleEngine); setAxisScale(QwtPlot::yLeft, d_ymin, d_ymax); setAxisTitle(QwtPlot::yLeft, "Relative Gain (dB)"); QList<QColor> default_colors; default_colors << QColor(Qt::blue) << QColor(Qt::red) << QColor(Qt::green) << QColor(Qt::black) << QColor(Qt::cyan) << QColor(Qt::magenta) << QColor(Qt::yellow) << QColor(Qt::gray) << QColor(Qt::darkRed) << QColor(Qt::darkGreen) << QColor(Qt::darkBlue) << QColor(Qt::darkGray); // Create a curve for each input // Automatically deleted when parent is deleted for(unsigned int i = 0; i < d_nplots; ++i) { d_ydata.push_back(new double[d_numPoints]); memset(d_ydata[i], 0x0, d_numPoints*sizeof(double)); d_plot_curve.push_back(new QwtPlotCurve(QString("Data %1").arg(i))); d_plot_curve[i]->attach(this); QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(default_colors[i]), QPen(default_colors[i]), QSize(7,7)); #if QWT_VERSION < 0x060000 d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_numPoints); d_plot_curve[i]->setSymbol(*symbol); #else d_plot_curve[i]->setRawSamples(d_xdata, d_ydata[i], d_numPoints); d_plot_curve[i]->setSymbol(symbol); #endif setLineColor(i, default_colors[i]); } // Create min/max plotter curves d_min_fft_plot_curve = new QwtPlotCurve("Min Hold"); d_min_fft_plot_curve->attach(this); const QColor default_min_fft_color = Qt::magenta; setMinFFTColor(default_min_fft_color); #if QWT_VERSION < 0x060000 d_min_fft_plot_curve->setRawData(d_xdata, d_min_fft_data, d_numPoints); #else d_min_fft_plot_curve->setRawSamples(d_xdata, d_min_fft_data, d_numPoints); #endif d_min_fft_plot_curve->setVisible(false); d_min_fft_plot_curve->setZ(0); d_max_fft_plot_curve = new QwtPlotCurve("Max Hold"); d_max_fft_plot_curve->attach(this); QColor default_max_fft_color = Qt::darkYellow; setMaxFFTColor(default_max_fft_color); #if QWT_VERSION < 0x060000 d_max_fft_plot_curve->setRawData(d_xdata, d_max_fft_data, d_numPoints); #else d_max_fft_plot_curve->setRawSamples(d_xdata, d_max_fft_data, d_numPoints); #endif d_max_fft_plot_curve->setVisible(false); d_max_fft_plot_curve->setZ(0); d_lower_intensity_marker= new QwtPlotMarker(); d_lower_intensity_marker->setLineStyle(QwtPlotMarker::HLine); QColor default_marker_lower_intensity_color = Qt::cyan; setMarkerLowerIntensityColor(default_marker_lower_intensity_color); d_lower_intensity_marker->attach(this); d_upper_intensity_marker = new QwtPlotMarker(); d_upper_intensity_marker->setLineStyle(QwtPlotMarker::HLine); QColor default_marker_upper_intensity_color = Qt::green; setMarkerUpperIntensityColor(default_marker_upper_intensity_color); d_upper_intensity_marker->attach(this); memset(d_xdata, 0x0, d_numPoints*sizeof(double)); for(int64_t number = 0; number < d_numPoints; number++){ d_min_fft_data[number] = 200.0; d_max_fft_data[number] = -280.0; } d_marker_peak_amplitude = new QwtPlotMarker(); QColor default_marker_peak_amplitude_color = Qt::yellow; setMarkerPeakAmplitudeColor(default_marker_peak_amplitude_color); /// THIS CAUSES A PROBLEM! //d_marker_peak_amplitude->attach(this); d_marker_noise_floor_amplitude = new QwtPlotMarker(); d_marker_noise_floor_amplitude->setLineStyle(QwtPlotMarker::HLine); QColor default_marker_noise_floor_amplitude_color = Qt::darkRed; setMarkerNoiseFloorAmplitudeColor(default_marker_noise_floor_amplitude_color); d_marker_noise_floor_amplitude->attach(this); d_marker_cf= new QwtPlotMarker(); d_marker_cf->setLineStyle(QwtPlotMarker::VLine); QColor default_marker_cf_color = Qt::lightGray; setMarkerCFColor(default_marker_cf_color); d_marker_cf->attach(this); d_marker_cf->hide(); d_peak_frequency = 0; d_peak_amplitude = -HUGE_VAL; d_noise_floor_amplitude = -HUGE_VAL; d_zoomer = new FreqDisplayZoomer(canvas(), 0); #if QWT_VERSION < 0x060000 d_zoomer->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif d_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); d_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); const QColor default_zoomer_color(Qt::darkRed); setZoomerColor(default_zoomer_color); // Do this after the zoomer has been built _resetXAxisPoints(); // Turn off min/max hold plots in legend #if QWT_VERSION < 0x060100 QWidget *w; w = legend()->find(d_min_fft_plot_curve); ((QwtLegendItem*)w)->setChecked(true); ((QwtLegendItem*)w)->setVisible(false); w = legend()->find(d_max_fft_plot_curve); ((QwtLegendItem*)w)->setChecked(true); ((QwtLegendItem*)w)->setVisible(false); legend()->setVisible(false); #else /* QWT_VERSION < 0x060100 */ QWidget *w; w = ((QwtLegend*)legend())->legendWidget(itemToInfo(d_min_fft_plot_curve)); ((QwtLegendLabel*)w)->setChecked(true); ((QwtLegendLabel*)w)->setVisible(false); w = ((QwtLegend*)legend())->legendWidget(itemToInfo(d_max_fft_plot_curve)); ((QwtLegendLabel*)w)->setChecked(true); ((QwtLegendLabel*)w)->setVisible(false); #endif /* QWT_VERSION < 0x060100 */ d_trigger_line = new QwtPlotMarker(); d_trigger_line->setLineStyle(QwtPlotMarker::HLine); d_trigger_line->setLinePen(QPen(Qt::red, 0.6, Qt::DashLine)); d_trigger_line->setRenderHint(QwtPlotItem::RenderAntialiased); d_trigger_line->setXValue(0.0); d_trigger_line->setYValue(0.0); replot(); } FrequencyDisplayPlot::~FrequencyDisplayPlot() { for(unsigned int i = 0; i < d_nplots; ++i) delete [] d_ydata[i]; delete[] d_max_fft_data; delete[] d_min_fft_data; delete[] d_xdata; } void FrequencyDisplayPlot::setYaxis(double min, double max) { // Get the new max/min values for the plot d_ymin = min; d_ymax = max; // Set the axis max/min to the new values setAxisScale(QwtPlot::yLeft, d_ymin, d_ymax); // Reset the base zoom level to the new axis scale set here. // But don't do it if we set the axis due to auto scaling. if(!d_autoscale_state) d_zoomer->setZoomBase(); } double FrequencyDisplayPlot::getYMin() const { return d_ymin; } double FrequencyDisplayPlot::getYMax() const { return d_ymax; } void FrequencyDisplayPlot::setFrequencyRange(const double centerfreq, const double bandwidth, const double units, const std::string &strunits) { double startFreq; double stopFreq = (centerfreq + bandwidth/2.0f) / units; if(d_half_freq) startFreq = centerfreq / units; else startFreq = (centerfreq - bandwidth/2.0f) / units; d_xdata_multiplier = units; bool reset = false; if((startFreq != d_start_frequency) || (stopFreq != d_stop_frequency)) reset = true; if(stopFreq > startFreq) { d_start_frequency = startFreq; d_stop_frequency = stopFreq; d_center_frequency = centerfreq / units; if((axisScaleDraw(QwtPlot::xBottom) != NULL) && (d_zoomer != NULL)) { double display_units = ceil(log10(units)/2.0); setAxisScaleDraw(QwtPlot::xBottom, new FreqDisplayScaleDraw(display_units)); setAxisTitle(QwtPlot::xBottom, QString("Frequency (%1)").arg(strunits.c_str())); if(reset) { _resetXAxisPoints(); clearMaxData(); clearMinData(); } ((FreqDisplayZoomer*)d_zoomer)->setFrequencyPrecision(display_units); ((FreqDisplayZoomer*)d_zoomer)->setUnitType(strunits); } } } double FrequencyDisplayPlot::getStartFrequency() const { return d_start_frequency; } double FrequencyDisplayPlot::getStopFrequency() const { return d_stop_frequency; } void FrequencyDisplayPlot::replot() { d_marker_noise_floor_amplitude->setYValue(d_noise_floor_amplitude); d_marker_peak_amplitude->setXValue(d_peak_frequency + d_start_frequency); // Make sure to take into account the start frequency // if(d_useCenterFrequencyFlag){ // d_marker_peak_amplitude->setXValue((d_peak_frequency/1000.0) + d_start_frequency); // } // else{ // _markerPeakAmplitude->setXValue(d_peak_frequency + d_start_frequency); // } d_marker_peak_amplitude->setYValue(d_peak_amplitude); QwtPlot::replot(); } void FrequencyDisplayPlot::plotNewData(const std::vector<double*> dataPoints, const int64_t numDataPoints, const double noiseFloorAmplitude, const double peakFrequency, const double peakAmplitude, const double timeInterval) { int64_t _npoints_in = d_half_freq ? numDataPoints/2 : numDataPoints; int64_t _in_index = d_half_freq ? _npoints_in : 0; if(!d_stop) { if(numDataPoints > 0) { if(_npoints_in != d_numPoints) { d_numPoints = _npoints_in; delete[] d_min_fft_data; delete[] d_max_fft_data; delete[] d_xdata; d_xdata = new double[d_numPoints]; d_min_fft_data = new double[d_numPoints]; d_max_fft_data = new double[d_numPoints]; for(unsigned int i = 0; i < d_nplots; ++i) { delete[] d_ydata[i]; d_ydata[i] = new double[d_numPoints]; #if QWT_VERSION < 0x060000 d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_numPoints); #else d_plot_curve[i]->setRawSamples(d_xdata, d_ydata[i], d_numPoints); #endif } #if QWT_VERSION < 0x060000 d_min_fft_plot_curve->setRawData(d_xdata, d_min_fft_data, d_numPoints); d_max_fft_plot_curve->setRawData(d_xdata, d_max_fft_data, d_numPoints); #else d_min_fft_plot_curve->setRawSamples(d_xdata, d_min_fft_data, d_numPoints); d_max_fft_plot_curve->setRawSamples(d_xdata, d_max_fft_data, d_numPoints); #endif _resetXAxisPoints(); clearMaxData(); clearMinData(); } double bottom=1e20, top=-1e20; for(unsigned int n = 0; n < d_nplots; ++n) { memcpy(d_ydata[n], &(dataPoints[n][_in_index]), _npoints_in*sizeof(double)); for(int64_t point = 0; point < _npoints_in; point++) { if(dataPoints[n][point] < d_min_fft_data[point]) { d_min_fft_data[point] = dataPoints[n][point+_in_index]; } if(dataPoints[n][point] > d_max_fft_data[point]) { d_max_fft_data[point] = dataPoints[n][point+_in_index]; } // Find overall top and bottom values in plot. // Used for autoscaling y-axis. if(dataPoints[n][point] < bottom) { bottom = dataPoints[n][point]; } if(dataPoints[n][point] > top) { top = dataPoints[n][point]; } } } if(d_autoscale_state) { _autoScale(bottom, top); if(d_autoscale_shot) { d_autoscale_state = false; d_autoscale_shot = false; } } d_noise_floor_amplitude = noiseFloorAmplitude; d_peak_frequency = peakFrequency; d_peak_amplitude = peakAmplitude; setUpperIntensityLevel(d_peak_amplitude); replot(); } } } void FrequencyDisplayPlot::plotNewData(const double* dataPoints, const int64_t numDataPoints, const double noiseFloorAmplitude, const double peakFrequency, const double peakAmplitude, const double timeInterval) { std::vector<double*> vecDataPoints; vecDataPoints.push_back((double*)dataPoints); plotNewData(vecDataPoints, numDataPoints, noiseFloorAmplitude, peakFrequency, peakAmplitude, timeInterval); } void FrequencyDisplayPlot::clearMaxData() { for(int64_t number = 0; number < d_numPoints; number++) { d_max_fft_data[number] = d_ymin; } } void FrequencyDisplayPlot::clearMinData() { for(int64_t number = 0; number < d_numPoints; number++) { d_min_fft_data[number] = d_ymax; } } void FrequencyDisplayPlot::_autoScale(double bottom, double top) { // Auto scale the y-axis with a margin of 10 dB on either side. d_ymin = bottom-10; d_ymax = top+10; setYaxis(d_ymin, d_ymax); } void FrequencyDisplayPlot::setAutoScale(bool state) { d_autoscale_state = state; } void FrequencyDisplayPlot::setAutoScaleShot() { d_autoscale_state = true; d_autoscale_shot = true; } void FrequencyDisplayPlot::setPlotPosHalf(bool half) { d_half_freq = half; if(half) d_start_frequency = d_center_frequency; } void FrequencyDisplayPlot::setMaxFFTVisible(const bool visibleFlag) { d_max_fft_visible = visibleFlag; d_max_fft_plot_curve->setVisible(visibleFlag); } const bool FrequencyDisplayPlot::getMaxFFTVisible() const { return d_max_fft_visible; } void FrequencyDisplayPlot::setMinFFTVisible(const bool visibleFlag) { d_min_fft_visible = visibleFlag; d_min_fft_plot_curve->setVisible(visibleFlag); } const bool FrequencyDisplayPlot::getMinFFTVisible() const { return d_min_fft_visible; } void FrequencyDisplayPlot::_resetXAxisPoints() { double fft_bin_size = (d_stop_frequency - d_start_frequency) / static_cast<double>(d_numPoints); double freqValue = d_start_frequency; for(int64_t loc = 0; loc < d_numPoints; loc++) { d_xdata[loc] = freqValue; freqValue += fft_bin_size; } setAxisScale(QwtPlot::xBottom, d_start_frequency, d_stop_frequency); // Set up zoomer base for maximum unzoom x-axis // and reset to maximum unzoom level QwtDoubleRect zbase = d_zoomer->zoomBase(); d_zoomer->zoom(zbase); d_zoomer->setZoomBase(zbase); d_zoomer->setZoomBase(true); d_zoomer->zoom(0); } void FrequencyDisplayPlot::setLowerIntensityLevel(const double lowerIntensityLevel) { d_lower_intensity_marker->setYValue(lowerIntensityLevel); } void FrequencyDisplayPlot::setUpperIntensityLevel(const double upperIntensityLevel) { d_upper_intensity_marker->setYValue(upperIntensityLevel); } void FrequencyDisplayPlot::setTraceColour(QColor c) { d_plot_curve[0]->setPen(QPen(c)); } void FrequencyDisplayPlot::setBGColour(QColor c) { QPalette palette; palette.setColor(canvas()->backgroundRole(), c); canvas()->setPalette(palette); } void FrequencyDisplayPlot::showCFMarker(const bool show) { if(show) d_marker_cf->show(); else d_marker_cf->hide(); } void FrequencyDisplayPlot::onPickerPointSelected(const QwtDoublePoint & p) { QPointF point = p; //fprintf(stderr,"onPickerPointSelected %f %f %d\n", point.x(), point.y(), d_xdata_multiplier); point.setX(point.x() * d_xdata_multiplier); emit plotPointSelected(point); } void FrequencyDisplayPlot::onPickerPointSelected6(const QPointF & p) { QPointF point = p; //fprintf(stderr,"onPickerPointSelected %f %f %d\n", point.x(), point.y(), d_xdata_multiplier); point.setX(point.x() * d_xdata_multiplier); emit plotPointSelected(point); } void FrequencyDisplayPlot::setYLabel(const std::string &label, const std::string &unit) { std::string l = label; if(unit.length() > 0) l += " (" + unit + ")"; setAxisTitle(QwtPlot::yLeft, QString(l.c_str())); } void FrequencyDisplayPlot::setMinFFTColor (QColor c) { d_min_fft_color = c; d_min_fft_plot_curve->setPen(QPen(c)); } const QColor FrequencyDisplayPlot::getMinFFTColor() const { return d_min_fft_color; } void FrequencyDisplayPlot::setMaxFFTColor (QColor c) { d_max_fft_color = c; d_max_fft_plot_curve->setPen(QPen(c)); } const QColor FrequencyDisplayPlot::getMaxFFTColor() const { return d_max_fft_color; } void FrequencyDisplayPlot::setMarkerLowerIntensityColor (QColor c) { d_marker_lower_intensity_color = c; d_lower_intensity_marker->setLinePen(QPen(c)); } const QColor FrequencyDisplayPlot::getMarkerLowerIntensityColor () const { return d_marker_lower_intensity_color; } void FrequencyDisplayPlot::setMarkerLowerIntensityVisible (bool visible) { d_marker_lower_intensity_visible = visible; if(visible) d_lower_intensity_marker->setLineStyle(QwtPlotMarker::HLine); else d_lower_intensity_marker->setLineStyle(QwtPlotMarker::NoLine); } const bool FrequencyDisplayPlot::getMarkerLowerIntensityVisible() const { return d_marker_lower_intensity_visible; } void FrequencyDisplayPlot::setMarkerUpperIntensityColor(QColor c) { d_marker_upper_intensity_color = c; d_upper_intensity_marker->setLinePen(QPen(c, 0, Qt::DotLine)); } const QColor FrequencyDisplayPlot::getMarkerUpperIntensityColor() const { return d_marker_upper_intensity_color; } void FrequencyDisplayPlot::setMarkerUpperIntensityVisible(bool visible) { d_marker_upper_intensity_visible = visible; if(visible) d_upper_intensity_marker->setLineStyle(QwtPlotMarker::HLine); else d_upper_intensity_marker->setLineStyle(QwtPlotMarker::NoLine); } const bool FrequencyDisplayPlot::getMarkerUpperIntensityVisible() const { return d_marker_upper_intensity_visible; } void FrequencyDisplayPlot::setMarkerPeakAmplitudeColor(QColor c) { d_marker_peak_amplitude_color = c; d_marker_peak_amplitude->setLinePen(QPen(c)); QwtSymbol symbol; symbol.setStyle(QwtSymbol::Diamond); symbol.setSize(8); symbol.setPen(QPen(c)); symbol.setBrush(QBrush(c)); #if QWT_VERSION < 0x060000 d_marker_peak_amplitude->setSymbol(symbol); #else d_marker_peak_amplitude->setSymbol(&symbol); #endif } const QColor FrequencyDisplayPlot::getMarkerPeakAmplitudeColor() const { return d_marker_peak_amplitude_color; } void FrequencyDisplayPlot::setMarkerNoiseFloorAmplitudeColor(QColor c) { d_marker_noise_floor_amplitude_color = c; d_marker_noise_floor_amplitude->setLinePen(QPen(c, 0, Qt::DotLine)); } const QColor FrequencyDisplayPlot::getMarkerNoiseFloorAmplitudeColor() const { return d_marker_noise_floor_amplitude_color; } void FrequencyDisplayPlot::setMarkerNoiseFloorAmplitudeVisible(bool visible) { d_marker_noise_floor_amplitude_visible = visible; if(visible) d_marker_noise_floor_amplitude->setLineStyle(QwtPlotMarker::HLine); else d_marker_noise_floor_amplitude->setLineStyle(QwtPlotMarker::NoLine); } const bool FrequencyDisplayPlot::getMarkerNoiseFloorAmplitudeVisible() const { return d_marker_noise_floor_amplitude_visible; } void FrequencyDisplayPlot::setMarkerCFColor(QColor c) { d_marker_cf_color = c; d_marker_cf->setLinePen(QPen(c, 0, Qt::DotLine)); } const QColor FrequencyDisplayPlot::getMarkerCFColor() const { return d_marker_cf_color; } void FrequencyDisplayPlot::attachTriggerLine(bool en) { if(en) { d_trigger_line->attach(this); } else { d_trigger_line->detach(); } } void FrequencyDisplayPlot::setTriggerLine(double level) { d_trigger_line->setYValue(level); } #endif /* FREQUENCY_DISPLAY_PLOT_C */
iohannez/gnuradio
gr-qtgui/lib/FrequencyDisplayPlot.cc
C++
gpl-3.0
21,199
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Defines Workflow event handlers * * @package block * @subpackage rate_course * @copyright 2009 Jenny Gray * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * Code was Rewritten for Moodle 2.X By Atar + Plus LTD for Comverse LTD. * @copyright &copy; 2011 Comverse LTD. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License */ /* List of handlers. */ $handlers = array ( /* * Course deleted. */ 'course_deleted' => array ( 'handlerfile' => '/blocks/rate_course/lib.php', // Where to call. 'handlerfunction' => 'course_delete', // What to call. 'schedule' => 'instant' ) );
InstaLearn/phonegaptest3
html/blocks/rate_course/db/events.php
PHP
gpl-3.0
1,368
import fs = require("fs"); export interface IFileWrite { path: string; content: string; } export async function writeFiles(files: IFileWrite[]): Promise<void> { "use strict"; for (var file of files) { await writeFile(file); }; } export function writeFile(file: IFileWrite): Promise<void> { "use strict"; return new Promise<void>(function (resolve, reject) { fs.writeFile(file.path, file.content, function (err) { if (err) { reject(err); } else { resolve(); } }); }); }
marianc/node-server-typescript-client
Tools/04.DataProviderGeneratorClient/src/modules/common/fileUtils.ts
TypeScript
gpl-3.0
599
class SkillsController < ApplicationController before_action :authenticate_user! load_and_authorize_resource # GET /skills # GET /skills.json def index @skills = Skill.all @page_title = "All Skills" respond_to do |format| format.html # index.html.erb format.json { render json: @skills } end end # GET /skills/1 # GET /skills/1.json def show @skill = Skill.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @skill } end end # GET /skills/new # GET /skills/new.json def new @skill = Skill.new respond_to do |format| format.html # new.html.erb format.json { render json: @skill } end end # GET /skills/1/edit def edit @skill = Skill.find(params[:id]) end # POST /skills # POST /skills.json def create @skill = Skill.new(skill_params) respond_to do |format| if @skill.save format.html { redirect_to skills_url, notice: 'Skill was successfully created.' } format.json { render json: @skill, status: :created, location: @skill } else format.html { render action: "new" } format.json { render json: @skill.errors, status: :unprocessable_entity } end end end # PUT /skills/1 # PUT /skills/1.json def update @skill = Skill.find(params[:id]) respond_to do |format| if @skill.update_attributes(skill_params) format.html { redirect_to skills_url, notice: 'Skill was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @skill.errors, status: :unprocessable_entity } end end end # DELETE /skills/1 # DELETE /skills/1.json def destroy @skill = Skill.find(params[:id]) @skill.destroy respond_to do |format| format.html { redirect_to skills_url } format.json { head :no_content } end end private def skill_params params.require(:skill).permit(:name, :status, course_ids: [], title_ids: []) end end
houhoulis/lims
app/controllers/skills_controller.rb
Ruby
gpl-3.0
2,118
/* * This file is part of VLE, a framework for multi-modeling, simulation * and analysis of complex dynamical systems. * https://www.vle-project.org * * Copyright (c) 2003-2018 Gauthier Quesnel <gauthier.quesnel@inra.fr> * Copyright (c) 2003-2018 ULCO http://www.univ-littoral.fr * Copyright (c) 2007-2018 INRA http://www.inra.fr * * See the AUTHORS or Authors.txt file for copyright owners and * contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef VLE_DEVS_THREAD_HPP #define VLE_DEVS_THREAD_HPP #include <vle/utils/Context.hpp> #include "devs/Simulator.hpp" #include "utils/ContextPrivate.hpp" #include "utils/i18n.hpp" #include <atomic> #include <chrono> #include <thread> namespace vle { namespace devs { template<typename SimulatorT> bool simulator_process(SimulatorT* simulator, Time time) noexcept { try { if (simulator->haveInternalEvent()) { if (not simulator->haveExternalEvents()) simulator->internalTransition(time); else simulator->confluentTransitions(time); } else { simulator->externalTransition(time); } } catch (...) { return false; } return true; } class SimulatorProcessParallel { std::vector<std::thread> m_workers; std::atomic<long int> m_block_id; std::atomic<long int> m_block_count; std::atomic<bool> m_running_flag; std::vector<Simulator*>* m_jobs; Time m_time; long m_block_size; void run() { while (m_running_flag.load(std::memory_order_relaxed)) { auto block = m_block_id.fetch_sub(1, std::memory_order_relaxed); if (block >= 0) { std::size_t begin = block * m_block_size; std::size_t begin_plus_b = begin + m_block_size; std::size_t end = std::min(m_jobs->size(), begin_plus_b); for (; begin < end; ++begin) simulator_process((*m_jobs)[begin], m_time); m_block_count.fetch_sub(1, std::memory_order_relaxed); } else { // // TODO: Maybe we can use a yield instead of this // sleep_for function to reduce the overhead of the // current thread. // std::this_thread::sleep_for(std::chrono::nanoseconds(1)); } } } public: SimulatorProcessParallel(utils::ContextPtr context) : m_jobs(nullptr) { long block_size = 8; { context->get_setting("vle.simulation.block-size", &block_size); if (block_size <= 0) m_block_size = 8; else m_block_size = block_size; } long workers_count = 1; { context->get_setting("vle.simulation.thread", &workers_count); if (workers_count <= 0) workers_count = 0l; } context->info(_("Simulation kernel: thread:%ld block-size:%ld\n"), workers_count, m_block_size); m_block_id.store(-1, std::memory_order_relaxed); m_block_count.store(-1, std::memory_order_relaxed); m_running_flag.store(true, std::memory_order_relaxed); try { m_workers.reserve(workers_count); for (long i = 0; i != workers_count; ++i) m_workers.emplace_back(&SimulatorProcessParallel::run, this); } catch (...) { m_running_flag.store(false, std::memory_order_relaxed); throw; } } ~SimulatorProcessParallel() noexcept { m_running_flag.store(false, std::memory_order_relaxed); for (auto& thread : m_workers) if (thread.joinable()) thread.join(); } bool parallelize() const noexcept { return not m_workers.empty(); } bool for_each(std::vector<Simulator*>& simulators, Time time) noexcept { m_jobs = &simulators; m_time = time; auto sz = static_cast<long>((simulators.size() / m_block_size) + ((simulators.size() % m_block_size) ? 1 : 0)); m_block_count.store(sz, std::memory_order_relaxed); m_block_id.store(sz, std::memory_order_relaxed); for (;;) { auto block = m_block_id.fetch_sub(1, std::memory_order_relaxed); if (block < 0) break; std::size_t begin = block * m_block_size; std::size_t begin_plus_b = begin + m_block_size; std::size_t end = std::min(m_jobs->size(), begin_plus_b); for (; begin < end; ++begin) simulator_process((*m_jobs)[begin], m_time); m_block_count.fetch_sub(1, std::memory_order_relaxed); } while (m_block_count.load(std::memory_order_relaxed) >= 0) std::this_thread::sleep_for(std::chrono::nanoseconds(1)); m_jobs = nullptr; return true; } }; } } #endif
quesnel/vle
src/vle/devs/Thread.hpp
C++
gpl-3.0
5,647
/* This file is part of VoltDB. * Copyright (C) 2008-2011 VoltDB Inc. * * 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 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. */ package everything; public class Shrinker extends ClientRunner.SubClient { @Override public void run() { if (getMBRss() < 800) { try { Thread.sleep(5000); } catch (InterruptedException e) {} return; } for (int i = 0; i < 500; i++) { // delete 100 rows from a random partition try { byte pval = (byte) (m_rand.nextInt() % 127); m_client.callProcedure(new Callback(), "Nibble你好", pval, 200); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(-1); } } } }
ifcharming/voltdb2.0
tests/test_apps/everything/src/everything/Shrinker.java
Java
gpl-3.0
1,834
/* Copyright 2014 the SumatraPDF project authors (see AUTHORS file). License: Simplified BSD (see COPYING.BSD) */ #include "BaseUtil.h" #include "FileWatcher.h" #include "FileUtil.h" #include "ThreadUtil.h" #include "WinUtil.h" #define NOLOG 1 #include "DebugLog.h" /* This code is tricky, so here's a high-level overview. More info at: http://qualapps.blogspot.com/2010/05/understanding-readdirectorychangesw.html Also, we did have a bug caused by incorrect use of CancelIo(). Here's a good description of its intricacies: http://blogs.msdn.com/b/oldnewthing/archive/2011/02/02/10123392.aspx We use ReadDirectoryChangesW() with overlapped i/o and i/o completion callback function. Callback function is called in the context of the thread that called ReadDirectoryChangesW() but only if it's in alertable state. Our ui thread isn't so we create our own thread and run code that calls ReadDirectoryChangesW() on that thread via QueueUserAPC(). g_watchedDirs and g_watchedFiles are shared between the main thread and worker thread so must be protected via g_threadCritSec. ReadDirectChangesW() doesn't always work for files on network drives, so for those files, we do manual checks, by using a timeout to periodically wake up thread. */ /* TODO: - should I end the thread when there are no files to watch? - a single file copy can generate multiple notifications for the same file. add some delay mechanism so that subsequent change notifications cancel a previous, delayed one ? E.g. a copy f2.pdf f.pdf generates 3 notifications if f2.pdf is 2 MB. - try to handle short file names as well: http://blogs.msdn.com/b/ericgu/archive/2005/10/07/478396.aspx but how to test it? - I could try to remove the need for g_threadCritSec by queing all code that touches g_watchedDirs/g_watchedFiles onto a thread via APC, but that's probably an overkill */ // there's a balance between responsiveness to changes and efficiency #define FILEWATCH_DELAY_IN_MS 1000 // Some people use overlapped.hEvent to store data but I'm playing it safe. struct OverlappedEx { OVERLAPPED overlapped; void * data; }; // info needed to detect that a file has changed struct FileState { FILETIME time; int64 size; }; struct WatchedDir { WatchedDir * next; const WCHAR * dirPath; HANDLE hDir; OverlappedEx overlapped; char buf[8*1024]; }; struct WatchedFile { WatchedFile * next; WatchedDir * watchedDir; const WCHAR * filePath; FileChangeObserver * observer; // if true, the file is on a network drive and we have // to check if it changed manually, by periodically checking // file state for changes bool isManualCheck; FileState fileState; }; static HANDLE g_threadHandle = 0; static DWORD g_threadId = 0; static HANDLE g_threadControlHandle = 0; // protects data structures shared between ui thread and file // watcher thread i.e. g_watchedDirs, g_watchedFiles static CRITICAL_SECTION g_threadCritSec; static WatchedDir * g_watchedDirs = NULL; static WatchedFile * g_watchedFiles = NULL; static void StartMonitoringDirForChanges(WatchedDir *wd); static void AwakeWatcherThread() { SetEvent(g_threadControlHandle); } static void GetFileState(const WCHAR *filePath, FileState* fs) { // Note: in my testing on network drive that is mac volume mounted // via parallels, lastWriteTime is not updated. lastAccessTime is, // but it's also updated when the file is being read from (e.g. // copy f.pdf f2.pdf will change lastAccessTime of f.pdf) // So I'm sticking with lastWriteTime fs->time = file::GetModificationTime(filePath); fs->size = file::GetSize(filePath); } static bool FileStateEq(FileState *fs1, FileState *fs2) { if (0 != CompareFileTime(&fs1->time, &fs2->time)) return false; if (fs1->size != fs2->size) return false; return true; } static bool FileStateChanged(const WCHAR *filePath, FileState *fs) { FileState fsTmp; GetFileState(filePath, &fsTmp); if (FileStateEq(fs, &fsTmp)) return false; memcpy(fs, &fsTmp, sizeof(*fs)); return true; } // TODO: per internet, fileName could be short, 8.3 dos-style name // and we don't handle that. On the other hand, I've only seen references // to it wrt. to rename/delete operation, which we don't get notified about // // TODO: to collapse multiple notifications for the same file, could put it on a // queue, restart the thread with a timeout, restart the process if we // get notified again before timeout expires, call OnFileChanges() when // timeout expires static void NotifyAboutFile(WatchedDir *d, const WCHAR *fileName) { lf(L"NotifyAboutFile(): %s", fileName); for (WatchedFile *wf = g_watchedFiles; wf; wf = wf->next) { if (wf->watchedDir != d) continue; const WCHAR *wfFileName = path::GetBaseName(wf->filePath); if (!str::EqI(fileName, wfFileName)) continue; // NOTE: It is not recommended to check whether the timestamp has changed // because the time granularity is so big that this can cause genuine // file notifications to be ignored. (This happens for instance for // PDF files produced by pdftex from small.tex document) wf->observer->OnFileChanged(); } } static void DeleteWatchedDir(WatchedDir *wd) { free((void*)wd->dirPath); free(wd); } static void CALLBACK ReadDirectoryChangesNotification(DWORD errCode, DWORD bytesTransfered, LPOVERLAPPED overlapped) { ScopedCritSec cs(&g_threadCritSec); OverlappedEx *over = (OverlappedEx*)overlapped; WatchedDir* wd = (WatchedDir*)over->data; lf(L"ReadDirectoryChangesNotification() dir: %s, numBytes: %d", wd->dirPath, (int)bytesTransfered); CrashIf(wd != wd->overlapped.data); if (errCode == ERROR_OPERATION_ABORTED) { lf(" ERROR_OPERATION_ABORTED"); DeleteWatchedDir(wd); return; } // This might mean overflow? Not sure. if (!bytesTransfered) return; FILE_NOTIFY_INFORMATION *notify = (FILE_NOTIFY_INFORMATION*)wd->buf; // collect files that changed, removing duplicates WStrVec changedFiles; for (;;) { ScopedMem<WCHAR> fileName(str::DupN(notify->FileName, notify->FileNameLength / sizeof(WCHAR))); // files can get updated either by writing to them directly or // by writing to a .tmp file first and then moving that file in place // (the latter only yields a RENAMED action with the expected file name) if (notify->Action == FILE_ACTION_MODIFIED || notify->Action == FILE_ACTION_RENAMED_NEW_NAME) { if (!changedFiles.Contains(fileName)) { lf(L"ReadDirectoryChangesNotification() FILE_ACTION_MODIFIED, for '%s'", fileName); changedFiles.Append(fileName.StealData()); } else { lf(L"ReadDirectoryChangesNotification() eliminating duplicate notification for '%s'", fileName); } } else { lf(L"ReadDirectoryChangesNotification() action=%d, for '%s'", (int)notify->Action, fileName); } // step to the next entry if there is one DWORD nextOff = notify->NextEntryOffset; if (!nextOff) break; notify = (FILE_NOTIFY_INFORMATION *)((char*)notify + nextOff); } StartMonitoringDirForChanges(wd); for (WCHAR **f = changedFiles.IterStart(); f; f = changedFiles.IterNext()) { NotifyAboutFile(wd, *f); } } static void CALLBACK StartMonitoringDirForChangesAPC(ULONG_PTR arg) { WatchedDir *wd = (WatchedDir*)arg; ZeroMemory(&wd->overlapped, sizeof(wd->overlapped)); OVERLAPPED *overlapped = (OVERLAPPED*)&(wd->overlapped); wd->overlapped.data = (HANDLE)wd; lf(L"StartMonitoringDirForChangesAPC() %s", wd->dirPath); CrashIf(g_threadId != GetCurrentThreadId()); ReadDirectoryChangesW( wd->hDir, wd->buf, // read results buffer sizeof(wd->buf), // length of buffer FALSE, // bWatchSubtree FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_FILE_NAME, // filter conditions NULL, // bytes returned overlapped, // overlapped buffer ReadDirectoryChangesNotification); // completion routine } static void StartMonitoringDirForChanges(WatchedDir *wd) { QueueUserAPC(StartMonitoringDirForChangesAPC, g_threadHandle, (ULONG_PTR)wd); } static DWORD GetTimeoutInMs() { ScopedCritSec cs(&g_threadCritSec); for (WatchedFile *wf = g_watchedFiles; wf; wf = wf->next) { if (wf->isManualCheck) return FILEWATCH_DELAY_IN_MS; } return INFINITE; } static void RunManualCheck() { ScopedCritSec cs(&g_threadCritSec); for (WatchedFile *wf = g_watchedFiles; wf; wf = wf->next) { if (!wf->isManualCheck) continue; if (FileStateChanged(wf->filePath, &wf->fileState)) { lf(L"RunManualCheck() %s changed", wf->filePath); wf->observer->OnFileChanged(); } } } static DWORD WINAPI FileWatcherThread(void *param) { HANDLE handles[1]; // must be alertable to receive ReadDirectoryChangesW() callbacks and APCs BOOL alertable = TRUE; for (;;) { handles[0] = g_threadControlHandle; DWORD timeout = GetTimeoutInMs(); DWORD obj = WaitForMultipleObjectsEx(1, handles, FALSE, timeout, alertable); if (WAIT_TIMEOUT == obj) { RunManualCheck(); continue; } if (WAIT_IO_COMPLETION == obj) { // APC complete. Nothing to do lf("FileWatcherThread(): APC complete"); continue; } int n = (int)(obj - WAIT_OBJECT_0); if (n == 0) { // a thread was explicitly awaken ResetEvent(g_threadControlHandle); lf("FileWatcherThread(): g_threadControlHandle signalled"); } else { dbglog::CrashLogF("FileWatcherThread(): n=%d", n); CrashIf(true); } } } static void StartThreadIfNecessary() { if (g_threadHandle) return; InitializeCriticalSection(&g_threadCritSec); g_threadControlHandle = CreateEvent(NULL, TRUE, FALSE, NULL); g_threadHandle = CreateThread(NULL, 0, FileWatcherThread, 0, 0, &g_threadId); SetThreadName(g_threadId, "FileWatcherThread"); } static WatchedDir *FindExistingWatchedDir(const WCHAR *dirPath) { for (WatchedDir *wd = g_watchedDirs; wd; wd = wd->next) { // TODO: normalize dirPath? if (str::EqI(dirPath, wd->dirPath)) return wd; } return NULL; } static void CALLBACK StopMonitoringDirAPC(ULONG_PTR arg) { WatchedDir *wd = (WatchedDir*)arg; lf("StopMonitoringDirAPC() wd=0x%p", wd); // this will cause ReadDirectoryChangesNotification() to be called // with errCode = ERROR_OPERATION_ABORTED BOOL ok = CancelIo(wd->hDir); if (!ok) LogLastError(); SafeCloseHandle(&wd->hDir); } static WatchedDir *NewWatchedDir(const WCHAR *dirPath) { HANDLE hDir = CreateFile( dirPath, FILE_LIST_DIRECTORY, FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); if (INVALID_HANDLE_VALUE == hDir) return NULL; WatchedDir *wd = AllocStruct<WatchedDir>(); wd->hDir = hDir; wd->dirPath = str::Dup(dirPath); ListInsert(&g_watchedDirs, wd); return wd; } static WatchedFile *NewWatchedFile(const WCHAR *filePath, FileChangeObserver *observer) { bool isManualCheck = PathIsNetworkPath(filePath); ScopedMem<WCHAR> dirPath(path::GetDir(filePath)); WatchedDir *wd = NULL; bool newDir = false; if (!isManualCheck) { wd = FindExistingWatchedDir(dirPath); if (!wd) { wd = NewWatchedDir(dirPath); if (!wd) return NULL; newDir = true; } } WatchedFile *wf = AllocStruct<WatchedFile>(); wf->filePath = str::Dup(filePath); wf->observer = observer; wf->watchedDir = wd; wf->isManualCheck = isManualCheck; ListInsert(&g_watchedFiles, wf); if (wf->isManualCheck) { GetFileState(filePath, &wf->fileState); AwakeWatcherThread(); } else { if (newDir) StartMonitoringDirForChanges(wf->watchedDir); } return wf; } static void DeleteWatchedFile(WatchedFile *wf) { free((void*)wf->filePath); delete wf->observer; free(wf); } /* Subscribe for notifications about file changes. When a file changes, we'll call observer->OnFileChanged(). We take ownership of observer object. Returns a cancellation token that can be used in FileWatcherUnsubscribe(). That way we can support multiple callers subscribing to the same file. */ WatchedFile *FileWatcherSubscribe(const WCHAR *path, FileChangeObserver *observer) { CrashIf(!observer); lf(L"FileWatcherSubscribe() path: %s", path); if (!file::Exists(path)) { delete observer; return NULL; } StartThreadIfNecessary(); ScopedCritSec cs(&g_threadCritSec); return NewWatchedFile(path, observer); } static bool IsWatchedDirReferenced(WatchedDir *wd) { for (WatchedFile *wf = g_watchedFiles; wf; wf = wf->next) { if (wf->watchedDir == wd) return true; } return false; } static void RemoveWatchedDirIfNotReferenced(WatchedDir *wd) { if (IsWatchedDirReferenced(wd)) return; bool ok = ListRemove(&g_watchedDirs, wd); CrashIf(!ok); // memory will be eventually freed in ReadDirectoryChangesNotification() QueueUserAPC(StopMonitoringDirAPC, g_threadHandle, (ULONG_PTR)wd); } static void RemoveWatchedFile(WatchedFile *wf) { WatchedDir *wd = wf->watchedDir; bool ok = ListRemove(&g_watchedFiles, wf); CrashIf(!ok); bool needsAwakeThread = wf->isManualCheck; DeleteWatchedFile(wf); if (needsAwakeThread) AwakeWatcherThread(); else RemoveWatchedDirIfNotReferenced(wd); } void FileWatcherUnsubscribe(WatchedFile *wf) { if (!wf) return; CrashIf(!g_threadHandle); ScopedCritSec cs(&g_threadCritSec); RemoveWatchedFile(wf); }
ibb-zimmers/betsynetpdf
sumatrapdf/src/utils/FileWatcher.cpp
C++
gpl-3.0
15,051
var searchData= [ ['query',['query',['../classcoda_1_1db_1_1query.html',1,'coda::db']]] ];
ryjen/db
html/search/classes_8.js
JavaScript
gpl-3.0
93
// Copyright 2014 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 "platform/network/HTTPParsers.h" #include "platform/heap/Handle.h" #include "platform/network/ResourceResponse.h" #include "platform/weborigin/Suborigin.h" #include "testing/gtest/include/gtest/gtest.h" #include "wtf/MathExtras.h" #include "wtf/dtoa/utils.h" #include "wtf/text/AtomicString.h" namespace blink { TEST(HTTPParsersTest, ParseCacheControl) { CacheControlHeader header; header = parseCacheControlDirectives("no-cache", AtomicString()); EXPECT_TRUE(header.parsed); EXPECT_TRUE(header.containsNoCache); EXPECT_FALSE(header.containsNoStore); EXPECT_FALSE(header.containsMustRevalidate); EXPECT_TRUE(std::isnan(header.maxAge)); header = parseCacheControlDirectives("no-cache no-store", AtomicString()); EXPECT_TRUE(header.parsed); EXPECT_TRUE(header.containsNoCache); EXPECT_FALSE(header.containsNoStore); EXPECT_FALSE(header.containsMustRevalidate); EXPECT_TRUE(std::isnan(header.maxAge)); header = parseCacheControlDirectives("no-store must-revalidate", AtomicString()); EXPECT_TRUE(header.parsed); EXPECT_FALSE(header.containsNoCache); EXPECT_TRUE(header.containsNoStore); EXPECT_FALSE(header.containsMustRevalidate); EXPECT_TRUE(std::isnan(header.maxAge)); header = parseCacheControlDirectives("max-age=0", AtomicString()); EXPECT_TRUE(header.parsed); EXPECT_FALSE(header.containsNoCache); EXPECT_FALSE(header.containsNoStore); EXPECT_FALSE(header.containsMustRevalidate); EXPECT_EQ(0.0, header.maxAge); header = parseCacheControlDirectives("max-age", AtomicString()); EXPECT_TRUE(header.parsed); EXPECT_FALSE(header.containsNoCache); EXPECT_FALSE(header.containsNoStore); EXPECT_FALSE(header.containsMustRevalidate); EXPECT_TRUE(std::isnan(header.maxAge)); header = parseCacheControlDirectives("max-age=0 no-cache", AtomicString()); EXPECT_TRUE(header.parsed); EXPECT_FALSE(header.containsNoCache); EXPECT_FALSE(header.containsNoStore); EXPECT_FALSE(header.containsMustRevalidate); EXPECT_EQ(0.0, header.maxAge); header = parseCacheControlDirectives("no-cache=foo", AtomicString()); EXPECT_TRUE(header.parsed); EXPECT_FALSE(header.containsNoCache); EXPECT_FALSE(header.containsNoStore); EXPECT_FALSE(header.containsMustRevalidate); EXPECT_TRUE(std::isnan(header.maxAge)); header = parseCacheControlDirectives("nonsense", AtomicString()); EXPECT_TRUE(header.parsed); EXPECT_FALSE(header.containsNoCache); EXPECT_FALSE(header.containsNoStore); EXPECT_FALSE(header.containsMustRevalidate); EXPECT_TRUE(std::isnan(header.maxAge)); header = parseCacheControlDirectives("\rno-cache\n\t\v\0\b", AtomicString()); EXPECT_TRUE(header.parsed); EXPECT_TRUE(header.containsNoCache); EXPECT_FALSE(header.containsNoStore); EXPECT_FALSE(header.containsMustRevalidate); EXPECT_TRUE(std::isnan(header.maxAge)); header = parseCacheControlDirectives(" no-cache ", AtomicString()); EXPECT_TRUE(header.parsed); EXPECT_TRUE(header.containsNoCache); EXPECT_FALSE(header.containsNoStore); EXPECT_FALSE(header.containsMustRevalidate); EXPECT_TRUE(std::isnan(header.maxAge)); header = parseCacheControlDirectives(AtomicString(), "no-cache"); EXPECT_TRUE(header.parsed); EXPECT_TRUE(header.containsNoCache); EXPECT_FALSE(header.containsNoStore); EXPECT_FALSE(header.containsMustRevalidate); EXPECT_TRUE(std::isnan(header.maxAge)); } TEST(HTTPParsersTest, CommaDelimitedHeaderSet) { CommaDelimitedHeaderSet set1; CommaDelimitedHeaderSet set2; parseCommaDelimitedHeader("dpr, rw, whatever", set1); EXPECT_TRUE(set1.contains("dpr")); EXPECT_TRUE(set1.contains("rw")); EXPECT_TRUE(set1.contains("whatever")); parseCommaDelimitedHeader("dprw\t , fo\to", set2); EXPECT_FALSE(set2.contains("dpr")); EXPECT_FALSE(set2.contains("rw")); EXPECT_FALSE(set2.contains("whatever")); EXPECT_TRUE(set2.contains("dprw")); EXPECT_FALSE(set2.contains("foo")); EXPECT_TRUE(set2.contains("fo\to")); } TEST(HTTPParsersTest, HTTPFieldContent) { const UChar hiraganaA[2] = {0x3042, 0}; EXPECT_TRUE(blink::isValidHTTPFieldContentRFC7230("\xd0\xa1")); EXPECT_TRUE(blink::isValidHTTPFieldContentRFC7230("t t")); EXPECT_TRUE(blink::isValidHTTPFieldContentRFC7230("t\tt")); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230(" ")); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230("")); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230("\x7f")); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230("t\rt")); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230("t\nt")); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230("t\bt")); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230("t\vt")); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230(" t")); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230("t ")); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230(String("t\0t", 3))); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230(String("\0", 1))); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230(String("test \0, 6"))); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230(String("test "))); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230("test\r\n data")); EXPECT_FALSE(blink::isValidHTTPFieldContentRFC7230(String(hiraganaA))); } TEST(HTTPParsersTest, HTTPToken) { const UChar hiraganaA[2] = {0x3042, 0}; const UChar latinCapitalAWithMacron[2] = {0x100, 0}; EXPECT_TRUE(blink::isValidHTTPToken("gzip")); EXPECT_TRUE(blink::isValidHTTPToken("no-cache")); EXPECT_TRUE(blink::isValidHTTPToken("86400")); EXPECT_TRUE(blink::isValidHTTPToken("~")); EXPECT_FALSE(blink::isValidHTTPToken("")); EXPECT_FALSE(blink::isValidHTTPToken(" ")); EXPECT_FALSE(blink::isValidHTTPToken("\t")); EXPECT_FALSE(blink::isValidHTTPToken("\x7f")); EXPECT_FALSE(blink::isValidHTTPToken("\xff")); EXPECT_FALSE(blink::isValidHTTPToken(String(latinCapitalAWithMacron))); EXPECT_FALSE(blink::isValidHTTPToken("t a")); EXPECT_FALSE(blink::isValidHTTPToken("()")); EXPECT_FALSE(blink::isValidHTTPToken("(foobar)")); EXPECT_FALSE(blink::isValidHTTPToken(String("\0", 1))); EXPECT_FALSE(blink::isValidHTTPToken(String(hiraganaA))); } TEST(HTTPParsersTest, ExtractMIMETypeFromMediaType) { const AtomicString textHtml("text/html"); EXPECT_EQ(textHtml, extractMIMETypeFromMediaType(AtomicString("text/html"))); EXPECT_EQ(textHtml, extractMIMETypeFromMediaType( AtomicString("text/html; charset=iso-8859-1"))); // Quoted charset parameter EXPECT_EQ(textHtml, extractMIMETypeFromMediaType( AtomicString("text/html; charset=\"quoted\""))); // Multiple parameters EXPECT_EQ(textHtml, extractMIMETypeFromMediaType( AtomicString("text/html; charset=x; foo=bar"))); // OWSes are trimmed. EXPECT_EQ(textHtml, extractMIMETypeFromMediaType(AtomicString(" text/html "))); EXPECT_EQ(textHtml, extractMIMETypeFromMediaType(AtomicString("\ttext/html \t"))); EXPECT_EQ(textHtml, extractMIMETypeFromMediaType( AtomicString("text/html ; charset=iso-8859-1"))); // Non-standard multiple type/subtype listing using a comma as a separator // is accepted. EXPECT_EQ(textHtml, extractMIMETypeFromMediaType(AtomicString("text/html,text/plain"))); EXPECT_EQ(textHtml, extractMIMETypeFromMediaType( AtomicString("text/html , text/plain"))); EXPECT_EQ(textHtml, extractMIMETypeFromMediaType( AtomicString("text/html\t,\ttext/plain"))); EXPECT_EQ(textHtml, extractMIMETypeFromMediaType(AtomicString( "text/html,text/plain;charset=iso-8859-1"))); // Preserves case. EXPECT_EQ("tExt/hTMl", extractMIMETypeFromMediaType(AtomicString("tExt/hTMl"))); EXPECT_EQ(emptyString(), extractMIMETypeFromMediaType(AtomicString(", text/html"))); EXPECT_EQ(emptyString(), extractMIMETypeFromMediaType(AtomicString("; text/html"))); // If no normalization is required, the same AtomicString should be returned. const AtomicString& passthrough = extractMIMETypeFromMediaType(textHtml); EXPECT_EQ(textHtml.impl(), passthrough.impl()); } TEST(HTTPParsersTest, ExtractMIMETypeFromMediaTypeInvalidInput) { // extractMIMETypeFromMediaType() returns the string before the first // semicolon after trimming OWSes at the head and the tail even if the // string doesn't conform to the media-type ABNF defined in the RFC 7231. // These behaviors could be fixed later when ready. // Non-OWS characters meaning space are not trimmed. EXPECT_EQ(AtomicString("\r\ntext/html\r\n"), extractMIMETypeFromMediaType(AtomicString("\r\ntext/html\r\n"))); // U+2003, EM SPACE (UTF-8: E2 80 83). EXPECT_EQ(AtomicString::fromUTF8("\xE2\x80\x83text/html"), extractMIMETypeFromMediaType( AtomicString::fromUTF8("\xE2\x80\x83text/html"))); // Invalid type/subtype. EXPECT_EQ(AtomicString("a"), extractMIMETypeFromMediaType(AtomicString("a"))); // Invalid parameters. EXPECT_EQ(AtomicString("text/html"), extractMIMETypeFromMediaType(AtomicString("text/html;wow"))); EXPECT_EQ(AtomicString("text/html"), extractMIMETypeFromMediaType(AtomicString("text/html;;;;;;"))); EXPECT_EQ(AtomicString("text/html"), extractMIMETypeFromMediaType(AtomicString("text/html; = = = "))); // Only OWSes at either the beginning or the end of the type/subtype // portion. EXPECT_EQ(AtomicString("text / html"), extractMIMETypeFromMediaType(AtomicString("text / html"))); EXPECT_EQ(AtomicString("t e x t / h t m l"), extractMIMETypeFromMediaType(AtomicString("t e x t / h t m l"))); EXPECT_EQ(AtomicString("text\r\n/\nhtml"), extractMIMETypeFromMediaType(AtomicString("text\r\n/\nhtml"))); EXPECT_EQ(AtomicString("text\n/\nhtml"), extractMIMETypeFromMediaType(AtomicString("text\n/\nhtml"))); EXPECT_EQ(AtomicString::fromUTF8("text\xE2\x80\x83/html"), extractMIMETypeFromMediaType( AtomicString::fromUTF8("text\xE2\x80\x83/html"))); } void expectParseNamePass(const char* message, String header, String expectedName) { SCOPED_TRACE(message); Vector<String> messages; Suborigin suborigin; EXPECT_TRUE(parseSuboriginHeader(header, &suborigin, messages)); EXPECT_EQ(expectedName, suborigin.name()); } void expectParseNameFail(const char* message, String header) { SCOPED_TRACE(message); Vector<String> messages; Suborigin suborigin; EXPECT_FALSE(parseSuboriginHeader(header, &suborigin, messages)); EXPECT_EQ(String(), suborigin.name()); } void expectParsePolicyPass( const char* message, String header, const Suborigin::SuboriginPolicyOptions expectedPolicy[], size_t numPolicies) { SCOPED_TRACE(message); Vector<String> messages; Suborigin suborigin; EXPECT_TRUE(parseSuboriginHeader(header, &suborigin, messages)); unsigned policiesMask = 0; for (size_t i = 0; i < numPolicies; i++) policiesMask |= static_cast<unsigned>(expectedPolicy[i]); EXPECT_EQ(policiesMask, suborigin.optionsMask()); } void expectParsePolicyFail(const char* message, String header) { SCOPED_TRACE(message); Vector<String> messages; Suborigin suborigin; EXPECT_FALSE(parseSuboriginHeader(header, &suborigin, messages)); EXPECT_EQ(String(), suborigin.name()); } TEST(HTTPParsersTest, SuboriginParseValidNames) { // Single headers expectParseNamePass("Alpha", "foo", "foo"); expectParseNamePass("Whitespace alpha", " foo ", "foo"); expectParseNamePass("Alphanumeric", "f0o", "f0o"); expectParseNamePass("Numeric at end", "foo42", "foo42"); // Mulitple headers should only give the first name expectParseNamePass("Multiple headers, no whitespace", "foo,bar", "foo"); expectParseNamePass("Multiple headers, whitespace before second", "foo, bar", "foo"); expectParseNamePass( "Multiple headers, whitespace after first and before second", "foo, bar", "foo"); expectParseNamePass("Multiple headers, empty second ignored", "foo, bar", "foo"); expectParseNamePass("Multiple headers, invalid second ignored", "foo, bar", "foo"); } TEST(HTTPParsersTest, SuboriginParseInvalidNames) { // Single header, invalid value expectParseNameFail("Empty header", ""); expectParseNameFail("Numeric", "42"); expectParseNameFail("Hyphen middle", "foo-bar"); expectParseNameFail("Hyphen start", "-foobar"); expectParseNameFail("Hyphen end", "foobar-"); expectParseNameFail("Whitespace in middle", "foo bar"); expectParseNameFail("Invalid character at end of name", "foobar'"); expectParseNameFail("Invalid character at start of name", "'foobar"); expectParseNameFail("Invalid character in middle of name", "foo'bar"); expectParseNameFail("Alternate invalid character in middle of name", "foob@r"); expectParseNameFail("First cap", "Foo"); expectParseNameFail("All cap", "FOO"); // Multiple headers, invalid value(s) expectParseNameFail("Multple headers, empty first header", ", bar"); expectParseNameFail("Multple headers, both empty headers", ","); expectParseNameFail("Multple headers, invalid character in first header", "f@oo, bar"); expectParseNameFail("Multple headers, invalid character in both headers", "f@oo, b@r"); } TEST(HTTPParsersTest, SuboriginParseValidPolicy) { const Suborigin::SuboriginPolicyOptions unsafePostmessageSend[] = { Suborigin::SuboriginPolicyOptions::UnsafePostMessageSend}; const Suborigin::SuboriginPolicyOptions unsafePostmessageReceive[] = { Suborigin::SuboriginPolicyOptions::UnsafePostMessageReceive}; const Suborigin::SuboriginPolicyOptions unsafePostmessageSendAndReceive[] = { Suborigin::SuboriginPolicyOptions::UnsafePostMessageSend, Suborigin::SuboriginPolicyOptions::UnsafePostMessageReceive}; const Suborigin::SuboriginPolicyOptions unsafeCookies[] = { Suborigin::SuboriginPolicyOptions::UnsafeCookies}; const Suborigin::SuboriginPolicyOptions unsafeCredentials[] = { Suborigin::SuboriginPolicyOptions::UnsafeCredentials}; const Suborigin::SuboriginPolicyOptions allOptions[] = { Suborigin::SuboriginPolicyOptions::UnsafePostMessageSend, Suborigin::SuboriginPolicyOptions::UnsafePostMessageReceive, Suborigin::SuboriginPolicyOptions::UnsafeCookies, Suborigin::SuboriginPolicyOptions::UnsafeCredentials}; // All simple, valid policies expectParsePolicyPass( "One policy, unsafe-postmessage-send", "foobar 'unsafe-postmessage-send'", unsafePostmessageSend, ARRAY_SIZE(unsafePostmessageSend)); expectParsePolicyPass("One policy, unsafe-postmessage-receive", "foobar 'unsafe-postmessage-receive'", unsafePostmessageReceive, ARRAY_SIZE(unsafePostmessageReceive)); expectParsePolicyPass("One policy, unsafe-cookies", "foobar 'unsafe-cookies'", unsafeCookies, ARRAY_SIZE(unsafeCookies)); expectParsePolicyPass("One policy, unsafe-credentials", "foobar 'unsafe-credentials'", unsafeCredentials, ARRAY_SIZE(unsafeCredentials)); // Formatting differences of policies and multiple policies expectParsePolicyPass("One policy, whitespace all around", "foobar 'unsafe-postmessage-send' ", unsafePostmessageSend, ARRAY_SIZE(unsafePostmessageSend)); expectParsePolicyPass( "Multiple, same policies", "foobar 'unsafe-postmessage-send' 'unsafe-postmessage-send'", unsafePostmessageSend, ARRAY_SIZE(unsafePostmessageSend)); expectParsePolicyPass( "Multiple, different policies", "foobar 'unsafe-postmessage-send' 'unsafe-postmessage-receive'", unsafePostmessageSendAndReceive, ARRAY_SIZE(unsafePostmessageSendAndReceive)); expectParsePolicyPass("Many different policies", "foobar 'unsafe-postmessage-send' " "'unsafe-postmessage-receive' 'unsafe-cookies' " "'unsafe-credentials'", allOptions, ARRAY_SIZE(allOptions)); expectParsePolicyPass("One policy, unknown option", "foobar 'unknown-option'", {}, 0); } TEST(HTTPParsersTest, SuboriginParseInvalidPolicy) { expectParsePolicyFail("One policy, no suborigin name", "'unsafe-postmessage-send'"); expectParsePolicyFail("One policy, invalid characters", "foobar 'un$afe-postmessage-send'"); expectParsePolicyFail("One policy, caps", "foobar 'UNSAFE-POSTMESSAGE-SEND'"); expectParsePolicyFail("One policy, missing first quote", "foobar unsafe-postmessage-send'"); expectParsePolicyFail("One policy, missing last quote", "foobar 'unsafe-postmessage-send"); expectParsePolicyFail("One policy, invalid character at end", "foobar 'unsafe-postmessage-send';"); expectParsePolicyFail( "Multiple policies, extra character between options", "foobar 'unsafe-postmessage-send' ; 'unsafe-postmessage-send'"); expectParsePolicyFail("Policy that is a single quote", "foobar '"); expectParsePolicyFail("Valid policy and then policy that is a single quote", "foobar 'unsafe-postmessage-send' '"); } TEST(HTTPParsersTest, ParseHTTPRefresh) { double delay; String url; EXPECT_FALSE(parseHTTPRefresh("", nullptr, delay, url)); EXPECT_FALSE(parseHTTPRefresh(" ", nullptr, delay, url)); EXPECT_TRUE(parseHTTPRefresh("123 ", nullptr, delay, url)); EXPECT_EQ(123.0, delay); EXPECT_TRUE(url.isEmpty()); EXPECT_TRUE(parseHTTPRefresh("1 ; url=dest", nullptr, delay, url)); EXPECT_EQ(1.0, delay); EXPECT_EQ("dest", url); EXPECT_TRUE( parseHTTPRefresh("1 ;\nurl=dest", isASCIISpace<UChar>, delay, url)); EXPECT_EQ(1.0, delay); EXPECT_EQ("dest", url); EXPECT_TRUE(parseHTTPRefresh("1 ;\nurl=dest", nullptr, delay, url)); EXPECT_EQ(1.0, delay); EXPECT_EQ("url=dest", url); EXPECT_TRUE(parseHTTPRefresh("1 url=dest", nullptr, delay, url)); EXPECT_EQ(1.0, delay); EXPECT_EQ("dest", url); EXPECT_TRUE( parseHTTPRefresh("10\nurl=dest", isASCIISpace<UChar>, delay, url)); EXPECT_EQ(10, delay); EXPECT_EQ("dest", url); } TEST(HTTPParsersTest, ParseMultipartHeadersResult) { struct { const char* data; const bool result; const size_t end; } tests[] = { {"This is junk", false, 0}, {"Foo: bar\nBaz:\n\nAfter:\n", true, 15}, {"Foo: bar\nBaz:\n", false, 0}, {"Foo: bar\r\nBaz:\r\n\r\nAfter:\r\n", true, 18}, {"Foo: bar\r\nBaz:\r\n", false, 0}, {"Foo: bar\nBaz:\r\n\r\nAfter:\n\n", true, 17}, {"Foo: bar\r\nBaz:\n", false, 0}, {"\r\n", true, 2}, }; for (size_t i = 0; i < WTF_ARRAY_LENGTH(tests); ++i) { ResourceResponse response; size_t end = 0; bool result = parseMultipartHeadersFromBody( tests[i].data, strlen(tests[i].data), &response, &end); EXPECT_EQ(tests[i].result, result); EXPECT_EQ(tests[i].end, end); } } TEST(HTTPParsersTest, ParseMultipartHeaders) { ResourceResponse response; response.addHTTPHeaderField("foo", "bar"); response.addHTTPHeaderField("range", "piyo"); response.addHTTPHeaderField("content-length", "999"); const char data[] = "content-type: image/png\ncontent-length: 10\n\n"; size_t end = 0; bool result = parseMultipartHeadersFromBody(data, strlen(data), &response, &end); EXPECT_TRUE(result); EXPECT_EQ(strlen(data), end); EXPECT_EQ("image/png", response.httpHeaderField("content-type")); EXPECT_EQ("10", response.httpHeaderField("content-length")); EXPECT_EQ("bar", response.httpHeaderField("foo")); EXPECT_EQ(AtomicString(), response.httpHeaderField("range")); } TEST(HTTPParsersTest, ParseMultipartHeadersContentCharset) { ResourceResponse response; const char data[] = "content-type: text/html; charset=utf-8\n\n"; size_t end = 0; bool result = parseMultipartHeadersFromBody(data, strlen(data), &response, &end); EXPECT_TRUE(result); EXPECT_EQ(strlen(data), end); EXPECT_EQ("text/html; charset=utf-8", response.httpHeaderField("content-type")); EXPECT_EQ("utf-8", response.textEncodingName()); } } // namespace blink
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Source/platform/network/HTTPParsersTest.cpp
C++
gpl-3.0
20,767
package com.yalantis.ucrop.util; import android.graphics.RectF; public class RectUtils { /** * Gets a float array of the 2D coordinates representing a rectangles * corners. * The order of the corners in the float array is: * 0------->1 * ^ | * | | * | v * 3<-------2 * * @param r the rectangle to get the corners of * @return the float array of corners (8 floats) */ public static float[] getCornersFromRect(RectF r) { return new float[]{ r.left, r.top, r.right, r.top, r.right, r.bottom, r.left, r.bottom }; } /** * Gets a float array of two lengths representing a rectangles width and height * The order of the corners in the input float array is: * 0------->1 * ^ | * | | * | v * 3<-------2 * * @param corners the float array of corners (8 floats) * @return the float array of width and height (2 floats) */ public static float[] getRectSidesFromCorners(float[] corners) { return new float[]{(float) Math.sqrt(Math.pow(corners[0] - corners[2], 2) + Math.pow(corners[1] - corners[3], 2)), (float) Math.sqrt(Math.pow(corners[2] - corners[4], 2) + Math.pow(corners[3] - corners[5], 2))}; } public static float[] getCenterFromRect(RectF r) { return new float[]{r.centerX(), r.centerY()}; } /** * Takes an array of 2D coordinates representing corners and returns the * smallest rectangle containing those coordinates. * * @param array array of 2D coordinates * @return smallest rectangle containing coordinates */ public static RectF trapToRect(float[] array) { RectF r = new RectF(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); for (int i = 1; i < array.length; i += 2) { float x = array[i - 1]; float y = array[i]; r.left = (x < r.left) ? x : r.left; r.top = (y < r.top) ? y : r.top; r.right = (x > r.right) ? x : r.right; r.bottom = (y > r.bottom) ? y : r.bottom; } r.sort(); return r; } }
drakeet/Lunei
ucrop/src/main/java/com/yalantis/ucrop/util/RectUtils.java
Java
gpl-3.0
2,322
/** * Copyright (C) 2011 Flamingo Project (http://www.cloudine.io). * <p/> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p/> * 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. * <p/> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opencloudengine.flamingo2.engine.hive; import org.apache.hive.service.cli.FetchOrientation; import org.apache.hive.service.cli.FetchType; import org.apache.hive.service.cli.HiveSQLException; import org.apache.hive.service.cli.thrift.TFetchOrientation; import org.apache.thrift.TException; import org.apache.thrift.transport.TTransport; import org.opencloudengine.flamingo2.model.hive.Schema; import java.sql.SQLException; import java.util.List; import java.util.Map; /** * Thrift API를 이용한 Hive Server 2 Client. */ public interface HiveThrift2Client { public void addHiveVariable(String key, String value); public void addHiveConfiguration(String key, String value); public String getUsername(); public String getPassword(); /** * Hive Thrift 세션을 오픈한다. * * @throws SQLException */ public void openSession() throws SQLException, TException; public void closeSession() throws HiveSQLException, TException; public TTransport getTransport(); public void connect() throws SQLException; public void execute(String query) throws SQLException, TException; public void executeAsync(String query) throws SQLException, TException; public void execute(String query, boolean async) throws SQLException, TException; public void execute(List<String> queries) throws SQLException, TException; public List<Schema> getResultSchema() throws SQLException, TException; public Map[] getResults() throws SQLException, TException; public String getStatus() throws SQLException, TException; public String getLog() throws HiveSQLException, TException; public Map[] getResults(FetchOrientation orientation, int maxRows, FetchType fetchType) throws Exception; public Map[] getResults(TFetchOrientation orientation, int maxRows, FetchType fetchType) throws Exception; public Map[] getResults(int maxRows) throws SQLException, TException; public String getError(); }
chiwanpark/flamingo2
flamingo2-web/src/main/java/org/opencloudengine/flamingo2/engine/hive/HiveThrift2Client.java
Java
gpl-3.0
2,736
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Question behaviour for the old adaptive mode. * * @package qbehaviour * @subpackage adaptive * @copyright 2009 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Question behaviour for adaptive mode. * * This is the old version of interactive mode. * * @copyright 2009 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class qbehaviour_adaptive extends question_behaviour_with_save { const IS_ARCHETYPAL = true; public function required_question_definition_type() { return 'question_automatically_gradable'; } public function get_expected_data() { if ($this->qa->get_state()->is_active()) { return array('submit' => PARAM_BOOL); } return parent::get_expected_data(); } public function get_state_string($showcorrectness) { $laststep = $this->qa->get_last_step(); if ($laststep->has_behaviour_var('_try')) { $state = question_state::graded_state_for_fraction( $laststep->get_behaviour_var('_rawfraction')); return $state->default_string(true); } $state = $this->qa->get_state(); if ($state == question_state::$todo) { return get_string('notcomplete', 'qbehaviour_adaptive'); } else { return parent::get_state_string($showcorrectness); } } public function get_right_answer_summary() { return $this->question->get_right_answer_summary(); } public function adjust_display_options(question_display_options $options) { parent::adjust_display_options($options); if (!$this->qa->get_state()->is_finished() && $this->qa->get_last_behaviour_var('_try')) { $options->feedback = true; } } public function process_action(question_attempt_pending_step $pendingstep) { if ($pendingstep->has_behaviour_var('comment')) { return $this->process_comment($pendingstep); } else if ($pendingstep->has_behaviour_var('finish')) { return $this->process_finish($pendingstep); } else if ($pendingstep->has_behaviour_var('submit')) { return $this->process_submit($pendingstep); } else { return $this->process_save($pendingstep); } } public function summarise_action(question_attempt_step $step) { if ($step->has_behaviour_var('comment')) { return $this->summarise_manual_comment($step); } else if ($step->has_behaviour_var('finish')) { return $this->summarise_finish($step); } else if ($step->has_behaviour_var('submit')) { return $this->summarise_submit($step); } else { return $this->summarise_save($step); } } public function process_save(question_attempt_pending_step $pendingstep) { $status = parent::process_save($pendingstep); $prevgrade = $this->qa->get_fraction(); if (!is_null($prevgrade)) { $pendingstep->set_fraction($prevgrade); } $pendingstep->set_state(question_state::$todo); return $status; } protected function adjusted_fraction($fraction, $prevtries) { return $fraction - $this->question->penalty * $prevtries; } public function process_submit(question_attempt_pending_step $pendingstep) { $status = $this->process_save($pendingstep); $response = $pendingstep->get_qt_data(); if (!$this->question->is_complete_response($response)) { $pendingstep->set_state(question_state::$invalid); if ($this->qa->get_state() != question_state::$invalid) { $status = question_attempt::KEEP; } return $status; } $prevstep = $this->qa->get_last_step_with_behaviour_var('_try'); $prevresponse = $prevstep->get_qt_data(); $prevtries = $this->qa->get_last_behaviour_var('_try', 0); $prevbest = $pendingstep->get_fraction(); if (is_null($prevbest)) { $prevbest = 0; } if ($this->question->is_same_response($response, $prevresponse)) { return question_attempt::DISCARD; } list($fraction, $state) = $this->question->grade_response($response); $pendingstep->set_fraction(max($prevbest, $this->adjusted_fraction($fraction, $prevtries))); if ($prevstep->get_state() == question_state::$complete) { $pendingstep->set_state(question_state::$complete); } else if ($state == question_state::$gradedright) { $pendingstep->set_state(question_state::$complete); } else { $pendingstep->set_state(question_state::$todo); } $pendingstep->set_behaviour_var('_try', $prevtries + 1); $pendingstep->set_behaviour_var('_rawfraction', $fraction); $pendingstep->set_new_response_summary($this->question->summarise_response($response)); return question_attempt::KEEP; } public function process_finish(question_attempt_pending_step $pendingstep) { if ($this->qa->get_state()->is_finished()) { return question_attempt::DISCARD; } $prevtries = $this->qa->get_last_behaviour_var('_try', 0); $prevbest = $this->qa->get_fraction(); if (is_null($prevbest)) { $prevbest = 0; } $laststep = $this->qa->get_last_step(); $response = $laststep->get_qt_data(); if (!$this->question->is_gradable_response($response)) { $state = question_state::$gaveup; $fraction = 0; } else { if ($laststep->has_behaviour_var('_try')) { // Last answer was graded, we want to regrade it. Otherwise the answer // has changed, and we are grading a new try. $prevtries -= 1; } list($fraction, $state) = $this->question->grade_response($response); $pendingstep->set_behaviour_var('_try', $prevtries + 1); $pendingstep->set_behaviour_var('_rawfraction', $fraction); $pendingstep->set_new_response_summary($this->question->summarise_response($response)); } $pendingstep->set_state($state); $pendingstep->set_fraction(max($prevbest, $this->adjusted_fraction($fraction, $prevtries))); return question_attempt::KEEP; } /** * Got the most recently graded step. This is mainly intended for use by the * renderer. * @return question_attempt_step the most recently graded step. */ public function get_graded_step() { $step = $this->qa->get_last_step_with_behaviour_var('_try'); if ($step->has_behaviour_var('_try')) { return $step; } else { return null; } } /** * Determine whether a question state represents an "improvable" result, * that is, whether the user can still improve their score. * * @param question_state $state the question state. * @return bool whether the state is improvable */ public function is_state_improvable(question_state $state) { return $state == question_state::$todo; } }
jenarroyo/moodle-repo
question/behaviour/adaptive/behaviour.php
PHP
gpl-3.0
8,058
#!/usr/bin/python import zmq import sys, os def main(): context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect(os.environ["QP_RUN_ADDRESS"]) def send(msg,expected): print "Send : ", msg socket.send(msg) reply = socket.recv() print "Reply : ", ':'+reply+':' if (reply != expected): print "Expected: ", ':'+expected+':' print "" assert (reply == expected) send("new_job ao_integrals tcp://130.120.229.139:12345 inproc://ao_integrals", "ok") send("new_job ao_integrals tcp://130.120.229.139:12345 inproc://ao_integrals", "error A job is already running") # send("connect","error Message not understood : connect") send("connect tcp","connect_reply ao_integrals 1 tcp://130.120.229.139:12345") send("connect inproc","connect_reply ao_integrals 2 inproc://ao_integrals") send("disconnect ao_integrals 3","error Queuing_system.ml:68:2 : disconnect ao_integrals 3") send("disconnect ao_integrals 2","disconnect_reply ao_integrals") send("connect inproc","connect_reply ao_integrals 3 inproc://ao_integrals") send("add_task ao_integrals triangle 3", "ok") send("add_task ao_integrals range 4 7", "ok") for i in range(8,11): send("add_task ao_integrals %d %d"%(i,i+10), "ok") send("get_task ao_integrals 3", "get_task_reply 10 10 20") send("get_task ao_integrals 3", "get_task_reply 9 9 19") send("get_task ao_integrals 3", "get_task_reply 8 8 18") send("task_done ao_integrals 3 10", "ok") send("task_done ao_integrals 3 9", "ok") send("task_done ao_integrals 3 8", "ok") send("del_task ao_integrals 10", "del_task_reply more 10") send("del_task ao_integrals 9", "del_task_reply more 9") send("del_task ao_integrals 8", "del_task_reply more 8") send("del_task ao_integrals 10", "error Task 10 is already deleted : del_task ao_integrals 10") send("get_task ao_integrals 1", "get_task_reply 7 4") send("get_task ao_integrals 3", "get_task_reply 6 5") send("get_task ao_integrals 1", "get_task_reply 5 6") send("get_task ao_integrals 3", "get_task_reply 4 7") send("get_task ao_integrals 3", "get_task_reply 3 1 3") send("get_task ao_integrals 1", "get_task_reply 2 2 3") send("get_task ao_integrals 1", "get_task_reply 1 3 3") send("task_done ao_integrals 1 1", "ok") send("task_done ao_integrals 1 2", "ok") send("task_done ao_integrals 3 3", "ok") send("task_done ao_integrals 3 4", "ok") send("task_done ao_integrals 1 5", "ok") send("task_done ao_integrals 1 6", "error Queuing_system.ml:81:30 : task_done ao_integrals 1 6") send("task_done ao_integrals 3 6", "ok") send("task_done ao_integrals 1 7", "ok") send("del_task ao_integrals 1", "del_task_reply more 1") send("del_task ao_integrals 2", "del_task_reply more 2") send("del_task ao_integrals 3", "del_task_reply more 3") send("del_task ao_integrals 4", "del_task_reply more 4") send("del_task ao_integrals 5", "del_task_reply more 5") send("del_task ao_integrals 6", "del_task_reply more 6") send("del_task ao_integrals 7", "del_task_reply done 7") send("end_job ao_integrals","ok") send("end_job ao_integrals","error No job is running") send("terminate","ok") if __name__ == '__main__': main()
TApplencourt/quantum_package
ocaml/tests/test_task_server.py
Python
gpl-3.0
3,246
# Copyright (C) 2005 Michael Urman # -*- coding: utf-8 -*- # # This program is free software; you can redistribute it and/or modify # it under the terms of version 2 of the GNU General Public License as # published by the Free Software Foundation. import warnings from mutagen._util import DictMixin from mutagen._compat import izip class FileType(DictMixin): """An abstract object wrapping tags and audio stream information. Attributes: * info -- :class:`StreamInfo` -- (length, bitrate, sample rate) * tags -- :class:`Tags` -- metadata tags, if any Each file format has different potential tags and stream information. FileTypes implement an interface very similar to Metadata; the dict interface, save, load, and delete calls on a FileType call the appropriate methods on its tag data. """ __module__ = "mutagen" info = None tags = None filename = None _mimes = ["application/octet-stream"] def __init__(self, filename=None, *args, **kwargs): if filename is None: warnings.warn("FileType constructor requires a filename", DeprecationWarning) else: self.load(filename, *args, **kwargs) def load(self, filename, *args, **kwargs): raise NotImplementedError def __getitem__(self, key): """Look up a metadata tag key. If the file has no tags at all, a KeyError is raised. """ if self.tags is None: raise KeyError(key) else: return self.tags[key] def __setitem__(self, key, value): """Set a metadata tag. If the file has no tags, an appropriate format is added (but not written until save is called). """ if self.tags is None: self.add_tags() self.tags[key] = value def __delitem__(self, key): """Delete a metadata tag key. If the file has no tags at all, a KeyError is raised. """ if self.tags is None: raise KeyError(key) else: del(self.tags[key]) def keys(self): """Return a list of keys in the metadata tag. If the file has no tags at all, an empty list is returned. """ if self.tags is None: return [] else: return self.tags.keys() def delete(self, filename=None): """Remove tags from a file. In cases where the tagging format is independent of the file type (for example `mutagen.ID3`) all traces of the tagging format will be removed. In cases where the tag is part of the file type, all tags and padding will be removed. The tags attribute will be cleared as well if there is one. Does nothing if the file has no tags. :raises mutagen.MutagenError: if deleting wasn't possible """ if self.tags is not None: if filename is None: filename = self.filename else: warnings.warn( "delete(filename=...) is deprecated, reload the file", DeprecationWarning) return self.tags.delete(filename) def save(self, filename=None, **kwargs): """Save metadata tags. :raises mutagen.MutagenError: if saving wasn't possible """ if filename is None: filename = self.filename else: warnings.warn( "save(filename=...) is deprecated, reload the file", DeprecationWarning) if self.tags is not None: return self.tags.save(filename, **kwargs) def pprint(self): """Print stream information and comment key=value pairs.""" stream = "%s (%s)" % (self.info.pprint(), self.mime[0]) try: tags = self.tags.pprint() except AttributeError: return stream else: return stream + ((tags and "\n" + tags) or "") def add_tags(self): """Adds new tags to the file. :raises mutagen.MutagenError: if tags already exist or adding is not possible. """ raise NotImplementedError @property def mime(self): """A list of mime types""" mimes = [] for Kind in type(self).__mro__: for mime in getattr(Kind, '_mimes', []): if mime not in mimes: mimes.append(mime) return mimes @staticmethod def score(filename, fileobj, header): raise NotImplementedError class StreamInfo(object): """Abstract stream information object. Provides attributes for length, bitrate, sample rate etc. See the implementations for details. """ __module__ = "mutagen" def pprint(self): """Print stream information""" raise NotImplementedError def File(filename, options=None, easy=False): """Guess the type of the file and try to open it. The file type is decided by several things, such as the first 128 bytes (which usually contains a file type identifier), the filename extension, and the presence of existing tags. If no appropriate type could be found, None is returned. :param options: Sequence of :class:`FileType` implementations, defaults to all included ones. :param easy: If the easy wrappers should be returnd if available. For example :class:`EasyMP3 <mp3.EasyMP3>` instead of :class:`MP3 <mp3.MP3>`. """ if options is None: from mutagen.asf import ASF from mutagen.apev2 import APEv2File from mutagen.flac import FLAC if easy: from mutagen.easyid3 import EasyID3FileType as ID3FileType else: from mutagen.id3 import ID3FileType if easy: from mutagen.mp3 import EasyMP3 as MP3 else: from mutagen.mp3 import MP3 from mutagen.oggflac import OggFLAC from mutagen.oggspeex import OggSpeex from mutagen.oggtheora import OggTheora from mutagen.oggvorbis import OggVorbis from mutagen.oggopus import OggOpus if easy: from mutagen.trueaudio import EasyTrueAudio as TrueAudio else: from mutagen.trueaudio import TrueAudio from mutagen.wavpack import WavPack if easy: from mutagen.easymp4 import EasyMP4 as MP4 else: from mutagen.mp4 import MP4 from mutagen.musepack import Musepack from mutagen.monkeysaudio import MonkeysAudio from mutagen.optimfrog import OptimFROG from mutagen.aiff import AIFF from mutagen.aac import AAC from mutagen.smf import SMF options = [MP3, TrueAudio, OggTheora, OggSpeex, OggVorbis, OggFLAC, FLAC, AIFF, APEv2File, MP4, ID3FileType, WavPack, Musepack, MonkeysAudio, OptimFROG, ASF, OggOpus, AAC, SMF] if not options: return None with open(filename, "rb") as fileobj: header = fileobj.read(128) # Sort by name after score. Otherwise import order affects # Kind sort order, which affects treatment of things with # equals scores. results = [(Kind.score(filename, fileobj, header), Kind.__name__) for Kind in options] results = list(izip(results, options)) results.sort() (score, name), Kind = results[-1] if score > 0: return Kind(filename) else: return None
bbsan2k/nzbToMedia
libs/mutagen/_file.py
Python
gpl-3.0
7,621
<?php /** * @file classes/site/VersionDAO.inc.php * * Copyright (c) 2013-2015 Simon Fraser University Library * Copyright (c) 2000-2015 John Willinsky * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING. * * @class VersionDAO * @ingroup site * @see Version * * @brief Operations for retrieving and modifying Version objects. */ import('lib.pkp.classes.site.Version'); class VersionDAO extends DAO { /** * Constructor */ function VersionDAO() { parent::DAO(); } /** * Retrieve the current version. * @param $productType string * @param $product string * @param $isPlugin boolean * @return Version */ function &getCurrentVersion($productType = null, $product = null, $isPlugin = false) { if(!$productType || !$product) { $application = PKPApplication::getApplication(); $productType = 'core'; $product = $application->getName(); } // We only have to check whether we are on a version previous // to the introduction of products when we're not looking for // a product version anyway. $returner = null; if (!$isPlugin) { $result =& $this->retrieve( 'SELECT * FROM versions WHERE current = 1' ); // If we only have one current version then this must be // the application version before the introduction of products // into the versions table. if ($result->RecordCount() == 1) { $oldVersion =& $this->_returnVersionFromRow($result->GetRowAssoc(false)); if (isset($oldVersion)) $returner =& $oldVersion; } $result->Close(); } if (!$returner) { // From here on we can assume that we have the product type // and product columns available in the versions table. $result =& $this->retrieve( 'SELECT * FROM versions WHERE current = 1 AND product_type = ? AND product = ?', array($productType, $product) ); $versionCount = $result->RecordCount(); if ($versionCount == 1) { $returner =& $this->_returnVersionFromRow($result->GetRowAssoc(false)); } elseif ($versionCount >1) { fatalError('More than one current version defined for the product type "'.$productType.'" and product "'.$product.'"!'); } } $result->Close(); unset($result); return $returner; } /** * Retrieve the complete version history, ordered by date (most recent first). * @param $productType string * @param $product string * @return array Versions */ function &getVersionHistory($productType = null, $product = null) { $versions = array(); if(!$productType || !$product) { $application = PKPApplication::getApplication(); $productType = 'core'; $product = $application->getName(); } $result =& $this->retrieve( 'SELECT * FROM versions WHERE product_type = ? AND product = ? ORDER BY date_installed DESC', array($productType, $product) ); while (!$result->EOF) { $versions[] = $this->_returnVersionFromRow($result->GetRowAssoc(false)); $result->MoveNext(); } $result->Close(); unset($result); return $versions; } /** * Internal function to return a Version object from a row. * @param $row array * @return Version */ function &_returnVersionFromRow(&$row) { $version = new Version( $row['major'], $row['minor'], $row['revision'], $row['build'], $this->datetimeFromDB($row['date_installed']), $row['current'], (isset($row['product_type']) ? $row['product_type'] : null), (isset($row['product']) ? $row['product'] : null), (isset($row['product_class_name']) ? $row['product_class_name'] : ''), (isset($row['lazy_load']) ? $row['lazy_load'] : 0), (isset($row['sitewide']) ? $row['sitewide'] : 0) ); HookRegistry::call('VersionDAO::_returnVersionFromRow', array(&$version, &$row)); return $version; } /** * Insert a new version. * @param $version Version * @param $isPlugin boolean */ function insertVersion(&$version, $isPlugin = false) { $isNewVersion = true; if ($version->getCurrent()) { // Find out whether the last installed version is the same as the // one to be inserted. $versionHistory =& $this->getVersionHistory($version->getProductType(), $version->getProduct()); $oldVersion =& array_shift($versionHistory); if ($oldVersion) { if ($version->compare($oldVersion) == 0) { // The old and the new current versions are the same so we need // to update the existing version entry. $isNewVersion = false; } elseif ($version->compare($oldVersion) == 1) { // Version to insert is newer than the existing version entry. // We reset existing entry. $this->update('UPDATE versions SET current = 0 WHERE current = 1 AND product = ?', $version->getProduct()); } else { // We do not support downgrades. fatalError('You are trying to downgrade the product "'.$version->getProduct().'" from version ['.$oldVersion->getVersionString().'] to version ['.$version->getVersionString().']. Downgrades are not supported.'); } } } if ($isNewVersion) { // We only change the install date when we insert new // version entries. if ($version->getDateInstalled() == null) { $version->setDateInstalled(Core::getCurrentDate()); } // Insert new version entry return $this->update( sprintf('INSERT INTO versions (major, minor, revision, build, date_installed, current, product_type, product, product_class_name, lazy_load, sitewide) VALUES (?, ?, ?, ?, %s, ?, ?, ?, ?, ?, ?)', $this->datetimeToDB($version->getDateInstalled())), array( (int) $version->getMajor(), (int) $version->getMinor(), (int) $version->getRevision(), (int) $version->getBuild(), (int) $version->getCurrent(), $version->getProductType(), $version->getProduct(), $version->getProductClassName(), ($version->getLazyLoad()?1:0), ($version->getSitewide()?1:0) ) ); } else { // Update existing version entry return $this->update( 'UPDATE versions SET current = ?, product_class_name = ?, lazy_load = ?, sitewide = ? WHERE product_type = ? AND product = ? AND major = ? AND minor = ? AND revision = ? AND build = ?', array( (int) $version->getCurrent(), $version->getProductClassName(), ($version->getLazyLoad()?1:0), ($version->getSitewide()?1:0), $version->getProductType(), $version->getProduct(), (int) $version->getMajor(), (int) $version->getMinor(), (int) $version->getRevision(), (int) $version->getBuild() ) ); } } /** * Retrieve all currently enabled products within the * given context as a two dimensional array with the * first key representing the product type, the second * key the product name and the value the product version. * * @param $context array the application context, only * products enabled in that context will be returned. * @return array */ function &getCurrentProducts($context) { if (count($context)) { // Construct the where clause for the plugin settings // context. $contextNames = array_keys($context); foreach ($contextNames as $contextLevel => $contextName) { // Transform from camel case to ..._... String::regexp_match_all('/[A-Z][a-z]*/', ucfirst($contextName), $words); $contextNames[$contextLevel] = strtolower_codesafe(implode('_', $words[0])); } $contextWhereClause = 'AND (('.implode('_id = ? AND ', $contextNames).'_id = ?) OR v.sitewide = 1)'; } else { $contextWhereClause = ''; } $result =& $this->retrieve( 'SELECT v.* FROM versions v LEFT JOIN plugin_settings ps ON lower(v.product_class_name) = ps.plugin_name AND ps.setting_name = \'enabled\' '.$contextWhereClause.' WHERE v.current = 1 AND (ps.setting_value = \'1\' OR v.lazy_load <> 1)', $context, false); $productArray = array(); while(!$result->EOF) { $row =& $result->getRowAssoc(false); $productArray[$row['product_type']][$row['product']] =& $this->_returnVersionFromRow($row); $result->MoveNext(); } $result->_close(); unset($result); return $productArray; } /** * Disable a product by setting its 'current' column to 0 * @param $productType string * @param $product string */ function disableVersion($productType, $product) { $this->update( 'UPDATE versions SET current = 0 WHERE current = 1 AND product_type = ? AND product = ?', array($productType, $product) ); } } ?>
jasonzou/journal.calaijol.org
tools/lib/pkp/pkp/classes/site/VersionDAO.inc.php
PHP
gpl-3.0
8,399
#include "CameraSpecifications.h" #include "Tools/FileFormats/Parse.h" CameraSpecifications::CameraSpecifications() { } CameraSpecifications::CameraSpecifications(const char* fileName) { LoadFromConfigFile(fileName); return; } CameraSpecifications::CameraSpecifications(const CameraSpecifications& sourceSpec) { this->resolutionWidth = sourceSpec.resolutionWidth; this->resolutionHeight = sourceSpec.resolutionHeight; this->fps = sourceSpec.fps; this->horizontalFov = sourceSpec.horizontalFov; this->verticalFov = sourceSpec.verticalFov; this->focalLength = sourceSpec.focalLength; return; } bool CameraSpecifications::LoadFromConfigFile(const char* fileName) { Parse file; bool fileParsed = file.ParseFile(fileName); if(fileParsed == false) return false; if(file.HasKey("Resolution Width")) { this->resolutionWidth = file.GetAsInt("Resolution Width"); } else { this->resolutionWidth = 0; } if(file.HasKey("Resolution Height")) { this->resolutionHeight = file.GetAsInt("Resolution Height"); } else { this->resolutionHeight = 0; } if(file.HasKey("Fps")) { this->fps = file.GetAsInt("Fps"); } else { this->fps = 0; } if(file.HasKey("Horizontal Fov")) { this->horizontalFov = file.GetAsDouble("Horizontal Fov"); } else { this->horizontalFov = 0.0; } if(file.HasKey("Vertical Fov")) { this->verticalFov = file.GetAsDouble("Vertical Fov"); } else { this->verticalFov = 0.0; } if(file.HasKey("Focal Length")) { this->focalLength = file.GetAsDouble("Focal Length"); } else { this->verticalFov = 0.0; } return fileParsed; }
shannonfenn/Multi-Platform-Vision-System
RPi/NUPlatform/NUCamera/CameraSpecifications.cpp
C++
gpl-3.0
1,813
package org.thoughtcrime.securesms; import android.animation.Animator; import android.annotation.TargetApi; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.support.annotation.AnimRes; import android.support.annotation.NonNull; import android.support.v4.view.animation.FastOutSlowInInterpolator; import android.support.v7.app.AlertDialog; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewAnimationUtils; import android.view.ViewGroup; import android.view.ViewTreeObserver.OnPreDrawListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import org.thoughtcrime.securesms.components.ContactFilterToolbar; import org.thoughtcrime.securesms.components.ContactFilterToolbar.OnFilterChangedListener; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.RecipientPreferenceDatabase.RecipientsPreferences; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.sms.MessageSender; import org.thoughtcrime.securesms.sms.OutgoingTextMessage; import org.thoughtcrime.securesms.util.ViewUtil; import org.thoughtcrime.securesms.util.concurrent.ListenableFuture.Listener; import org.thoughtcrime.securesms.util.task.ProgressDialogAsyncTask; import org.whispersystems.libaxolotl.util.guava.Optional; import java.util.concurrent.ExecutionException; public class InviteActivity extends PassphraseRequiredActionBarActivity implements ContactSelectionListFragment.OnContactSelectedListener { private MasterSecret masterSecret; private ContactSelectionListFragment contactsFragment; private EditText inviteText; private View shareButton; private View smsButton; private ViewGroup smsSendFrame; private Button smsSendButton; private Button smsCancelButton; private Animation slideInAnimation; private Animation slideOutAnimation; private ContactFilterToolbar contactFilter; private ImageView heart; @Override protected void onCreate(Bundle savedInstanceState, @NonNull MasterSecret masterSecret) { this.masterSecret = masterSecret; getIntent().putExtra(ContactSelectionListFragment.DISPLAY_MODE, ContactSelectionListFragment.DISPLAY_MODE_OTHER_ONLY); getIntent().putExtra(ContactSelectionListFragment.MULTI_SELECT, true); getIntent().putExtra(ContactSelectionListFragment.REFRESHABLE, false); super.onCreate(savedInstanceState, masterSecret); setContentView(R.layout.invite_activity); getSupportActionBar().setTitle(R.string.AndroidManifest__invite_friends); initializeResources(); } private void initializeResources() { slideInAnimation = loadAnimation(R.anim.slide_from_bottom); slideOutAnimation = loadAnimation(R.anim.slide_to_bottom); shareButton = ViewUtil.findById(this, R.id.share_button); smsButton = ViewUtil.findById(this, R.id.sms_button); inviteText = ViewUtil.findById(this, R.id.invite_text); smsSendFrame = ViewUtil.findById(this, R.id.sms_send_frame); smsSendButton = ViewUtil.findById(this, R.id.send_sms_button); smsCancelButton = ViewUtil.findById(this, R.id.cancel_sms_button); contactFilter = ViewUtil.findById(this, R.id.contact_filter); heart = ViewUtil.findById(this, R.id.heart); contactsFragment = (ContactSelectionListFragment)getSupportFragmentManager().findFragmentById(R.id.contact_selection_list_fragment); inviteText.setText(getString(R.string.InviteActivity_lets_switch_to_signal, "http://sgnl.link/1KpeYmF")); updateSmsButtonText(); if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { heart.getViewTreeObserver().addOnPreDrawListener(new HeartPreDrawListener()); } contactsFragment.setOnContactSelectedListener(this); shareButton.setOnClickListener(new ShareClickListener()); smsButton.setOnClickListener(new SmsClickListener()); smsCancelButton.setOnClickListener(new SmsCancelClickListener()); smsSendButton.setOnClickListener(new SmsSendClickListener()); contactFilter.setOnFilterChangedListener(new ContactFilterChangedListener()); } private Animation loadAnimation(@AnimRes int animResId) { final Animation animation = AnimationUtils.loadAnimation(this, animResId); animation.setInterpolator(new FastOutSlowInInterpolator()); return animation; } @Override public void onContactSelected(String number) { updateSmsButtonText(); } @Override public void onContactDeselected(String number) { updateSmsButtonText(); } private void sendSmsInvites() { new SendSmsInvitesAsyncTask(this, inviteText.getText().toString()) .execute(contactsFragment.getSelectedContacts() .toArray(new String[contactsFragment.getSelectedContacts().size()])); } private void updateSmsButtonText() { smsSendButton.setText(getResources().getQuantityString(R.plurals.InviteActivity_send_to_friends, contactsFragment.getSelectedContacts().size(), contactsFragment.getSelectedContacts().size())); smsSendButton.setEnabled(!contactsFragment.getSelectedContacts().isEmpty()); } @Override public void onBackPressed() { if (smsSendFrame.getVisibility() == View.VISIBLE) { cancelSmsSelection(); } else { super.onBackPressed(); } } private void cancelSmsSelection() { contactsFragment.reset(); updateSmsButtonText(); ViewUtil.animateOut(smsSendFrame, slideOutAnimation, View.GONE); } private class ShareClickListener implements OnClickListener { @Override public void onClick(View v) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, inviteText.getText().toString()); sendIntent.setType("text/plain"); if (sendIntent.resolveActivity(getPackageManager()) != null) { startActivity(Intent.createChooser(sendIntent, getString(R.string.InviteActivity_invite_to_signal))); } else { Toast.makeText(InviteActivity.this, R.string.InviteActivity_no_app_to_share_to, Toast.LENGTH_LONG).show(); } } } private class SmsClickListener implements OnClickListener { @Override public void onClick(View v) { ViewUtil.animateIn(smsSendFrame, slideInAnimation); } } private class SmsCancelClickListener implements OnClickListener { @Override public void onClick(View v) { cancelSmsSelection(); } } private class SmsSendClickListener implements OnClickListener { @Override public void onClick(View v) { new AlertDialog.Builder(InviteActivity.this) .setTitle(getResources().getQuantityString(R.plurals.InviteActivity_send_sms_invites, contactsFragment.getSelectedContacts().size(), contactsFragment.getSelectedContacts().size())) .setMessage(inviteText.getText().toString()) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { sendSmsInvites(); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } } private class ContactFilterChangedListener implements OnFilterChangedListener { @Override public void onFilterChanged(String filter) { contactsFragment.setQueryFilter(filter); } } private class HeartPreDrawListener implements OnPreDrawListener { @Override @TargetApi(VERSION_CODES.LOLLIPOP) public boolean onPreDraw() { heart.getViewTreeObserver().removeOnPreDrawListener(this); final int w = heart.getWidth(); final int h = heart.getHeight(); Animator reveal = ViewAnimationUtils.createCircularReveal(heart, w / 2, h, 0, (float)Math.sqrt(h*h + (w*w/4))); reveal.setInterpolator(new FastOutSlowInInterpolator()); reveal.setDuration(800); reveal.start(); return false; } } private class SendSmsInvitesAsyncTask extends ProgressDialogAsyncTask<String,Void,Void> { private final String message; public SendSmsInvitesAsyncTask(Context context, String message) { super(context, R.string.InviteActivity_sending, R.string.InviteActivity_sending); this.message = message; } @Override protected Void doInBackground(String... numbers) { final Context context = getContext(); if (context == null) return null; for (String number : numbers) { Recipients recipients = RecipientFactory.getRecipientsFromString(context, number, false); if (recipients.getPrimaryRecipient() != null) { Optional<RecipientsPreferences> preferences = DatabaseFactory.getRecipientPreferenceDatabase(context).getRecipientsPreferences(recipients.getIds()); int subscriptionId = preferences.isPresent() ? preferences.get().getDefaultSubscriptionId().or(-1) : -1; MessageSender.send(context, masterSecret, new OutgoingTextMessage(recipients, message, subscriptionId), -1L, true); if (recipients.getPrimaryRecipient().getContactUri() != null) { DatabaseFactory.getRecipientPreferenceDatabase(context).setSeenInviteReminder(recipients, true); } } } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); final Context context = getContext(); if (context == null) return; ViewUtil.animateOut(smsSendFrame, slideOutAnimation, View.GONE).addListener(new Listener<Boolean>() { @Override public void onSuccess(Boolean result) { contactsFragment.reset(); } @Override public void onFailure(ExecutionException e) {} }); Toast.makeText(context, R.string.InviteActivity_invitations_sent, Toast.LENGTH_LONG).show(); } } }
janimo/Signal-Android
src/org/thoughtcrime/securesms/InviteActivity.java
Java
gpl-3.0
11,026
package cn.nukkit.item; /** * author: MagicDroidX * Nukkit Project */ public class ItemBootsIron extends ItemArmor { public ItemBootsIron() { this(0, 1); } public ItemBootsIron(Integer meta) { this(meta, 1); } public ItemBootsIron(Integer meta, int count) { super(IRON_BOOTS, meta, count, "Iron Boots"); } @Override public int getTier() { return ItemArmor.TIER_IRON; } @Override public boolean isBoots() { return true; } }
Creeperface01/NukkitGT
src/main/java/cn/nukkit/item/ItemBootsIron.java
Java
gpl-3.0
520
/* Copyright (C) 1991-2001 and beyond by Bo Lindbergh and the "Aleph One" developers. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. This license is contained in the file "COPYING", which is included with this source code; it is available online at http://www.gnu.org/licenses/gpl.html Jan 25, 2002 (Br'fin (Jeremy Parsons)): Added TARGET_API_MAC_CARBON for Carbon.h Added accessors for datafields now opaque in Carbon */ #if defined(EXPLICIT_CARBON_HEADER) #include <Carbon/Carbon.h> /* #else #include <Resources.h> #include <Quickdraw.h> */ #endif #include "csfonts.h" static TextSpec null_text_spec; void GetNewTextSpec( TextSpec *spec, short resid, short item) { Handle res; int cnt; TextSpec *src; res=GetResource('finf',resid); if (!res) goto notfound; if (!*res) LoadResource(res); if (!*res) goto notfound; cnt=*(short *)*res; if (item<0 || item>=cnt) goto notfound; src=(TextSpec *)(*res+sizeof (short)); *spec=src[item]; return; notfound: *spec=null_text_spec; } void GetFont( TextSpec *spec) { GrafPtr port; GetPort(&port); spec->font=GetPortTextFont(port); spec->style=GetPortTextFace(port); spec->size=GetPortTextSize(port); } void SetFont( TextSpec *spec) { TextFont(spec->font); TextFace(spec->style); TextSize(spec->size); }
0x7F800000/Aleph-NONE
Source_Files/CSeries/csfonts.cpp
C++
gpl-3.0
1,735
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Version details * * @package block_course_overview * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $plugin->version = 2013012300; // The current plugin version (Date: YYYYMMDDXX) $plugin->requires = 2012112900; // Requires this Moodle version $plugin->component = 'block_course_overview'; // Full name of the plugin (used for diagnostics)
Burick/moodle
blocks/course_overview/version.php
PHP
gpl-3.0
1,193
//--- Aura Script ----------------------------------------------------------- // Math Advanced for 3 Dungeon //--- Description ----------------------------------------------------------- // Dungeon script for Math Advanced for 3. //--------------------------------------------------------------------------- [DungeonScript("dunbarton_math_high_3_dungeon")] public class MathAdv3DungeonScript : DungeonScript { public override void OnBoss(Dungeon dungeon) { dungeon.AddBoss(20019, 2); // Giant Skeleton Hellhound dungeon.AddBoss(11019, 2); // Bard Skeleton dungeon.PlayCutscene("bossroom_Math_BardSkeleton_GiantSkeletonHellhound"); } public override void OnBossDeath(Dungeon dungeon, Creature boss, Creature killer) { // Transform Bard Skeletons when their hounds were killed. if (boss.RaceId == 20019 && dungeon.RemainingBosses == 2) { dungeon.RemoveAllMonsters(); dungeon.AddBoss(11020, 2); // Metal Bard Skeleton dungeon.PlayCutscene("bossroom_Math_BardSkeleton_change"); } } public override void OnCleared(Dungeon dungeon) { var rnd = RandomProvider.Get(); var creators = dungeon.GetCreators(); for (int i = 0; i < creators.Count; ++i) { var member = creators[i]; var treasureChest = new TreasureChest(); if (i == 0) { var prefix = 0; switch (rnd.Next(3)) { case 0: prefix = 20711; break; // Famous case 1: prefix = 20712; break; // Ornamented case 2: prefix = 20402; break; // Strong } treasureChest.Add(Item.CreateEnchant(prefix)); } treasureChest.AddGold(rnd.Next(1980, 3630)); // Gold treasureChest.Add(GetRandomTreasureItem(rnd)); // Random item dungeon.AddChest(treasureChest); member.GiveItemWithEffect(Item.CreateKey(70028, "chest")); } } List<DropData> drops; public Item GetRandomTreasureItem(Random rnd) { if (drops == null) { drops = new List<DropData>(); drops.Add(new DropData(itemId: 62004, chance: 17, amountMin: 1, amountMax: 2)); // Magic Powder drops.Add(new DropData(itemId: 51102, chance: 17, amountMin: 1, amountMax: 2)); // Mana Herb drops.Add(new DropData(itemId: 51003, chance: 17, amountMin: 1, amountMax: 2)); // HP 50 Potion drops.Add(new DropData(itemId: 51008, chance: 17, amountMin: 1, amountMax: 2)); // MP 50 Potion drops.Add(new DropData(itemId: 51013, chance: 17, amountMin: 1, amountMax: 2)); // Stamina 50 Potion if (IsEnabled("MathAdvanced")) { drops.Add(new DropData(itemId: 63129, chance: 5, amount: 1, expires: 360)); // Math Adv. Fomor Pass for 2 drops.Add(new DropData(itemId: 63130, chance: 5, amount: 1, expires: 360)); // Math Adv. Fomor Pass for 3 drops.Add(new DropData(itemId: 63131, chance: 5, amount: 1, expires: 360)); // Math Adv. Fomor Pass } } return Item.GetRandomDrop(rnd, drops); } }
xCryptic/aura
system/scripts/dungeons/dunbarton_math_high_3_dungeon.cs
C#
gpl-3.0
2,813
# encoding: utf-8 module TableHelper # usage: 1) 標準 # table_to_index2 @items # usage: 2) ソートリンク # path_index = Site.request_path # table_to_index2 @items, 'sort_link_options' => { # 'disable_cols' => ['id','name'], # 'sort_keys' => @sort_keys, # 'path_index' => path_index, # 'other_query_string' => @qs # } # usage: 3) yaml 定義名を指定 # table_to_index2 @items, 'table_name' => 'governor_opinion_posts' # usage: 4) link_to_edit つき(同様に link_to_show, link_to_destroy) # table_to_index2 @items, 'link_to_edit' => 1 # usage: 4-2) 条件つき link_to_edit(同様に link_to_show, link_to_destroy) # table_to_index2 @items, 'link_to_edit' => Proc.new{|item| item.is_finished != 1 } # usage: 4-3) 飛び先・リンクキャプションの変更(同様に link_to_show, link_to_destroy) # table_to_index2 @items, :show_path=> 'gw_icons_path([[id]])', :link_to_show_caption => '展開' # usage: 5) td 内の出力を強制上書きするブロックを指定(条件つきで出力を抑止したり、スタイルを変更したり) # table_to_index2 @items, 'field_td_criteria' => {'ed_at' => Proc.new{|item| # ret = Gw.date_common(item.ed_at) # item.nil? || item.ed_at.nil? ? ret : (Time.now > item.ed_at && nz(item.is_finished,0) != 1 ? %Q(<font color="red">#{ret}</font>) : ret) # }} # usage: 6) caption を出力 # table_to_index2 @items, :caption=>'2009年の市場動向', :caption_class=>'caption_class_name' # usage: 7) 出力列・出力順を強制指定 # table_to_index2 @items, 'columns'=>[:id, :name] # 書式は table_field の影響を受ける # 出力列選択については、table_field に一貫させ、列出力順の指定用だと思ってもらった方がいいです # 出力列選択の優先順位は 1) 'columns'=> での指定 2) table_field の _cols: での指定 3) (:select 時)attributes_names 4) column_names # usage: 8) th/td にも class="#{field_name}" を出す(colgroup でどうにもならないスタイルを使いたい時用。white-space: nowrap;とか) # table_to_index2 @items, :force_td_class=>1 # table_to_index2 @items, :force_th_class=>1 # usage: 9) 縦に連続するtd内容が一致する場合、表示を省略する指定 # table_to_index2 @items, :simplize_same_in_column=>['name'], :same_str=>' 〃' # usage: 10) 詳細表示オプション(body フィールドを詳細表示します) # table_to_index2 @items, :detail=>:body, # :detail_nobr=>1, :detail_auto_link=>1 # usage: 11) 追加アクションボタン(例はあんまり実用的じゃなくて、文例バリエーション重視なのに注意) # table_to_index2 @items, :link_to => [{ # # 単純に出力 # :path => 'finish_gw_todo_path([[id]])', # :caption => '完了' # }, { # # ブロック条件つき出力 # :path => 'unfinish_gw_todo_path([[id]])', # :caption => '未完了', # :proc => Proc.new{|item| item.is_finished != 1 } # }, { # # ブロック条件つき出力(false時キャプションも指定) # :path => 'test_gw_todo_path([[id]])', # :caption => ['cap_true', 'cap_false'], # :proc => Proc.new{|item| item.is_finished != 1 } # } # ] # usage: 12) テーブル選択の応用(table_name: をキーにして直接読まず、table_name: action: をキーに yaml 定義を読みます) # table_name: action: が存在する場合、table_name: より table_name: action: が優先されます。 # デフォルトの action は table_to_index2 では index、table_to_show2 では show です。 # table_name: _common: が存在する場合、_common に {action} を merge したものが対象になります。 # table_name: _base: relation_name が存在する場合、そちらをベースに処理します。 # table_to_index2 @items, :action => 'show' # usage: 13) table 全体の html class の置き換え # table_to_index2 @items, :class => 'index print' def table_to_form(f, item, _options = {}) options = HashWithIndifferentAccess.new(_options) cr = "\n" require 'yaml' trans_hash_raw = Gw.load_yaml_files_cache action = nz(options[:action], 'form') if !options['table_name'].nil? hash_name = options['table_name'] else hash_name = item.class.table_name if item.is_a?(ActiveRecord::Base) end trans_hash = get_trans_hash(trans_hash_raw, hash_name, action) cols = !options['columns'].nil? ? options['columns'] : ( !trans_hash['_cols'].nil? ? trans_hash['_cols'].split(':') : (item.class.column_names.sort == item.attribute_names.sort ? item.class.column_names : item.attribute_names)) required_cols = !options['required_cols'].nil? ? options['required_cols'] : ( !trans_hash['_required_cols'].nil? ? trans_hash['_required_cols'].split(':') : []) trans_hash_h = trans_hash trans_hash = trans_hash.to_a textarea_fields = nz(options['_textarea_fields'], []) textarea_fields = textarea_fields.split(':') if !textarea_fields.is_a?(Array) styles = nz(options[:styles], {}) class_s = nz(options[:class], 'show') html = %Q(<table class="#{class_s}">#{cr}) if options[:disable_table_tag].nil? html += show_table_caption(options) cols.each do |col| trans = trans_hash.assoc(col.to_s)[1] rescue trans = col trans = nz(trans) split_trans = trans.split(':') field_str, value_str = if textarea_fields.index(col).nil? case split_trans[0] when 'd', 'D' _opt_dtp = {:errors=>item.errors, :time=>split_trans[0]=='d'} [split_trans[1], date_picker3(f, col, (item.send(col).nil? ? '' : item.send(col).strftime('%Y-%m-%d %H:%M')), _opt_dtp)] # rescue [split_trans[1], ''] when 'r' [split_trans[1], f.select(col, Gw.yaml_to_array_for_select(split_trans[2]), :selected=>@item.send(col))] else style = nz(styles[col], 'width:30em;') case trans when '' s = f.text_field(col, :style => style) rescue '' [col.humanize, s] when 'x' [nil, nil] else s = f.text_field(col, :style => style) rescue '' [h(trans), s] end end else [h(trans), form_text_area(f, col)] end prefix_s = (options[:prefix].blank? || options[:prefix][col].blank? ? '' : options[:prefix][col]) body_s = (!options['field_td_criteria'].nil? && !options['field_td_criteria'][col].nil? && options['field_td_criteria'][col].is_a?(Proc) ? options['field_td_criteria'][col].call(item) : value_str) suffix_s = (options[:suffix].blank? || options[:suffix][col].blank? ? '' : options[:suffix][col]) value_str = "#{prefix_s}#{body_s}#{suffix_s}" field_str += Gw.required if !required_cols.index(col).nil? html += show_field_tr(field_str, value_str) unless field_str.nil? end html += '</table>' if options[:disable_table_tag].nil? return html end def table_to_index2(items, _options = {}) options = HashWithIndifferentAccess.new(_options) cr = "\n" return %Q(<div class="notice">表示する項目はありません。</div>) if items.length == 0 require 'yaml' trans_hash_raw = Gw.load_yaml_files_cache action = nz(options[:action], 'index') unless options['table_name'].nil? hash_name = options['table_name'] else if items.is_a?(ActiveRecord::Base) hash_name = items.class.table_name elsif items.is_a?(WillPaginate::Collection) hash_name = items.last.class.table_name elsif items.is_a?(Array) hash_name = items.last.class.table_name if items.last.is_a?(ActiveRecord::Base) end end trans_hash = get_trans_hash(trans_hash_raw, hash_name, action) options['sort_link'] = nz(options['sort_link'], 1) sort_link_options = nz(options['sort_link_options'],{}) opt_link_to = parse_opt_link_to(options) tr_options = {} tr_options[:detail] = options[:detail] cols = !options['columns'].nil? ? options['columns'] : ( !trans_hash['_cols'].nil? ? trans_hash['_cols'].split(':') : (items.last.class.column_names.sort == items.last.attribute_names.sort ? items.last.class.column_names : items.last.attribute_names)) return %Q(<div class="notice">表示する項目はありません。</div>) if cols.length == 0 trans_hash = trans_hash.to_a if Gw.is_ar_array?(items) class_s = nz(options[:class], 'index') html = %Q(<table class="#{class_s}">#{cr}) if options[:disable_table_tag].nil? html += show_table_caption(options) buttons_colgroup = '' buttons_colgroup += %Q( <colgroup class="action"></colgroup>) + cr if opt_link_to['show'] # for show buttons_colgroup += %Q( <colgroup class="action"></colgroup>) + cr if opt_link_to['edit'] # for edit buttons_colgroup += %Q( <colgroup class="action"></colgroup>) + cr if opt_link_to['destroy'] # for edit nz(options[:link_to],[]).length.times do buttons_colgroup += %Q( <colgroup class="action"></colgroup>) + cr end html += buttons_colgroup if nf(options[:buttons_right]).blank? n_cols = 0 cols.each do |col| begin trans = trans_hash.assoc(col.to_s)[1] rescue trans = col end trans = nz(trans) split_trans = trans.split(':') case split_trans[0] when 'd','D', 'r', 'n', 'dbraw', 'img' html += %Q( <colgroup class="#{col}"></colgroup>) + cr n_cols += 1 else case trans when '' html += %Q( <colgroup class="#{col}"></colgroup>) + cr n_cols += 1 when 'x' else html += %Q( <colgroup class="#{col}"></colgroup>) + cr n_cols += 1 end end end html += buttons_colgroup if !nf(options[:buttons_right]).blank? if options[:disable_header].nil? c_s = class_str('action', options) html += ' <tr>' + cr buttons_header = '' buttons_header += '<th class="check"></th>' if !options['check'].blank? 'explore:show:edit:destroy'.split(':').each_with_index do |col, idx| buttons_header += " <th#{c_s}></th>" + cr if opt_link_to[col] end nz(options[:link_to],[]).each do |x| buttons_header += x && x[:header_caption] ? " <th#{c_s}>#{x[:header_caption]}</th>" + cr : " <th#{c_s}></th>" + cr end html += buttons_header if nf(options[:buttons_right]).blank? cols.each do |col| begin trans = trans_hash.assoc(col.to_s)[1] rescue trans = col end trans = nz(trans) split_trans = trans.split(':') sort_link_options[:force_td_class] = nz(options[:force_td_class], nil) sort_link_options[:force_th_class] = nz(options[:force_th_class], nil) sort_link_options[:col] = col case split_trans[0] when 'd','D', 'r', 'n', 'dbraw', 'img', /f\{(.+)\}/ html += show_field_th(split_trans[1], options['sort_link'], col, sort_link_options) when 't', /f\{(.+)\}/ html += show_field_th(split_trans[1], options['sort_link'], col, sort_link_options) else case trans when '' html += show_field_th(col.humanize, options['sort_link'], col, sort_link_options) when 'x' else html += show_field_th(h(trans), options['sort_link'], col, sort_link_options) end end end html += buttons_header if !nf(options[:buttons_right]).blank? html += ' </tr>' + cr end remember_last_td = {} items.each do |item| options[:rs] = options[:detail] options[:col] = 'action' tr_head_str = %Q(<tr#{cycle '', ' class="cycle"'}>) html += tr_head_str html += "<td>" + (check_box_tag "ids[]", "#{item.id}") + "</td>" if !options['check'].blank? part_buttons = '' 'explore:show:edit:destroy'.split(':').each_with_index do |col, idx| if !options['field_td_criteria'].nil? && !options['field_td_criteria'][col].nil? && options['field_td_criteria'][col].is_a?(Proc) value_str = options['field_td_criteria'][col].call(item) part_buttons += show_field_td(value_str, options) else opt_link_to_1 = case options["link_to_#{col}"] when Proc options["link_to_#{col}"].call(item) else opt_link_to[col] end opt_col_path = options["#{col}_path".to_sym] caption_s = nz(options["link_to_#{col}_caption".to_sym], '展開:詳細:編集:削除'.split(':')[idx] ) link_str = if opt_col_path opt_col_path_x = get_opt_col_path(opt_col_path, item) link_to(caption_s, eval(opt_col_path_x)) else if options[:image_action_button].blank? class_s, title_s, _caption_s = %q(nil), %q(nil), "'#{caption_s}'" else class_s, title_s, _caption_s = %Q('image #{col}'), %Q('#{caption_s}'), %q('&nbsp;') end col == 'explore' ? link_to_explore(item) : eval("link_to_#{col}(item.id, #{_caption_s}, :class=>#{class_s}, :title=>#{title_s})") end part_buttons += show_field_td(opt_link_to_1 ? link_str : '', options) + cr if opt_link_to[col] end end nz(options[:link_to],[]).each do |lt| opt_link_to_x = lt[:proc].is_a?(Proc) ? lt[:proc].call(item) : 1 if lt[:caption].is_a? Array caption_t = nz(lt[:caption][0]) caption_f = nz(lt[:caption][1]) caption_nil = nz(lt[:caption][2]) rescue caption_f else caption_t = lt[:caption] caption_f = '' caption_nil = '' end if opt_link_to_x.nil? link_to_path_x = caption_nil else caption_s = opt_link_to_x ? caption_t : caption_f if options[:image_action_button].blank? class_s, title_s, _caption_s = nil, nil, caption_s else action_s = !lt[:action].is_a?(Array) ? lt[:action] : opt_link_to_x ? lt[:action][0] : lt[:action][1] class_s, title_s, _caption_s = %Q(image #{action_s}), %Q(#{caption_s}), %q(&nbsp;) end _link_opt = {:class=>class_s, :title=>title_s} _link_opt[:target] = lt[:target] if lt[:target] _link_opt[:class] = lt[:class] if lt[:class] link_to_path_x = link_to _caption_s, eval(get_opt_col_path(lt[:path], item)), _link_opt end part_buttons += show_field_td(link_to_path_x, options) + cr end html += part_buttons if nf(options[:buttons_right]).blank? options.delete :rs cols.each do |col| options[:col] = col trans = trans_hash.assoc(col.to_s)[1] rescue col trans = nz(trans) field_str, value_str = get_fv(trans, item, col, trans_hash_raw, options) unless field_str.nil? if !options[:simplize_same_in_column].nil? && !options[:simplize_same_in_column].index(col).nil? if nz(remember_last_td[col]) == item.send(col) value_str = nz(options[:same_str],'&nbsp;〃') else remember_last_td[col] = item.send(col) end end html += show_field_td(value_str, options) end end html += part_buttons if !nf(options[:buttons_right]).blank? html += ' </tr>' + cr unless tr_options[:detail].nil? if tr_options[:detail].is_a?(Proc) detail_s = tr_options[:detail].call(item).to_s else col = tr_options[:detail].to_s trans = trans_hash.assoc(col)[1] rescue col trans = nz(trans) field_str, value_str = get_fv(trans, item, col, trans_hash_raw, options) detail_s = nz(value_str) end detail_s = br detail_s if options[:detail_nobr].nil? detail = %Q(#{tr_head_str}<td colspan="#{n_cols}">#{detail_s}</td></tr>) detail = auto_link detail unless options[:detail_auto_link].nil? html += detail end end html += '</table>' if options[:disable_table_tag].nil? return html else raise TypeError, "unknown input type(#{items.class.to_s})" end end def table_to_show(item, options = {}) cols = item.class.column_names html = '<table class="show">' + "\n" cols.each do |col| begin col_title = ::I18n.t("#{item.class.model_name.underscore}.#{col}", :scope => [:activerecord, :attributes], :raise => true) rescue col_title = col.humanize end html += ' <tr>' + "\n" html += " <th>#{col_title}</th>\n" html += " <td>#{hbr(item.send(col))}</td>\n" html += ' </tr>' + "\n" end html += '</table>' return html end def table_to_show2(item, _options = {}) options = HashWithIndifferentAccess.new(_options) cr = "\n" require 'yaml' trans_hash_raw = Gw.load_yaml_files_cache action = nz(options[:action], 'show') unless options['table_name'].nil? hash_name = options['table_name'] else hash_name = item.class.table_name if item.is_a?(ActiveRecord::Base) end trans_hash = get_trans_hash(trans_hash_raw, hash_name, action) cols = !options['columns'].nil? ? options['columns'] : ( !trans_hash['_cols'].nil? ? trans_hash['_cols'].split(':') : (item.class.column_names.sort == item.attribute_names.sort ? item.class.column_names : item.attribute_names)) trans_hash = trans_hash.to_a class_s = nz(options[:class], 'show') html = %Q(<table class="#{class_s}">#{cr}) if options[:disable_table_tag].nil? html += show_table_caption(options) cols.each do |col| trans = trans_hash.assoc(col.to_s)[1] rescue col trans = nz(trans) field_str, value_str = get_fv(trans, item, col, trans_hash_raw, options) show_options = {} show_options[:force_td_class] = nz(options[:force_td_class], nil) show_options[:force_th_class] = nz(options[:force_th_class], nil) show_options[:col] = col html += show_field_tr(field_str, value_str, show_options) unless field_str.nil? end html += '</table>' if options[:disable_table_tag].nil? return html end # 一覧表示用テーブル # @param klass モデルの型 # @param rows モデルインスタンスの配列 # @param opts オプション # :caption ... キャプション指定 # :operation ... 操作列を追加。内容は以下のシンボル配列で指定。 # :show ... true指定で「詳細」リンク # :edit ... true指定で「編集」リンク # :destroy ... true指定で「削除」リンク # :columns ... :content_columns指定で「id」および「***_id」を除外 # def table_to_index(klass, rows, opts = {}) require 'yaml' case opts[:columns] when :content_columns cols = klass.content_columns else cols = klass.columns end trans_hash_raw = Gw.load_yaml_files_cache unless opts['table_name'].nil? trans_hash = trans_hash_raw[options['table_name']].to_a else if klass.is_a? ActiveRecord::Base trans_hash = trans_hash_raw[klass.table_name].to_a end end require_op, op_show, op_edit, op_destroy = false require_op = true if opts[:operation] if require_op op_show = true if opts[:operation].detect(nil){|opt| opt == :show} op_edit = true if opts[:operation].detect(nil){|opt| opt == :edit} op_destroy = true if opts[:operation].detect(nil){|opt| opt == :destroy} end content_tag :table, :class => 'index' do caption = '' if opts[:caption] caption = content_tag(:caption, h(opts[:caption])) end theader = content_tag :tr do ths = [] if require_op ths << content_tag(:th, h("操作")) end cols.each do |col| begin trans = trans_hash.assoc(col.name)[1] rescue mdlname = klass.name.underscore colname = col.name trans = t("#{mdlname}.#{colname}", :scope => [:activerecord, :attributes]) end ths << content_tag(:th, "#{trans}") end ths.join end tbody = '' trs = [] if rows rows.each do |row| tr_opts = {} cls_cycle = cycle(nil, 'cycle') tr_opts[:class] = cls_cycle if cls_cycle trs << content_tag(:tr, tr_opts) do tds = [] if require_op tds << content_tag(:td) do ops = [] ops << link_to_show(row) if op_show ops << link_to_edit(row) if op_edit ops << link_to_destroy(row) if op_destroy ops.join(' ') end end cols.each do |col| cls_opts = {} cls_opts[:class] = col.type tds << content_tag(:td, cls_opts) do val = row[col.name.intern] s = '' case col.type when :integer s = val.to_s when :string s = h(val) when :text s = h(val) when :date s = localize(val) unless val.nil? when :datetime, :timestamp s = localize(val) unless val.nil? when :time s = localize(val, :format => "%H:%M:%S") unless val.nil? when :decimal s = val.to_s when :float s = val.to_s when :binary s = val.to_s when :boolean s = val.to_s end s end end tds.join end end end caption + theader + trs.join end end private def show_field_tr(f,v, options={}) c_s = class_str(options[:col], options) "<tr><th#{c_s}>#{f}</th><td#{c_s}>#{v}</td></tr>" end def show_field_th(v = '', sort_link_flag = true, sort_link_field_name = '', sort_link_options = {}) class_options = {} [:force_td_class, :col, :force_th_class].each do |k| class_options[k] = sort_link_options[k] sort_link_options.delete k end unless sort_link_options.nil? c_s = class_str(class_options[:col], class_options) if sort_link_flag return "<th#{c_s}>#{v}</th>" if sort_link_options.blank? || (!sort_link_options['disable_cols'].blank? && !sort_link_options['disable_cols'].index(sort_link_field_name).nil?) return %Q(<th#{c_s}>#{sort_link(v, sort_link_options["sort_keys"], sort_link_options["path_index"], sort_link_field_name, sort_link_options["other_query_string"])}</th>) else return "<th#{c_s}>#{v}</th>" end return "" end def show_field_td(v = '', _options={}) options = HashWithIndifferentAccess.new(_options) options.delete :force_th_class col_td_class_option = nz(options[:col_td_class], {}) _tdcls = col_td_class_option[options[:col]] ? col_td_class_option[options[:col]] : '' options[:add_class] = _tdcls unless _tdcls.blank? c_s = class_str(options[:col], options) rs_s = options[:rs].nil? ? '' : ' rowspan="2"' "<td#{c_s}#{rs_s}>#{v}</td>" end def class_str(s, options = {}) c_s = nil _class_name = ((!options[:force_td_class].nil? || !options[:force_th_class].nil?) && Gw.trim(s) != '') ? "#{s}" : '' if options[:add_class] _class_name = _class_name == '' ? "#{options[:add_class]}" : "#{_class_name} #{options[:add_class]}" end _class_name == '' ? c_s= '' : c_s = %Q( class="#{_class_name}") return c_s end def get_opt_col_path(opt_col_path, item) opt_col_path_x = opt_col_path.dup reps = opt_col_path_x.scan(/\[\[(.+?)\]\]/) reps.each do |rep| opt_col_path_x.sub!(/\[\[#{rep[0]}\]\]/, "#{item.send(rep[0])}") end opt_col_path_x end def show_table_caption(options = {}) html = '' class_str = options[:caption_class] ? %Q( class="#{options[:caption_class]}") : '' html = "<caption#{class_str}>#{options[:caption]}</caption>" if options[:caption] html end def parse_opt_link_to(options) opt_link_to = {} opt_link_to['show'] = _op4(options, 'link_to_show', 1) opt_link_to['edit'] = _op4(options, 'link_to_edit', nil) opt_link_to['destroy'] = _op4(options, 'link_to_destroy', nil) opt_link_to['explore'] = _op4(options, 'link_to_explore', nil) opt_link_to end def _op4(obj, key, if_undef) if_def_and_falsy = nil if_def_and_truthy = 1 raise TypeError if !obj.is_a?(Hash) return if_undef if !obj.key?(key) return obj[key] ? (obj[key].to_s == '0' ? if_def_and_falsy : if_def_and_truthy ) : if_def_and_falsy end def get_trans_hash(trans_hash_raw, hash_name, action) trans_hash = {} unless hash_name.blank? trans_hash_org = trans_hash_raw[hash_name] return {} if trans_hash_org.blank? unless trans_hash_org['_base'].nil? trans_hash_ind = trans_hash_org.dup trans_hash_org = trans_hash_raw[trans_hash_org['_base']] trans_hash_org = trans_hash_org.deep_merge(trans_hash_ind) end trans_hash_common = {} trans_hash_common = trans_hash_org['_common'] if !trans_hash_org.nil? && !trans_hash_org['_common'].nil? trans_hash_action = {} trans_hash_action = trans_hash_org['show'] if !trans_hash_org.nil? && action == 'form' && !trans_hash_org['show'].nil? trans_hash = trans_hash_org.dup.reject{|k,v| v.is_a?(Hash)}.deep_merge(trans_hash_common).deep_merge(trans_hash_action) trans_hash_action = trans_hash_org[action] if !trans_hash_org.nil? && !trans_hash_org[action].nil? trans_hash = trans_hash_org.dup.reject{|k,v| v.is_a?(Hash)}.deep_merge(trans_hash_common).deep_merge(trans_hash_action) end return trans_hash end def get_fv(trans, item, col, trans_hash_raw, options={}) options[:noh_cols] = Gw.as_array options[:noh_cols] split_trans = trans.split(':') field_str = split_trans[1] raw_data = item.send(col) rescue '' if item.methods.grep(col).blank? && item.attributes.keys.grep(col).blank? field_str = split_trans.length > 1 ? split_trans[1] : split_trans[0] value_str = raw_data else field_str, value_str = case split_trans[0] when /f\{(.+)\}/ [split_trans[1], Gw.int_format($1, item.send(col))] when 'd' d = item.send(col) d = d.to_datetime if d.is_a? String vd = d.nil? ? '' : d.strftime('%Y-%m-%d %H:%M') [split_trans[1], (d.blank? ? '' : vd)] when 'D' d = item.send(col) d = d.to_datetime if d.is_a? String vd = d.nil? ? '' : d.strftime('%Y-%m-%d') d.nil? ? '' : d.strftime('%Y-%m-%d') [split_trans[1], vd] when 'r' rc = trans_hash_raw[(split_trans[2])].to_a.assoc(item.send(col.to_s)) rc = trans_hash_raw[(split_trans[2])].to_a.assoc(item.send(col.to_s).to_i) if rc.nil? [split_trans[1], rc[1]] when 'n' item.send(col).to_s.strip != '' ? [nil, nil] : [split_trans[1], hbr(item.send(col))] when 'dbraw' if item.send(col).blank? [split_trans[1], ''] else quote = item.send(col).class.to_s == 'String' ? "'" : '' [split_trans[1], Gw::NameValue.get('dbraw', split_trans[2], split_trans[3], "#{split_trans[4]}=#{quote}#{item.send(col)}#{quote}")] end when 'img' c_s = options[:thumbnail].blank? ? '' : %Q( class="thumbnail") val = item.send(col).to_s.strip != '' ? %Q(<img src="#{hbr(item.send(col))}" alt=""#{c_s} />) : '' [split_trans[1], val] else detail_nobr_flg = "#{options[:detail]}" == "#{col}" && !options[:detail_nobr].nil? case trans when '' v = if options[:noh_cols].index(col).nil? detail_nobr_flg ? h(item.send(col)) : hbr(item.send(col)) else detail_nobr_flg ? item.send(col) : br(item.send(col)) end rescue '' [col.humanize, v] when 'x' [nil, nil] else v = if options[:noh_cols].index(col).nil? detail_nobr_flg ? h(item.send(col)) : hbr(item.send(col)) else detail_nobr_flg ? item.send(col) : br(item.send(col)) end rescue '' [h(trans), v] end end rescue [split_trans[1], raw_data] end value_str = options['field_td_criteria'][col].call(item) if !options['field_td_criteria'].nil? && !options['field_td_criteria'][col].nil? && options['field_td_criteria'][col].is_a?(Proc) return [field_str, value_str] end end module TableHelper_dust def table(items, options = {}) return 'empty' if items.size == 0 if options[:cols] cols = options[:cols].split(',') else cols = []; items[0].class.columns.each {|col| cols << col.name; } end attr = options[:class] ? ' class="' + options[:class] + '"' : '' html = "<table#{attr} border=1>\n" html += "<tr>\n" cols.each do |col|; html += " <th>#{col}</th>\n"; end html += "</tr>\n" items.size.times do |i| html += "<tr>\n" cols.each do |col|; html += " <td>#{items[i].send(col)}</td>\n"; end html += "</tr>\n" a = url_for(items[i]) html += a end html += "</table>" return html end def th(name, options = {}) return "<th#{to_css(options)}>#{to_link(name, options)}</th>" end def td(name, options = {}) return "<td#{to_css(options)}>#{to_link(name, options)}</td>" end def to_link(name, options = {}) return html_escape(name) unless options[:link] href = ' href="' + options[:link] + '"' return "<a#{href}>#{html_escape(name)}</a>" end def to_css(options = {}) css = '' css += ' width: ' + options[:size] + ';' if options[:size] case options[:type] when :num; css += ' text-align :right;' when :label; css += ' text-align :center;' when :text; css += ' text-align :left;' end if options[:type] return ' style="' + css.strip + '"' if css != '' end end
ryo-on/jorurigw
app/helpers/table_helper.rb
Ruby
gpl-3.0
30,825
<?php /* This file is part of iCE Hrm. iCE Hrm 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. iCE Hrm 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 iCE Hrm. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------ Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd] Developer: Thilina Hasantha (thilina.hasantha[at]gmail.com / facebook.com/thilinah) */ $moduleName = 'Modules'; define('MODULE_PATH',dirname(__FILE__)); include APP_BASE_PATH.'header.php'; include APP_BASE_PATH.'modulejslibs.inc.php'; ?><div class="span9"> <ul class="nav nav-tabs" id="modTab" style="margin-bottom:0px;margin-left:5px;border-bottom: none;"> <li class="active"><a id="tabModule" href="#tabPageModule">Modules</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="tabPageModule"> <div id="Module" class="reviewBlock" data-content="List" style="padding-left:5px;"> </div> <div id="ModuleForm" class="reviewBlock" data-content="Form" style="padding-left:5px;display:none;"> </div> </div> </div> </div> <script> var modJsList = new Array(); modJsList['moduleModule'] = new ModuleAdapter('Module','Module'); modJsList['moduleModule'].setShowAddNew(false); var modJs = modJsList['moduleModule']; </script> <?php include APP_BASE_PATH.'footer.php';?>
rhnvrm/icehrm
ext/admin/modules/index.php
PHP
gpl-3.0
1,794
namespace Pokemon { class uniqueId; } unsigned int qHash (const Pokemon::uniqueId &key); #include <cmath> #include <ctime> #include <cassert> #include <QtXml> #include <QSqlRecord> #include <PokemonInfo/pokemoninfo.h> #include <PokemonInfo/battlestructs.h> #include <PokemonInfo/movesetchecker.h> #include "tier.h" #include "tiermachine.h" #include "security.h" #include "server.h" #include "waitingobject.h" #include "loadinsertthread.h" QString MemberRating::toString() const { return name + "%" + QString::number(matches).rightJustified(5,'0',true) + "%" + QString::number(rating).rightJustified(5,'0',true) + "%" + QString::number(displayed_rating).rightJustified(5,'0',true) + "%" + QString::number(last_check_time).rightJustified(10,'0',true) + "%" + QString::number(bonus_time).rightJustified(10,' ',true) + "%" + QString::number(winCount).rightJustified(5,'0',true) + "\n"; } /* Explanations here: http://pokemon-online.eu/threads/how-to-change-the-rating-system-to-include-auto-decrease.3045/ and here: http://pokemon-online.eu/threads/new-rating-system.4189/ */ void MemberRating::changeRating(int opponent_rating, bool win) { QPair<int,int> change = pointChangeEstimate(opponent_rating); if (matches < 9999) { matches += 1; } if (win && winCount < 9999) { winCount += 1; } rating = rating + (win ? change.first : change.second); const int hpp = TierMachine::obj()->hours_per_period; const int msp = TierMachine::obj()->max_saved_periods; const int mpd = TierMachine::obj()->max_percent_decay; const int ppp = TierMachine::obj()->percent_per_period; bonus_time = bonus_time + (hpp* 3600); if (bonus_time > msp * hpp * 3600) bonus_time = msp * hpp * 3600; else if (bonus_time < 0 && ((-bonus_time)/(hpp*3600)*ppp) > mpd) { bonus_time = - ((mpd/ppp)+1) * hpp * 3600; } } void MemberRating::calculateDisplayedRating() { int cur_time = time(NULL); int diff = cur_time - last_check_time; last_check_time = cur_time; bonus_time = bonus_time - diff; const int hpp = TierMachine::obj()->hours_per_period; const int msp = TierMachine::obj()->max_saved_periods; if (bonus_time > msp * hpp * 3600) bonus_time = msp * hpp * 3600; /* We don't do a min check on the time, in order to let alts be 3 months old and get deleted.*/ if (bonus_time > 0) displayed_rating = rating; else { int percent = ((-bonus_time)/(hpp*3600))*TierMachine::obj()->percent_per_period; if (percent > TierMachine::obj()->max_percent_decay) { percent = TierMachine::obj()->max_percent_decay; } displayed_rating = 1000 + (rating-1000) * (100 - percent) / 100; } } QPair<int, int> MemberRating::pointChangeEstimate(int opponent_rating) { int n = matches; int kfactor; if (n <= 5) { static const int kfactors[] = {100, 90, 80, 70, 60, 50}; kfactor = kfactors[n]; } else { kfactor = 32; } double myesp = 1/(1+ pow(10., (float(opponent_rating)-rating)/400)); /* The +0.5 is a trick to round the value instead of flooring it */ return QPair<int,int>(int((1. - myesp)*kfactor+0.5),-int(myesp*kfactor +0.5)); } void Tier::changeName(const QString &name) { this->m_name = name; this->sql_table = "tier_" + ::slug(name); } void Tier::changeId(int id) { m_id = id; } int Tier::make_query_number(int type) { /* boss->version is only updated in the main thread, so this call is safe as make_query_number is only called in the main thread too */ return (type << 10) + id() + (boss->version << 16); } void Tier::loadSqlFromFile() { QSqlQuery query; query.setForwardOnly(true); query.exec(QString("select * from %1 limit 1").arg(sql_table)); int count = query.record().count(); /* That's an outdated database, before decaying ratings were introduced */ if (count == 4) { /* Outdated database */ QSqlDatabase::database().transaction(); query.exec(QString("alter table %1 add column displayed_rating int").arg(sql_table)); query.exec(QString("alter table %1 add column last_check_time int").arg(sql_table)); query.exec(QString("alter table %1 add column bonus_time int").arg(sql_table)); query.exec(QString("update %1 set bonus_time=0").arg(sql_table)); query.exec(QString("update %1 set displayed_rating=rating").arg(sql_table)); query.exec(QString("update %1 set last_check_time=%2").arg(sql_table).arg(QString::number(time(NULL)))); query.exec(QString("drop index tierrating_index")); query.exec(QString("drop index tiername_index")); query.exec(QString("create index %1_tiername_index on %1 (name)").arg(sql_table)); query.exec(QString("create index %1_tierrating_index on %1 (displayed_rating)").arg(sql_table)); QSqlDatabase::database().commit(); } else if (count == 7) { /* Outdated database, before winCount was introduced */ QSqlDatabase::database().transaction(); query.exec(QString("alter table %1 add column winCount int").arg(sql_table)); query.exec(QString("update %1 set winCount=0").arg(sql_table)); QSqlDatabase::database().commit(); } else if (!query.next() && count != 8) { if (SQLCreator::databaseType == SQLCreator::PostGreSQL) { /* The only way to have an auto increment field with PostGreSQL is to my knowledge using the serial type */ query.exec(QString("create table %1 (id serial, name varchar(20), rating int, displayed_rating int, last_check_time int, bonus_time int, matches int, winCount int, primary key(id))").arg(sql_table)); } else if (SQLCreator::databaseType == SQLCreator::MySQL){ query.exec(QString("create table %1 (id integer auto_increment, name varchar(20) unique, rating int, displayed_rating int, last_check_time int, bonus_time int, matches int, winCount int, primary key(id))").arg(sql_table)); } else if (SQLCreator::databaseType == SQLCreator::SQLite){ /* The only way to have an auto increment field with SQLite is to my knowledge having a 'integer primary key' field -- that exact quote */ query.exec(QString("create table if not exists %1 (id integer primary key autoincrement, name varchar(20) unique, rating int, displayed_rating int, last_check_time int, bonus_time int, matches int, winCount int)").arg(sql_table)); } else { throw QString("Using a not supported database"); } query.exec(QString("drop index %1_tiername_index").arg(sql_table)); query.exec(QString("drop index %1_tierrating_index").arg(sql_table)); query.exec(QString("create index %1_tiername_index on %1 (name)").arg(sql_table)); query.exec(QString("create index %1_tierrating_index on %1 (displayed_rating)").arg(sql_table)); QFile in("serverdb/tier_" + name() + ".txt"); if (!in.exists()) { return; } Server::print(QString("Importing old database for tier %1 to table %2").arg(name(), sql_table)); in.open(QIODevice::ReadOnly); QStringList members = QString::fromUtf8(in.readAll()).split('\n'); clock_t t = clock(); int current_time = time(NULL); if (members.size() > 0) { int count = members[0].split('%').size(); QSqlDatabase::database().transaction(); query.prepare(QString("insert into %1(name, rating, displayed_rating, last_check_time, bonus_time, matches, winCount) " "values (:name, :rating, :displayed_rating, :last_check_time, :bonus_time, :matches, :winCount)").arg(sql_table)); if (count == 3) { foreach(QString member, members) { QString m2 = member.toLower(); QStringList mmr = m2.split('%'); if (mmr.size() != 3) continue; query.bindValue(":name", mmr[0].toLower()); query.bindValue(":matches", mmr[1].toInt()); query.bindValue(":rating", mmr[2].toInt()); query.bindValue(":displayed_rating", mmr[2].toInt()); query.bindValue(":last_check_time", current_time); query.bindValue(":bonus_time", 0); query.exec(); } } else if (count == 6 || count == 7) { foreach(QString member, members) { QString m2 = member.toLower(); QStringList mmr = m2.split('%'); if (mmr.size() != 6 && mmr.size() != 7) continue; query.bindValue(":name", mmr[0].toLower()); query.bindValue(":matches", mmr[1].toInt()); query.bindValue(":rating", mmr[2].toInt()); query.bindValue(":displayed_rating", mmr[3].toInt()); query.bindValue(":last_check_time", mmr[4].toInt()); query.bindValue(":bonus_time", mmr[5].toInt()); if (mmr.size() == 7) query.bindValue(":winCount", mmr[6].toInt()); query.exec(); } } QSqlDatabase::database().commit(); } t = clock() - t; Server::print(QString::number(float(t)/CLOCKS_PER_SEC) + " secs"); Server::print(query.lastError().text()); } } void Tier::loadFromFile() { if (isSql()) { loadSqlFromFile(); return; } ratings.clear(); rankings = decltype(rankings)(); delete in; in = new QFile("serverdb/tier_" + name() + ".txt"); in->open(QIODevice::ReadOnly); QStringList members = QString::fromUtf8(in->readAll()).split('\n'); foreach(QString member, members) { QStringList mmr = member.split('%'); if (mmr.size() != 3 && mmr.size() < 7) continue; if (!SecurityManager::exist(mmr[0])) continue; MemberRating m; m.name = mmr[0]; m.matches = mmr[1].toInt(); m.rating = mmr[2].toInt(); if (mmr.size() == 3) { m.displayed_rating = m.rating; m.last_check_time = time(nullptr); m.bonus_time = 0; } else { m.displayed_rating = mmr[3].toInt(); m.last_check_time = mmr[4].toInt(); m.bonus_time = mmr[5].trimmed().toInt(); m.winCount = mmr[6].toInt(); } m.node = rankings.insert(m.displayed_rating, m.name); ratings[m.name] = m; } in->close(); in->open(QIODevice::WriteOnly); int pos = 0; for (auto it = ratings.begin(); it != ratings.end(); ++it) { it->second.filePos = pos; in->write(it->second.toString().toUtf8()); pos = in->pos(); } lastFilePos = pos; in->close(); in->open(QIODevice::ReadWrite); } int Tier::count() { if (isSql()) { if (m_count != -1 && time(NULL) - last_count_time < 3600) { return m_count; } else { QSqlQuery q; q.setForwardOnly(true); q.exec(QString("select count(*) from %1").arg(sql_table)); q.next(); last_count_time = time(NULL); return (m_count = q.value(0).toInt()); } } return ratings.size(); } void Tier::addBanParent(Tier *t) { if (!t) { parent = NULL; return; } Tier *it = t; while (it != NULL) { if (it == this) { parent = NULL; return; } it = it->parent; } /* No cyclic tree, so we can assign it */ parent = t; } QString Tier::bannedReason(const PokeBattle &p, bool child) const { QString errorList = ""; if (banPokes) { if (bannedPokes.contains(PokemonInfo::NonAestheticForme(p.num()))) { errorList += QString("Pokemon %1 is banned, ").arg(PokemonInfo::Name(p.num())); } if (bannedMoves.size() > 0) { for(int i = 0; i < 4; i++) { if(bannedMoves.contains(p.move(i).num())) { errorList += QString("Move %1 is banned, ").arg(MoveInfo::Name(p.move(i).num())); } } } if (bannedItems.contains(p.item())) { errorList += QString("Item %1 is banned, ").arg(ItemInfo::Name(p.item())); } if (bannedAbilities.contains(p.ability())) { errorList += QString("Ability %1 is banned, ").arg(AbilityInfo::Name(p.ability())); } } else { if (bannedPokes.size() > 0 && !bannedPokes.contains(PokemonInfo::NonAestheticForme(p.num()))) { errorList += QString("Pokemon %1 is banned, ").arg(PokemonInfo::Name(p.num())); } if (bannedMoves.size() > 0) { for(int i = 0; i < 4; i++) { if(p.move(i).num() != 0 && !bannedMoves.contains(p.move(i).num())) { errorList += QString("Move %1 is banned, ").arg(MoveInfo::Name(p.move(i).num())); } } } if (bannedItems.size() > 0 && p.item() != 0 && !bannedItems.contains(p.item())) { errorList += QString("Item %1 is banned, ").arg(ItemInfo::Name(p.item())); } if (bannedAbilities.size() > 0 && p.ability() != 0 && !bannedAbilities.contains(p.ability())) { errorList += QString("Ability %1 is banned, ").arg(AbilityInfo::Name(p.ability())); } } if (allowIllegal != "true" && p.illegal()) { errorList += QString("Pokemon %1 has an illegal set, ").arg(PokemonInfo::Name(p.num())); } if (parent) { errorList += parent->bannedReason(p, true); } if (errorList.length() >= 2 && !child) { QStringList errors = errorList.split(", ").toSet().toList(); //remove duplicates QMutableListIterator<QString> i(errors); while (i.hasNext()) { if (i.next().isEmpty()) { i.remove(); } } errorList = errors.join(", ") + "."; } return errorList; } bool Tier::isBanned(const PokeBattle &p) const { if (banPokes) { if (bannedPokes.contains(PokemonInfo::NonAestheticForme(p.num()))) return true; if (bannedMoves.size() > 0) { for (int i = 0; i < 4; i++) { if (bannedMoves.contains(p.move(i).num())) { return true; } } } if (bannedItems.contains(p.item())) { return true; } if (bannedAbilities.contains(p.ability())) { return true; } // if (bannedSets.contains(p.num())) { // foreach (BannedPoke b, bannedSets.values(p.num())) { // if (b.isBanned(p)) // return true; // } // } } else { /* The mode is the "restrict" mode, so instead we force the pokemons to have some characteristics */ if (bannedPokes.size() > 0 && !bannedPokes.contains(PokemonInfo::NonAestheticForme(p.num()))) return true; if (bannedMoves.size() > 0) { for (int i = 0; i < 4; i++) { if (p.move(i).num() != 0 && !bannedMoves.contains(p.move(i).num())) { return true; } } } if (bannedItems.size() > 0 && p.item() != 0 && !bannedItems.contains(p.item())) { return true; } if (bannedAbilities.size() > 0 && p.ability() != 0 && !bannedAbilities.contains(p.ability())) { return true; } // if (bannedSets.size() > 0 && bannedSets.contains(p.num())) { // foreach (BannedPoke b, bannedSets.values(p.num())) { // if (b.isForcedMatch(p)) // goto afterloop; // } // return true; // afterloop:; // } } if(minGen > 0) { if(!MoveSetChecker::isValid(p.num(), m_gen, p.move(0).num(), p.move(1).num(), p.move(2).num(), p.move(3).num(), p.ability(), p.gender(), p.level(), false, NULL, NULL, minGen)) { return true; } } if (allowIllegal != "true" && p.illegal()) { return true; } if (parent) { return parent->isBanned(p); } else { return false; } } bool Tier::isRestricted(const PokeBattle &p) const { if (restrictedPokes.contains(PokemonInfo::NonAestheticForme(p.num()))) return true; // if (restrictedSets.contains(p.num())) { // foreach (BannedPoke set, restrictedSets) { // if (set.isBanned(p)) // return true; // } // } return false; } bool Tier::exists(const QString &name) { if (!holder.isInMemory(name)) loadMemberInMemory(name); if (isSql()) { return holder.exists(name); } else { return ratings.find(name) != ratings.end(); } } int Tier::ranking(const QString &name) { if (!exists(name)) return -1; if (isSql()) { int r = rating(name); QSqlQuery q; q.setForwardOnly(true); q.prepare(QString("select count(*) from %1 where (displayed_rating>:r1 or (displayed_rating=:r2 and name<=:name))").arg(sql_table)); q.bindValue(":r1", r); q.bindValue(":r2", r); q.bindValue(":name", name.toLower()); q.exec(); if (q.next()) return q.value(0).toInt(); else return -1; } return ratings.at(name).node->ranking(); } bool Tier::isValid(const TeamBattle &t) const { if (!allowGen(t.gen)) { return false; } int restricted = 0; for (int i = 0; i< 6; i++) { if (t.poke(i).num() != 0) { if (isBanned(t.poke(i))) return false; if (isRestricted(t.poke(i))) { restricted += 1; if (restricted > maxRestrictedPokes) { return false; } } } } return true; } void Tier::fixTeam(TeamBattle &t) const { for (int i = 0; i < 6; i ++) { if (i >= numberOfPokemons) { t.poke(i).num() = 0; continue; } } } quint8 Tier::restricted(TeamBattle &t) const { int ret = 0; for (int i = 0; i < 6; i++) { if (isRestricted(t.poke(i))) { ret |= 1 << i; } } return ret; } void Tier::changeRating(const QString &player, int newRating) { assert(exists(player)); if (isSql()) { MemberRating m = member(player); m.rating = newRating; updateMember(m); return; } ratings[player].rating = newRating; updateMember(ratings[player]); } void Tier::changeRating(const QString &w, const QString &l) { /* Not really necessary, as pointChangeEstimate should always be called at the beginning of the battle, but meh maybe it's not a battle */ bool addw(false), addl(false); addw = !exists(w); addl = !exists(l); MemberRating win = addw ? MemberRating(w) : member(w); MemberRating los = addl ? MemberRating(l) : member(l); int oldwin = win.rating; win.changeRating(los.rating, true); los.changeRating(oldwin, false); win.calculateDisplayedRating(); los.calculateDisplayedRating(); updateMember(win, addw); updateMember(los, addl); } MemberRating Tier::member(const QString &name) { if (!holder.isInMemory(name)) loadMemberInMemory(name); if (isSql()) { return holder.member(name); } else { return ratings[name]; } } int Tier::rating(const QString &name) { if (!holder.isInMemory(name)) loadMemberInMemory(name); if (exists(name)) { if (isSql()) { return holder.member(name).displayed_rating; } else { return ratings[name].displayed_rating; } } else { return 1000; } } int Tier::inner_rating(const QString &name) { if (!holder.isInMemory(name)) loadMemberInMemory(name); if (exists(name)) { if (isSql()) { return holder.member(name).rating; } else { return ratings[name].rating; } } else { return 1000; } } int Tier::ratedBattles(const QString &name) { if (!holder.isInMemory(name)) loadMemberInMemory(name); if (exists(name)) { if (isSql()) { return holder.member(name).matches; } else { return ratings[name].matches; } } else { return 0; } } int Tier::ratedWins(const QString &name) { if (!holder.isInMemory(name)) loadMemberInMemory(name); if (exists(name)) { if (isSql()) { return holder.member(name).winCount; } else { return ratings[name].winCount; } } else { return 0; } } void Tier::loadMemberInMemory(const QString &name, QObject *o, const char *slot) { if (!o) { if (holder.isInMemory(name)) return; assert(isSql()); QSqlQuery q; q.setForwardOnly(true); processQuery(&q, name, GetInfoOnUser, nullptr); return; } holder.cleanCache(); WaitingObject *w = WaitingObjects::getObject(); /* It is important that this connect is done before the connect to freeObject(), because then the user at the signal's reception can use the object at will knowing it's not already used by another Player or w/e */ QObject::connect(w, SIGNAL(waitFinished()), o, slot); QObject::connect(w, SIGNAL(waitFinished()), WaitingObjects::getInstance(), SLOT(freeObject())); if (holder.isInMemory(name)) { w->setProperty("tier", this->name()); w->emitSignal(); } else { LoadInsertThread<MemberRating> *t = getThread(); t->pushQuery(name, w, make_query_number(GetInfoOnUser)); } } void Tier::fetchRankings(const QVariant &data, QObject *o, const char *slot) { WaitingObject *w = WaitingObjects::getObject(); /* It is important that this connect is done before the connect to freeObject(), because then the user at the signal's reception can use the object at will knowing it's not already used by another Player or w/e */ QObject::connect(w, SIGNAL(waitFinished()), o, slot); QObject::connect(w, SIGNAL(waitFinished()), WaitingObjects::getInstance(), SLOT(freeObject())); if (isSql()) { auto *t = getThread(); t->pushQuery(data, w, make_query_number(GetRankings)); } else { processQuery(0, data, GetRankings, w); w->emitSignal(); } } void Tier::fetchRanking(const QString &name, QObject *o, const char *slot) { WaitingObject *w = WaitingObjects::getObject(); /* It is important that this connect is done before the connect to freeObject(), because then the user at the signal's reception can use the object at will knowing it's not already used by another Player or w/e */ QObject::connect(w, SIGNAL(waitFinished()), o, slot); QObject::connect(w, SIGNAL(waitFinished()), WaitingObjects::getInstance(), SLOT(freeObject())); if (isSql()) { auto *t = getThread(); t->pushQuery(name.toLower(), w, make_query_number(GetRanking)); } else { processQuery(0, name, GetRanking, w); w->emitSignal(); } } void Tier::exportDatabase() const { if (!isSql()) { return; } QFile out(QString("tier_%1.txt").arg(name())); out.open(QIODevice::WriteOnly); QSqlQuery q; q.setForwardOnly(true); q.exec(QString("select name, matches, rating, displayed_rating, last_check_time, bonus_time, winCount from %1 order by name asc").arg(sql_table)); while (q.next()) { MemberRating m(q.value(0).toString(), q.value(1).toInt(), q.value(2).toInt(), q.value(3).toInt(), q.value(4).toInt(), q.value(5).toInt()); out.write(m.toString().toUtf8()); } Server::print(QString("Database of tier %1 exported!").arg(name())); } /* Precondition: name is in lowercase */ void Tier::processQuery(QSqlQuery *q, const QVariant &name, int type, WaitingObject *w) { if (w) { w->setProperty("tier", this->name()); } if (type == GetInfoOnUser) { assert(isSql());//Should never reach here otherwise q->prepare(QString("select matches, rating, displayed_rating, last_check_time, bonus_time, winCount from %1 where name=? limit 1").arg(sql_table)); q->addBindValue(name); q->exec(); if (!q->next()) { holder.addNonExistant(name.toString()); } else { MemberRating m(name.toString(), q->value(0).toInt(), q->value(1).toInt(), q->value(2).toInt(), q->value(3).toInt(), q->value(4).toInt()); holder.addMemberInMemory(m); } q->finish(); } else if (type == GetRankings) { int page; if (name.type() == QVariant::String) { int r = ranking(name.toString()); page = (r-1)/TierMachine::playersByPage + 1; } else { page = name.toInt(); } QVector<QPair<QString, int> > results; results.reserve(TierMachine::playersByPage); w->data["rankingpage"] = page; w->data["tier"] = this->name(); /* A page is 40 players */ int startingRank = (page-1) * TierMachine::playersByPage + 1; if (isSql()) { if (SQLCreator::databaseType == SQLCreator::PostGreSQL) q->prepare(QString("select name, displayed_rating from %1 order by displayed_rating desc, name asc offset :offset limit :limit").arg(sql_table)); else q->prepare(QString("select name, displayed_rating from %1 order by displayed_rating desc, name asc limit :offset, :limit").arg(sql_table)); q->bindValue(":offset", startingRank-1); q->bindValue(":limit", TierMachine::playersByPage); q->exec(); while (q->next()) { results.push_back(QPair<QString, int>(q->value(0).toString(), q->value(1).toInt())); } q->finish(); w->data["rankingdata"] = QVariant::fromValue(results); return; } RankingTree<QString>::iterator it = rankings.getByRanking(startingRank); int i = 0; while (i < TierMachine::playersByPage && it.p != NULL) { i++; results.push_back(QPair<QString, int> (it->data, it->key)); --it; } w->data["rankingdata"] = QVariant::fromValue(results); } else if (type == GetRanking) { w->setProperty("ranking", ranking(name.toString())); } } void Tier::insertMember(QSqlQuery *q, void *data, int update) { MemberRating &m = *(MemberRating*) data; if (isSql()) { if (update) q->prepare(QString("update %1 set matches=:matches, rating=:rating, displayed_rating=:displayed_rating, last_check_time=:last_check_time," "bonus_time=:bonus_time, winCount=:winCount where name=:name").arg(sql_table)); else q->prepare(QString("insert into %1(name, matches, rating, displayed_rating, last_check_time, bonus_time, winCount)" "values(:name, :matches, :rating, :displayed_rating, :last_check_time, :bonus_time, :winCount)").arg(sql_table)); q->bindValue(":name", m.name.toLower()); q->bindValue(":matches", m.matches); q->bindValue(":rating", m.rating); q->bindValue(":displayed_rating", m.displayed_rating); q->bindValue(":last_check_time", m.last_check_time); q->bindValue(":bonus_time", m.bonus_time); q->bindValue(":winCount", m.winCount); q->exec(); q->finish(); return; } if (update) { MemberRating oldm = ratings.at(m.name); m.filePos = oldm.filePos; m.node = oldm.node; in->seek(m.filePos); in->write(m.toString().toUtf8()); ratings[m.name] = m; ratings[m.name].node = rankings.changeKey(m.node.node(), m.rating); } else { m.filePos = lastFilePos; m.node = rankings.insert(m.rating, m.name); in->seek(lastFilePos); in->write(m.toString().toUtf8()); lastFilePos = in->pos(); ratings[m.name] = m; } } void Tier::updateMember(MemberRating &m, bool add) { holder.addMemberInMemory(m); if (add) { m_count += 1; } updateMemberInDatabase(m, add); } void Tier::updateMemberInDatabase(MemberRating &m, bool add) { if (isSql()) { boss->thread->pushMember(m, make_query_number(add ? InsertMember : UpdateMember)); } else { /* Can't thread writes since manipulating data directly */ insertMember(0, &m, add ? InsertMember : UpdateMember); } } void Tier::loadFromXml(const QDomElement &elem) { banPokes = elem.attribute("banMode", "ban") == "ban"; banParentS = elem.attribute("banParent"); parent = NULL; changeName(elem.attribute("name")); if (elem.hasAttribute("tableName") && elem.attribute("tableName").length() > 0) { sql_table = elem.attribute("tableName"); } m_gen = Pokemon::gen(elem.attribute("gen", QString::number(GenInfo::GenMax())).toInt(), elem.attribute("subgen",QString::number(GenInfo::NumberOfSubgens(elem.attribute("gen", QString::number(GenInfo::GenMax())).toInt())-1)).toInt()); if (m_gen.num == 0) { m_gen.subnum = 0; } minGen = elem.attribute("minGen", "-1").toInt(); allowIllegal = elem.attribute("allowIllegal", "false"); maxLevel = elem.attribute("maxLevel", "100").toInt(); numberOfPokemons = elem.attribute("numberOfPokemons", "6").toInt(); maxRestrictedPokes = elem.attribute("numberOfRestricted", "1").toInt(); mode = elem.attribute("mode", "0").toInt(); if (mode < ChallengeInfo::Singles || mode > ChallengeInfo::Rotation) { mode = ChallengeInfo::Singles; } displayOrder = elem.attribute("displayOrder", "0").toInt(); clauses = 0; // bannedSets.clear(); subgen="1" // restrictedSets.clear(); m_count = -1; last_count_time = 0; importBannedMoves(elem.attribute("moves")); importBannedZMoves(elem.attribute("zmoves")); importBannedItems(elem.attribute("items")); importBannedPokes(elem.attribute("pokemons")); importBannedAbilities(elem.attribute("abilities", "")); importRestrictedPokes(elem.attribute("restrictedPokemons")); QStringList clausesL = elem.attribute("clauses").split(","); foreach(QString clause, clausesL) { int index = ChallengeInfo::clause(clause.trimmed()); if (index > -1) { clauses |= 1 << index; } } // QDomElement pokElem = elem.firstChildElement("sets"); // if (!pokElem.isNull()) { // pokElem = elem.firstChildElement("pokemon"); // while (!pokElem.isNull()) { // BannedPoke p; // p.loadFromXml(elem); // bannedSets.insert(p.poke, p); // pokElem = elem.nextSiblingElement("pokemon"); // } // } // pokElem = elem.firstChildElement("restrictedSets"); // if (!pokElem.isNull()) { // pokElem = elem.firstChildElement("pokemon"); // while (!pokElem.isNull()) { // BannedPoke p; // p.loadFromXml(elem); // restrictedSets.insert(p.poke, p); // pokElem = elem.nextSiblingElement("pokemon"); // } // } } void Tier::resetLadder() { if (isSql()) { QSqlQuery q; q.setForwardOnly(true); q.exec(QString("delete from %1").arg(sql_table)); clearCache(); m_count = 0; return; } ratings.clear(); rankings = decltype(rankings)(); in->remove(); in->open(QIODevice::ReadWrite); } void Tier::clearCache() { holder.clearCache(); } QDomElement & Tier::toXml(QDomElement &dest) const { dest.setAttribute("name", name()); dest.setAttribute("tableName", sql_table); if (banPokes) { dest.setAttribute("banMode", "ban"); } else { dest.setAttribute("banMode", "restrict"); } dest.setAttribute("banParent", banParentS); dest.setAttribute("gen", m_gen.num); dest.setAttribute("subgen", m_gen.subnum); dest.setAttribute("minGen", minGen); dest.setAttribute("allowIllegal", allowIllegal); dest.setAttribute("maxLevel", maxLevel); dest.setAttribute("numberOfPokemons", numberOfPokemons); dest.setAttribute("numberOfRestricted", maxRestrictedPokes); dest.setAttribute("mode", mode); dest.setAttribute("displayOrder", displayOrder); dest.setAttribute("moves", getBannedMoves()); dest.setAttribute("zmoves", getBannedZMoves()); dest.setAttribute("items", getBannedItems()); dest.setAttribute("abilities", getBannedAbilities()); dest.setAttribute("pokemons", getBannedPokes()); dest.setAttribute("restrictedPokemons", getRestrictedPokes()); if (clauses != 0) { QStringList res; int clauses = this->clauses; int i = 0; while (clauses > 0) { if (clauses % 2 == 1) { res.append(ChallengeInfo::clause(i)); } clauses /= 2; i++; } res.sort(); dest.setAttribute("clauses", res.join(",")); } // QDomDocument doc; // if (bannedSets.size() > 0) { // QDomElement elem = doc.createElement("sets"); // foreach(BannedPoke b, bannedSets) { // QDomElement belem = doc.createElement("pokemon"); // b.toXml(belem); // elem.appendChild(belem); // } // dest.appendChild(elem); // } // if (restrictedSets.size() > 0) { // QDomElement elem = doc.createElement("restrictedSets"); // foreach(BannedPoke b, restrictedSets) { // QDomElement belem = doc.createElement("pokemon"); // b.toXml(belem); // elem.appendChild(belem); // } // dest.appendChild(elem); // } return dest; } QString Tier::getBannedPokes(bool parentNeeded) const { QStringList bannedPokesS; foreach(Pokemon::uniqueId poke, bannedPokes) { bannedPokesS.append(PokemonInfo::Name(poke)); } if (parent && parentNeeded) { bannedPokesS.append(parent->getBannedPokes(true)); } bannedPokesS.sort(); return bannedPokesS.join(", "); } QString Tier::getBannedItems() const { QStringList bannedItemsS; foreach(int item, bannedItems) { bannedItemsS.append(ItemInfo::Name(item)); } bannedItemsS.sort(); return bannedItemsS.join(", "); } QString Tier::getBannedMoves() const { QStringList bannedMovesS; foreach(int move, bannedMoves) { bannedMovesS.append(MoveInfo::Name(move)); } bannedMovesS.sort(); return bannedMovesS.join(", "); } QString Tier::getBannedZMoves(bool parentNeeded) const { QStringList bannedZMovesS; foreach(int zmove, bannedZMoves) { bannedZMovesS.append(MoveInfo::Name(zmove)); } if (parent && parentNeeded) { bannedZMovesS.append(parent->getBannedZMoves()); } bannedZMovesS.sort(); return bannedZMovesS.join(", "); } QString Tier::getBannedAbilities() const { QStringList bannedAbilitiesS; foreach(int move, bannedAbilities) { bannedAbilitiesS.append(AbilityInfo::Name(move)); } bannedAbilitiesS.sort(); return bannedAbilitiesS.join(", "); } QString Tier::getRestrictedPokes() const { QStringList restrictedPokesS; foreach(Pokemon::uniqueId poke, restrictedPokes) { restrictedPokesS.append(PokemonInfo::Name(poke)); } restrictedPokesS.sort(); return restrictedPokesS.join(", "); } int Tier::getGeneration() { return m_gen.num; } int Tier::getSubGeneration() { return m_gen.subnum; } void Tier::importBannedPokes(const QString &s) { bannedPokes.clear(); if (s.length() == 0) return; QStringList pokes = s.split(","); foreach (QString poke, pokes) { Pokemon::uniqueId num = PokemonInfo::Number(poke.trimmed()); if (num != 0) bannedPokes.insert(num); } } void Tier::importBannedItems(const QString &s) { bannedItems.clear(); if (s.length() == 0) return; QStringList items = s.split(","); foreach (QString item, items) { int num = ItemInfo::Number(item.trimmed()); if (num != Pokemon::NoPoke) bannedItems.insert(num); } } void Tier::importBannedMoves(const QString &s) { bannedMoves.clear(); if (s.length() == 0) return; QStringList moves = s.split(","); foreach(QString move, moves) { int num = MoveInfo::Number(move.trimmed()); if (num != 0) bannedMoves.insert(num); } } void Tier::importBannedZMoves(const QString &s) { bannedZMoves.clear(); if (s.length() == 0) return; QStringList zmoves = s.split(","); foreach(QString zmove, zmoves) { int num = MoveInfo::Number(zmove.trimmed()); if (num != 0) bannedZMoves.insert(num); } } void Tier::importBannedAbilities(const QString &s) { bannedAbilities.clear(); if (s.length() == 0) return; QStringList abilities = s.split(","); foreach(QString ability, abilities) { int num = AbilityInfo::Number(ability.trimmed()); if (num != 0) bannedAbilities.insert(num); } } void Tier::importRestrictedPokes(const QString &s) { restrictedPokes.clear(); if (s.length() == 0) return; QStringList rpokes = s.split(","); foreach (QString poke, rpokes) { Pokemon::uniqueId num = PokemonInfo::Number(poke.trimmed()); if (num != Pokemon::NoPoke) restrictedPokes.insert(num); } } //void BannedPoke::loadFromXml(const QDomElement &elem) { // poke = PokemonInfo::Number(elem.attribute("name")); // item = ItemInfo::Number("item"); // QStringList moves = elem.attribute("moves").split(","); // foreach (QString move, moves) { // int num = MoveInfo::Number(move.trimmed()); // if (num != 0) { // this->moves.insert(num); // } // } //} //QDomElement &BannedPoke::toXml(QDomElement &dest) const { // dest.setAttribute("name", PokemonInfo::Name(poke)); // if (item > 0) // dest.setAttribute("item", ItemInfo::Name(item)); // if (moves.size() > 0) { // QStringList res; // foreach(int move, moves) { // res.append(MoveInfo::Name(move)); // } // res.sort(); // dest.setAttribute("moves", res.join(",")); // } // return dest; //} //bool BannedPoke::isBanned(const PokeBattle &poke) const //{ // if (moves.size() == 0 && item == 0) // return true; // if (item != 0 && poke.item() == item) { // return true; // } // if (moves.size() > 0) { // for (int i = 0; i < 4; i++) { // if (moves.contains(poke.move(i).num())) { // return true; // } // } // } // return false; //} //bool BannedPoke::isForcedMatch(const PokeBattle &poke) const //{ // if (moves.size() == 0 && item == 0) // return true; // if (item != 0 && poke.item() != item) { // return false; // } // if (moves.size() > 0) { // for (int i = 0; i < 4; i++) { // if (!moves.contains(poke.move(i).num())) { // return false; // } // } // } // return true; //} Tier::Tier(TierMachine *boss, TierCategory *cat) : boss(boss), node(cat), holder(1000) { m_count = -1; last_count_time = 0; in = nullptr; banPokes = true; parent = nullptr; m_gen = Pokemon::gen(GenInfo::GenMax(), GenInfo::NumberOfSubgens(GenInfo::GenMax())-1); minGen = -1; allowIllegal = "false"; maxLevel = 100; numberOfPokemons = 6; maxRestrictedPokes = 1; mode = ChallengeInfo::Singles; displayOrder = 0; clauses = 0; } Tier::~Tier() { delete in, in = nullptr; qDebug() << "Deleting tier " << name(); } void Tier::kill() { node->kill(this); } QPair<int, int> Tier::pointChangeEstimate(const QString &player, const QString &foe) { MemberRating p = exists(player) ? member(player) : MemberRating(player); MemberRating f = exists(foe) ? member(foe) : MemberRating(foe); return p.pointChangeEstimate(f.rating); } LoadInsertThread<MemberRating> * Tier::getThread() { return boss->getThread(); } int Tier::getMode() const { return mode; } bool Tier::allowGen(Pokemon::gen gen) const { if (this->m_gen == 0) return true; return this->m_gen == gen; } int Tier::getClauses() const { return clauses; } int Tier::getMaxLevel() const { return maxLevel; } Tier *Tier::dataClone() const { Tier *ret = new Tier(); Tier &t = *ret; t.banPokes = banPokes; // t.bannedSets = bannedSets; // t.restrictedSets = restrictedSets; t.maxRestrictedPokes = maxRestrictedPokes; t.numberOfPokemons = numberOfPokemons; t.maxLevel = maxLevel; t.m_gen = m_gen; t.minGen = minGen; t.allowIllegal = allowIllegal; t.banParentS = banParentS; t.bannedItems = bannedItems; t.bannedMoves = bannedMoves; t.bannedZMoves = bannedZMoves; t.bannedAbilities = bannedAbilities; t.bannedPokes = bannedPokes; t.restrictedPokes = restrictedPokes; t.mode = mode; t.displayOrder = displayOrder; t.clauses = clauses; t.m_name = m_name; return ret; } void Tier::processDailyRun() { if (isSql()) { QSqlQuery query; query.setForwardOnly(true); Server::print(QString("Running Daily Run for tier %1").arg(name())); clock_t t = clock(); QSqlDatabase::database().transaction(); query.prepare(QString("select name, matches, rating, displayed_rating, last_check_time, bonus_time, winCount from %1").arg(sql_table)); query.exec(); QStringList names; while (query.next()) { QString name = query.value(0).toString(); names.push_back(name); if (!holder.isInMemory(name)) { MemberRating m(query.value(0).toString(), query.value(1).toInt(), query.value(2).toInt(), query.value(3).toInt(), query.value(4).toInt(), query.value(5).toInt()); m.calculateDisplayedRating(); holder.addMemberInMemory(m); } else { MemberRating m = holder.member(name); m.calculateDisplayedRating(); holder.addMemberInMemory(m); } } query.finish(); foreach(QString name, names) { MemberRating m = holder.member(name); insertMember(&query, &m, true); } /* After updating all, deleting the old members */ int min_bonus_time = -TierMachine::obj()->alt_expiration * 3600 * 24 * 30; query.prepare(QString("select name from %1 where bonus_time<%2").arg(sql_table).arg(min_bonus_time)); query.exec(); int count = 0; while (query.next()) { holder.removeMemberInMemory(query.value(0).toString()); count ++; } Server::print(QString("%1 alts removed from the ladder.").arg(count)); query.prepare(QString("delete from %1 where bonus_time<%2").arg(sql_table).arg(min_bonus_time)); query.exec(); holder.cleanCache(); QSqlDatabase::database().commit(); t = clock() - t; Server::print(QString::number(float(t)/CLOCKS_PER_SEC) + " secs"); Server::print(query.lastError().text()); return; } Server::print(QString("Running Daily Run for tier %1").arg(name())); clock_t t = clock(); int count = 0; int min_bonus_time = -TierMachine::obj()->alt_expiration * 3600 * 24 * 30; for (auto it = ratings.begin(); it != ratings.end(); ) { auto &m = it->second; if (m.bonus_time < min_bonus_time) { m.name[0] = ':'; in->seek(m.filePos); in->write(m.toString().toUtf8()); it = ratings.erase(it); } else { m.calculateDisplayedRating(); in->seek(m.filePos); in->write(m.toString().toUtf8()); ++it; } } Server::print(QString("%1 alts removed from the ladder.").arg(count)); /* Regenerate rankings & all */ loadFromFile(); t = clock() - t; Server::print(QString::number(float(t)/CLOCKS_PER_SEC) + " secs"); }
turbedi/pokemon-online
src/Server/tier.cpp
C++
gpl-3.0
45,228
<?php require_once("../../config.php"); require_once("lib.php"); $id = required_param('id', PARAM_INT); //moduleid $format = optional_param('format', CHOICE_PUBLISH_NAMES, PARAM_INT); $download = optional_param('download', '', PARAM_ALPHA); $action = optional_param('action', '', PARAM_ALPHA); $attemptids = optional_param('attemptid', array(), PARAM_INT); //get array of responses to delete. $url = new moodle_url('/mod/choice/report.php', array('id'=>$id)); if ($format !== CHOICE_PUBLISH_NAMES) { $url->param('format', $format); } if ($download !== '') { $url->param('download', $download); } if ($action !== '') { $url->param('action', $action); } $PAGE->set_url($url); if (! $cm = get_coursemodule_from_id('choice', $id)) { print_error("invalidcoursemodule"); } if (! $course = $DB->get_record("course", array("id" => $cm->course))) { print_error("coursemisconf"); } require_login($course->id, false, $cm); $context = get_context_instance(CONTEXT_MODULE, $cm->id); require_capability('mod/choice:readresponses', $context); if (!$choice = choice_get_choice($cm->instance)) { print_error('invalidcoursemodule'); } $strchoice = get_string("modulename", "choice"); $strchoices = get_string("modulenameplural", "choice"); $strresponses = get_string("responses", "choice"); add_to_log($course->id, "choice", "report", "report.php?id=$cm->id", "$choice->id",$cm->id); if (data_submitted() && $action == 'delete' && has_capability('mod/choice:deleteresponses',$context) && confirm_sesskey()) { choice_delete_responses($attemptids, $choice, $cm, $course); //delete responses. redirect("report.php?id=$cm->id"); } if (!$download) { $PAGE->navbar->add($strresponses); $PAGE->set_title(format_string($choice->name).": $strresponses"); $PAGE->set_heading($course->fullname); echo $OUTPUT->header(); /// Check to see if groups are being used in this choice $groupmode = groups_get_activity_groupmode($cm); if ($groupmode) { groups_get_activity_group($cm, true); groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/choice/report.php?id='.$id); } } else { $groupmode = groups_get_activity_groupmode($cm); } $users = choice_get_response_data($choice, $cm, $groupmode); if ($download == "ods" && has_capability('mod/choice:downloadresponses', $context)) { require_once("$CFG->libdir/odslib.class.php"); /// Calculate file name $filename = clean_filename("$course->shortname ".strip_tags(format_string($choice->name,true))).'.ods'; /// Creating a workbook $workbook = new MoodleODSWorkbook("-"); /// Send HTTP headers $workbook->send($filename); /// Creating the first worksheet $myxls =& $workbook->add_worksheet($strresponses); /// Print names of all the fields $myxls->write_string(0,0,get_string("lastname")); $myxls->write_string(0,1,get_string("firstname")); $myxls->write_string(0,2,get_string("idnumber")); $myxls->write_string(0,3,get_string("group")); $myxls->write_string(0,4,get_string("choice","choice")); /// generate the data for the body of the spreadsheet $i=0; $row=1; if ($users) { foreach ($users as $option => $userid) { $option_text = choice_get_option_text($choice, $option); foreach($userid as $user) { $myxls->write_string($row,0,$user->lastname); $myxls->write_string($row,1,$user->firstname); $studentid=(!empty($user->idnumber) ? $user->idnumber : " "); $myxls->write_string($row,2,$studentid); $ug2 = ''; if ($usergrps = groups_get_all_groups($course->id, $user->id)) { foreach ($usergrps as $ug) { $ug2 = $ug2. $ug->name; } } $myxls->write_string($row,3,$ug2); if (isset($option_text)) { $myxls->write_string($row,4,format_string($option_text,true)); } $row++; $pos=4; } } } /// Close the workbook $workbook->close(); exit; } //print spreadsheet if one is asked for: if ($download == "xls" && has_capability('mod/choice:downloadresponses', $context)) { require_once("$CFG->libdir/excellib.class.php"); /// Calculate file name $filename = clean_filename("$course->shortname ".strip_tags(format_string($choice->name,true))).'.xls'; /// Creating a workbook $workbook = new MoodleExcelWorkbook("-"); /// Send HTTP headers $workbook->send($filename); /// Creating the first worksheet $myxls =& $workbook->add_worksheet($strresponses); /// Print names of all the fields $myxls->write_string(0,0,get_string("lastname")); $myxls->write_string(0,1,get_string("firstname")); $myxls->write_string(0,2,get_string("idnumber")); $myxls->write_string(0,3,get_string("group")); $myxls->write_string(0,4,get_string("choice","choice")); /// generate the data for the body of the spreadsheet $i=0; $row=1; if ($users) { foreach ($users as $option => $userid) { $option_text = choice_get_option_text($choice, $option); foreach($userid as $user) { $myxls->write_string($row,0,$user->lastname); $myxls->write_string($row,1,$user->firstname); $studentid=(!empty($user->idnumber) ? $user->idnumber : " "); $myxls->write_string($row,2,$studentid); $ug2 = ''; if ($usergrps = groups_get_all_groups($course->id, $user->id)) { foreach ($usergrps as $ug) { $ug2 = $ug2. $ug->name; } } $myxls->write_string($row,3,$ug2); if (isset($option_text)) { $myxls->write_string($row,4,format_string($option_text,true)); } $row++; } } $pos=4; } /// Close the workbook $workbook->close(); exit; } // print text file if ($download == "txt" && has_capability('mod/choice:downloadresponses', $context)) { $filename = clean_filename("$course->shortname ".strip_tags(format_string($choice->name,true))).'.txt'; header("Content-Type: application/download\n"); header("Content-Disposition: attachment; filename=\"$filename\""); header("Expires: 0"); header("Cache-Control: must-revalidate,post-check=0,pre-check=0"); header("Pragma: public"); /// Print names of all the fields echo get_string("firstname")."\t".get_string("lastname") . "\t". get_string("idnumber") . "\t"; echo get_string("group"). "\t"; echo get_string("choice","choice"). "\n"; /// generate the data for the body of the spreadsheet $i=0; if ($users) { foreach ($users as $option => $userid) { $option_text = choice_get_option_text($choice, $option); foreach($userid as $user) { echo $user->lastname; echo "\t".$user->firstname; $studentid = " "; if (!empty($user->idnumber)) { $studentid = $user->idnumber; } echo "\t". $studentid."\t"; $ug2 = ''; if ($usergrps = groups_get_all_groups($course->id, $user->id)) { foreach ($usergrps as $ug) { $ug2 = $ug2. $ug->name; } } echo $ug2. "\t"; if (isset($option_text)) { echo format_string($option_text,true); } echo "\n"; } } } exit; } // Show those who haven't answered the question. if (!empty($choice->showunanswered)) { $choice->option[0] = get_string('notanswered', 'choice'); $choice->maxanswers[0] = 0; } $results = prepare_choice_show_results($choice, $course, $cm, $users); $renderer = $PAGE->get_renderer('mod_choice'); echo $renderer->display_result($results, has_capability('mod/choice:readresponses', $context)); //now give links for downloading spreadsheets. if (!empty($users) && has_capability('mod/choice:downloadresponses',$context)) { $downloadoptions = array(); $options = array(); $options["id"] = "$cm->id"; $options["download"] = "ods"; $button = $OUTPUT->single_button(new moodle_url("report.php", $options), get_string("downloadods")); $downloadoptions[] = html_writer::tag('li', $button, array('class'=>'reportoption')); $options["download"] = "xls"; $button = $OUTPUT->single_button(new moodle_url("report.php", $options), get_string("downloadexcel")); $downloadoptions[] = html_writer::tag('li', $button, array('class'=>'reportoption')); $options["download"] = "txt"; $button = $OUTPUT->single_button(new moodle_url("report.php", $options), get_string("downloadtext")); $downloadoptions[] = html_writer::tag('li', $button, array('class'=>'reportoption')); $downloadlist = html_writer::tag('ul', implode('', $downloadoptions)); $downloadlist .= html_writer::tag('div', '', array('class'=>'clearfloat')); echo html_writer::tag('div',$downloadlist, array('class'=>'downloadreport')); } echo $OUTPUT->footer();
hit-moodle/moodle
mod/choice/report.php
PHP
gpl-3.0
10,193
#!/usr/bin/env python ''' Applied Python Course, Class1, Exercise 2c Note, you will need to update the IP and COMMUNITY_STRING to use this script. ''' import snmp_helper COMMUNITY_STRING = '********' ip_addr = '10.10.10.10' pynet_rtr1 = (ip_addr, COMMUNITY_STRING, 7961) pynet_rtr2 = (ip_addr, COMMUNITY_STRING, 8061) SYS_DESCR = '1.3.6.1.2.1.1.1.0' SYS_NAME = '1.3.6.1.2.1.1.5.0' for a_device in (pynet_rtr1, pynet_rtr2): print "\n*********************" for the_oid in (SYS_NAME, SYS_DESCR): snmp_data = snmp_helper.snmp_get_oid(a_device, oid=the_oid) output = snmp_helper.snmp_extract(snmp_data) print output print "*********************" print
Collisio-Adolebitque/pfne-2017
pynet/appliedpy_ecourse/class1/ex2_simple_snmp.py
Python
gpl-3.0
694
/* * Copyright © 2014 - 2015 Alexander01998 and contributors * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package tk.wurst_client.mods; import tk.wurst_client.WurstClient; import tk.wurst_client.events.listeners.UpdateListener; import tk.wurst_client.mods.Mod.Category; import tk.wurst_client.mods.Mod.Info; @Info(category = Category.MISC, description = "Instantly turns off all enabled mods.\n" + "Be careful with this!", name = "Panic") public class PanicMod extends Mod implements UpdateListener { @Override public void onEnable() { WurstClient.INSTANCE.eventManager.add(UpdateListener.class, this); } @Override public void onUpdate() { for(Mod mod : WurstClient.INSTANCE.modManager.getAllMods()) if(mod.getCategory() != Category.HIDDEN && mod.isEnabled()) mod.setEnabled(false); } @Override public void onDisable() { WurstClient.INSTANCE.eventManager.remove(UpdateListener.class, this); } }
nerdtron123/Wurst-Client
Wurst Client/src/tk/wurst_client/mods/PanicMod.java
Java
mpl-2.0
1,120
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package subnet_test import ( "errors" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "github.com/juju/juju/cmd/juju/subnet" coretesting "github.com/juju/juju/testing" ) type SubnetCommandSuite struct { BaseSubnetSuite } var _ = gc.Suite(&SubnetCommandSuite{}) type SubnetCommandBaseSuite struct { coretesting.BaseSuite baseCmd *subnet.SubnetCommandBase } func (s *SubnetCommandBaseSuite) SetUpTest(c *gc.C) { s.BaseSuite.SetUpTest(c) s.baseCmd = &subnet.SubnetCommandBase{} } var _ = gc.Suite(&SubnetCommandBaseSuite{}) func (s *SubnetCommandBaseSuite) TestCheckNumArgs(c *gc.C) { threeErrors := []error{ errors.New("first"), errors.New("second"), errors.New("third"), } twoErrors := threeErrors[:2] oneError := threeErrors[:1] threeArgs := []string{"foo", "bar", "baz"} twoArgs := threeArgs[:2] oneArg := threeArgs[:1] for i, errs := range [][]error{nil, oneError, twoErrors, threeErrors} { for j, args := range [][]string{nil, oneArg, twoArgs, threeArgs} { expectErr := "" if i > j { // Returned error is always the one with index equal // to len(args), if it exists. expectErr = errs[j].Error() } c.Logf("test #%d: args: %v, errors: %v -> %q", i*4+j, args, errs, expectErr) err := s.baseCmd.CheckNumArgs(args, errs) if expectErr != "" { c.Check(err, gc.ErrorMatches, expectErr) } else { c.Check(err, jc.ErrorIsNil) } } } } func (s *SubnetCommandBaseSuite) TestValidateCIDR(c *gc.C) { // We only validate the subset of accepted CIDR formats which we // need to support. for i, test := range []struct { about string input string strict bool output string expectErr string }{{ about: "valid IPv4 CIDR, strict=false", input: "10.0.5.0/24", strict: false, output: "10.0.5.0/24", }, { about: "valid IPv4 CIDR, struct=true", input: "10.0.5.0/24", strict: true, output: "10.0.5.0/24", }, { about: "valid IPv6 CIDR, strict=false", input: "2001:db8::/32", strict: false, output: "2001:db8::/32", }, { about: "valid IPv6 CIDR, strict=true", input: "2001:db8::/32", strict: true, output: "2001:db8::/32", }, { about: "incorrectly specified IPv4 CIDR, strict=false", input: "192.168.10.20/16", strict: false, output: "192.168.0.0/16", }, { about: "incorrectly specified IPv4 CIDR, strict=true", input: "192.168.10.20/16", strict: true, expectErr: `"192.168.10.20/16" is not correctly specified, expected "192.168.0.0/16"`, }, { about: "incorrectly specified IPv6 CIDR, strict=false", input: "2001:db8::2/48", strict: false, output: "2001:db8::/48", }, { about: "incorrectly specified IPv6 CIDR, strict=true", input: "2001:db8::2/48", strict: true, expectErr: `"2001:db8::2/48" is not correctly specified, expected "2001:db8::/48"`, }, { about: "empty CIDR, strict=false", input: "", strict: false, expectErr: `"" is not a valid CIDR`, }, { about: "empty CIDR, strict=true", input: "", strict: true, expectErr: `"" is not a valid CIDR`, }} { c.Logf("test #%d: %s -> %s", i, test.about, test.expectErr) validated, err := s.baseCmd.ValidateCIDR(test.input, test.strict) if test.expectErr != "" { c.Check(err, gc.ErrorMatches, test.expectErr) } else { c.Check(err, jc.ErrorIsNil) } c.Check(validated, gc.Equals, test.output) } } func (s *SubnetCommandBaseSuite) TestValidateSpace(c *gc.C) { // We only validate a few more common invalid cases as // names.IsValidSpace() is separately and more extensively tested. for i, test := range []struct { about string input string expectErr string }{{ about: "valid space - only lowercase letters", input: "space", }, { about: "valid space - only numbers", input: "42", }, { about: "valid space - only lowercase letters and numbers", input: "over9000", }, { about: "valid space - with dashes", input: "my-new-99space", }, { about: "invalid space - with symbols", input: "%in$valid", expectErr: `"%in\$valid" is not a valid space name`, }, { about: "invalid space - with underscores", input: "42_foo", expectErr: `"42_foo" is not a valid space name`, }, { about: "invalid space - with uppercase letters", input: "Not-Good", expectErr: `"Not-Good" is not a valid space name`, }, { about: "empty space name", input: "", expectErr: `"" is not a valid space name`, }} { c.Logf("test #%d: %s -> %s", i, test.about, test.expectErr) validated, err := s.baseCmd.ValidateSpace(test.input) if test.expectErr != "" { c.Check(err, gc.ErrorMatches, test.expectErr) c.Check(validated.Id(), gc.Equals, "") } else { c.Check(err, jc.ErrorIsNil) // When the input is valid it should stay the same. c.Check(validated.Id(), gc.Equals, test.input) } } }
freyes/juju
cmd/juju/subnet/subnet_test.go
GO
agpl-3.0
4,970
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-occupancy', templateUrl: './occupancy.component.html', styleUrls: ['./occupancy.component.css'] }) export class OccupancyComponent implements OnInit { constructor() { } ngOnInit() { } }
feloy/simmage-ui
src/app/logistics/occupancy/occupancy.component.ts
TypeScript
agpl-3.0
281
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2015 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.coeus.sys.framework.rule; import org.apache.commons.collections4.keyvalue.DefaultMapEntry; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.coeus.sys.framework.validation.ErrorReporter; import org.kuali.coeus.sys.framework.validation.SoftError; import org.kuali.rice.kns.service.DictionaryValidationService; import org.kuali.rice.kns.service.KNSServiceLocator; import org.kuali.rice.krad.data.DataObjectService; import org.kuali.rice.krad.util.AuditError; import org.kuali.rice.krad.bo.DocumentHeader; import org.kuali.rice.krad.document.Document; import org.kuali.rice.krad.document.TransactionalDocument; import org.kuali.rice.krad.rules.DocumentRuleBase; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.KRADConstants; import org.kuali.rice.krad.util.KRADPropertyConstants; import java.util.AbstractMap.SimpleEntry; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Base implementation class for KRA document business rules * * @author $Author: gmcgrego $ * @version $Revision: 1.13 $ */ public abstract class KcTransactionalDocumentRuleBase extends DocumentRuleBase { public static final String DOCUMENT_ERROR_PATH = "document"; public static final boolean VALIDATION_REQUIRED = true; public static final boolean CHOMP_LAST_LETTER_S_FROM_COLLECTION_NAME = false; private ErrorReporter errorReporter; private DataObjectService dataObjectService; private BusinessObjectService businessObjectService; private DictionaryValidationService knsDictionaryValidationService; /** * Delegates to {@link ErrorReporter#reportError(String, String, String...) ErrorReporter#reportError(String, String, String...)} * to keep api compatibility. * @see ErrorReporter#reportError(String, String, String...) */ protected void reportError(String propertyName, String errorKey, String... errorParams) { this.getErrorReporter().reportError(propertyName, errorKey, errorParams); } /** * Delegates to {@link ErrorReporter#reportError(String, String, String...) ErrorReporter#reportError(String, String, String...)} * to keep api compatibility. * @see ErrorReporter#reportError(String, String, String...) */ protected void reportWarning(String propertyName, String errorKey, String... errorParams) { this.getErrorReporter().reportWarning(propertyName, errorKey, errorParams); } /** * Delegates to {@link ErrorReporter#reportAuditError(AuditError, String, String, String) ErrorReporter#reportAuditError(AuditError, String, String, String)} * to keep api compatibility. * @see ErrorReporter#reportAuditError(AuditError, String, String, String) */ protected void addAuditError(AuditError error, String errorKey, String clusterLabel, String clusterCategory) { this.getErrorReporter().reportAuditError(error, errorKey, clusterLabel, clusterCategory); } /** * Delegates to {@link ErrorReporter#reportSoftError(String, String, String...) ErrorReporter#reportSoftError(String, String, String...)} * to keep api compatibility. * @see ErrorReporter#reportSoftError(String, String, String...) */ protected void reportSoftError(String propertyName, String errorKey, String... errorParams) { this.getErrorReporter().reportSoftError(propertyName, errorKey, errorParams); } /** * Delegates to {@link ErrorReporter#getSoftErrors() ErrorReporter#getSoftErrors()} * to keep api compatibility. * @see ErrorReporter#getSoftErrors() */ public Map<String, Collection<SoftError>> getSoftErrors() { return this.getErrorReporter().getSoftErrors(); } /** * Convenience method for creating a <code>{@link SimpleEntry}</code> out of a key/value pair * * @param key * @param value * @return SimpleImmutableEntry */ protected Entry<String, String> keyValue(String key, Object value) { @SuppressWarnings("unchecked") //Commons Collections does not support Generics final Entry<String, String> entry = (value == null) ? new DefaultMapEntry(key, "") : new DefaultMapEntry(key, value.toString()); return entry; } /** * The opposite of <code>{@link #isValid(Class, java.util.Map.Entry[])}</code> * * @param boClass the class of the business object to validate * @param entries varargs array of <code>{@link SimpleEntry}</code> key/value pair instances * @return true if invalid; false if valid * @see #isValid(Class, java.util.Map.Entry[]) */ protected boolean isInvalid(Class<?> boClass, Entry<String, String> ... entries) { return !isValid(boClass, entries); } /** * Is the given code valid? Query the database for a matching code * If found, it is valid; otherwise it is invalid. * * @param boClass the class of the business object to validate * @param entries varargs array of <code>{@link SimpleEntry}</code> key/value pair instances * @return true if invalid; false if valid * @see #isValid(Class, java.util.Map.Entry[]) */ protected boolean isValid(Class<?> boClass, Entry<String,String> ... entries) { boolean retval = false; if (entries != null && entries.length > 0) { Map<String,String> fieldValues = new HashMap<String,String>(); for (Entry<String,String> entry : entries) { fieldValues.put(entry.getKey(), entry.getValue()); } if (getBusinessObjectService().countMatching(boClass, fieldValues) > 0) { retval = true; } } return retval; } /* * Overriding the rice method since we need to use the knsDD validation service instead of the KRAd one. * We use KNS DD components like validation patterns that the Krad validator does not even check * because KRAD only checks for constraints and all validation patterns are constraints in KRAD. */ @Override public boolean processSaveDocument(Document document) { boolean isValid = true; isValid = isDocumentOverviewValid(document); GlobalVariables.getMessageMap().addToErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME); // Using the KNS DD validation service here instead of KRAD getKnsDictionaryValidationService().validateDocumentAndUpdatableReferencesRecursively(document, getMaxDictionaryValidationDepth(), VALIDATION_REQUIRED, CHOMP_LAST_LETTER_S_FROM_COLLECTION_NAME); // leaving this in because there is no DocumentDictionaryService in KNS to check for existence. This might just be //handled by the call above. getDictionaryValidationService().validateDefaultExistenceChecksForTransDoc((TransactionalDocument) document); GlobalVariables.getMessageMap().removeFromErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME); isValid &= GlobalVariables.getMessageMap().hasNoErrors(); isValid &= processCustomSaveDocumentBusinessRules(document); return isValid; } /* * Overriding the rice method and removing the docHeader description check here since * it is already being done in the kns DD validation step above to avoid dual error messages. */ @Override public boolean isDocumentOverviewValid(Document document) { // add in the documentHeader path GlobalVariables.getMessageMap().addToErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME); GlobalVariables.getMessageMap().addToErrorPath(KRADConstants.DOCUMENT_HEADER_PROPERTY_NAME); validateSensitiveDataValue(KRADPropertyConstants.EXPLANATION, document.getDocumentHeader().getExplanation(), getDataDictionaryService().getAttributeLabel(DocumentHeader.class, KRADPropertyConstants.EXPLANATION)); validateSensitiveDataValue(KRADPropertyConstants.DOCUMENT_DESCRIPTION, document.getDocumentHeader().getDocumentDescription(), getDataDictionaryService().getAttributeLabel( DocumentHeader.class, KRADPropertyConstants.DOCUMENT_DESCRIPTION)); // drop the error path keys off now GlobalVariables.getMessageMap().removeFromErrorPath(KRADConstants.DOCUMENT_HEADER_PROPERTY_NAME); GlobalVariables.getMessageMap().removeFromErrorPath(KRADConstants.DOCUMENT_PROPERTY_NAME); return GlobalVariables.getMessageMap().hasNoErrors(); } protected final BusinessObjectService getBusinessObjectService() { if (businessObjectService == null) { businessObjectService = KcServiceLocator.getService(BusinessObjectService.class); } return businessObjectService; } public void setBusinessObjectService(BusinessObjectService businessObjectService){ this.businessObjectService = businessObjectService; } public ErrorReporter getErrorReporter() { if (this.errorReporter == null) { this.errorReporter = KcServiceLocator.getService(ErrorReporter.class); } return this.errorReporter; } public void setErrorReporter(ErrorReporter errorReporter) { this.errorReporter = errorReporter; } protected DictionaryValidationService getKnsDictionaryValidationService() { if (this.knsDictionaryValidationService == null) { this.knsDictionaryValidationService = KNSServiceLocator.getKNSDictionaryValidationService(); } return this.knsDictionaryValidationService; } public void setKnsDictionaryValidationService(DictionaryValidationService knsDictionaryValidationService) { this.knsDictionaryValidationService = knsDictionaryValidationService; } protected DataObjectService getDataObjectService() { if (dataObjectService == null) { dataObjectService = KcServiceLocator.getService(DataObjectService.class); } return dataObjectService; } protected void setDataObjectService(DataObjectService dataObjectService) { this.dataObjectService = dataObjectService; } }
sanjupolus/kc-coeus-1508.3
coeus-impl/src/main/java/org/kuali/coeus/sys/framework/rule/KcTransactionalDocumentRuleBase.java
Java
agpl-3.0
11,137
require 'rails_helper' describe User do describe "#debate_votes" do let(:user) { create(:user) } it "returns {} if no debate" do expect(user.debate_votes([])).to eq({}) end it "returns a hash of debates ids and votes" do debate1 = create(:debate) debate2 = create(:debate) debate3 = create(:debate) create(:vote, voter: user, votable: debate1, vote_flag: true) create(:vote, voter: user, votable: debate3, vote_flag: false) voted = user.debate_votes([debate1, debate2, debate3]) expect(voted[debate1.id]).to eq(true) expect(voted[debate2.id]).to eq(nil) expect(voted[debate3.id]).to eq(false) end end describe "#comment_flags" do let(:user) { create(:user) } it "returns {} if no comment" do expect(user.comment_flags([])).to eq({}) end it "returns a hash of flaggable_ids with 'true' if they were flagged by the user" do comment1 = create(:comment) comment2 = create(:comment) comment3 = create(:comment) Flag.flag(user, comment1) Flag.flag(user, comment3) flagged = user.comment_flags([comment1, comment2, comment3]) expect(flagged[comment1.id]).to be expect(flagged[comment2.id]).to_not be expect(flagged[comment3.id]).to be end end subject { build(:user) } it "is valid" do expect(subject).to be_valid end describe "#terms" do it "is not valid without accepting the terms of service" do subject.terms_of_service = nil expect(subject).to_not be_valid end end describe "#name" do it "is the username when the user is not an organization" do expect(subject.name).to eq(subject.username) end end describe 'preferences' do describe 'email_on_comment' do it 'should be false by default' do expect(subject.email_on_comment).to eq(false) end end describe 'email_on_comment_reply' do it 'should be false by default' do expect(subject.email_on_comment_reply).to eq(false) end end describe 'subscription_to_website_newsletter' do it 'should be false by default' do expect(subject.newsletter).to eq(false) end end end describe "administrator?" do it "is false when the user is not an admin" do expect(subject.administrator?).to be false end it "is true when the user is an admin" do subject.update(roles: ["administrator"]) expect(subject.administrator?).to be true end end describe "moderator?" do it "is false when the user is not a moderator" do expect(subject.moderator?).to be false end it "is true when the user is a moderator" do subject.update(roles: ["moderator"]) expect(subject.moderator?).to be true end end describe "organization?" do it "is false when the user is not an organization" do expect(subject.organization?).to be false end describe 'when it is an organization' do before(:each) { create(:organization, user: subject) } it "is true when the user is an organization" do expect(subject.organization?).to be true end it "calculates the name using the organization name" do expect(subject.name).to eq(subject.organization.name) end end end describe "verified_organization?" do it "is falsy when the user is not an organization" do expect(subject).to_not be_verified_organization end describe 'when it is an organization' do before(:each) { create(:organization, user: subject) } it "is false when the user is not a verified organization" do expect(subject).to_not be_verified_organization end it "is true when the user is a verified organization" do subject.organization.verify expect(subject).to be_verified_organization end end end describe "organization_attributes" do before(:each) { subject.organization_attributes = {name: 'org', responsible_name: 'julia'} } it "triggers the creation of an associated organization" do expect(subject.organization).to be expect(subject.organization.name).to eq('org') expect(subject.organization.responsible_name).to eq('julia') end it "deactivates the validation of username, and activates the validation of organization" do subject.username = nil expect(subject).to be_valid subject.organization.name= nil expect(subject).to_not be_valid end end describe "official?" do it "is false when the user is not an official" do expect(subject.official_level).to eq(0) expect(subject.official?).to be false end it "is true when the user is an official" do subject.official_level = 3 subject.save expect(subject.official?).to be true end end describe "add_official_position!" do it "is false when level not valid" do expect(subject.add_official_position!(89)).to be false end it "updates official position fields" do expect(subject).not_to be_official subject.add_official_position!(2) expect(subject).to be_official expect(subject.official_level).to eq(2) subject.add_official_position!(3) expect(subject.official_level).to eq(3) end end describe "remove_official_position!" do it "updates official position fields" do subject.add_official_position!(3) expect(subject).to be_official subject.remove_official_position! expect(subject).not_to be_official expect(subject.official_level).to eq(0) end end describe "officials scope" do it "returns only users with official positions" do create(:user, official_level: 1) create(:user, official_level: 3) create(:user, official_level: 4) create(:user, official_level: 5) 2.times { create(:user) } officials = User.officials expect(officials.size).to eq(4) officials.each do |user| expect(user.official_level).to be > 0 end end end describe "has_official_email" do it "checks if the mail address has the officials domain" do # We will use empleados.madrid.es as the officials' domain # Subdomains are also accepted Setting['email_domain_for_officials'] = 'officials.madrid.es' user1 = create(:user, email: "john@officials.madrid.es", confirmed_at: Time.now) user2 = create(:user, email: "john@yes.officials.madrid.es", confirmed_at: Time.now) user3 = create(:user, email: "john@unofficials.madrid.es", confirmed_at: Time.now) user4 = create(:user, email: "john@example.org", confirmed_at: Time.now) expect(user1.has_official_email?).to eq(true) expect(user2.has_official_email?).to eq(true) expect(user3.has_official_email?).to eq(false) expect(user4.has_official_email?).to eq(false) end end describe "self.search" do it "find users by email" do user1 = create(:user, email: "larry@madrid.es") create(:user, email: "bird@madrid.es") search = User.search("larry@madrid.es") expect(search.size).to eq(1) expect(search.first).to eq(user1) end it "find users by name" do user1 = create(:user, username: "Larry Bird") create(:user, username: "Robert Parish") search = User.search("larry") expect(search.size).to eq(1) expect(search.first).to eq(user1) end it "returns no results if no search term provided" do expect(User.search(" ").size).to eq(0) end end describe "verification" do it_behaves_like "verifiable" end describe "document_number" do it "should upcase document number" do user = User.new({document_number: "x1234567z"}) user.valid? expect(user.document_number).to eq("X1234567Z") end it "should remove all characters except numbers and letters" do user = User.new({document_number: " 12.345.678 - B"}) user.valid? expect(user.document_number).to eq("12345678B") end end describe "#erase" do it "anonymizes a user and marks him as hidden" do user = create(:user, username: "manolo", unconfirmed_email: "a@a.com", document_number: "1234", phone_number: "5678", encrypted_password: "foobar", confirmation_token: "token1", reset_password_token: "token2", email_verification_token: "token3") user.erase('a test') user.reload expect(user.erase_reason).to eq('a test') expect(user.erased_at).to be expect(user.username).to be_nil expect(user.email).to be_nil expect(user.unconfirmed_email).to be_nil expect(user.document_number).to be_nil expect(user.phone_number).to be_nil expect(user.encrypted_password).to be_empty expect(user.confirmation_token).to be_nil expect(user.reset_password_token).to be_nil expect(user.email_verification_token).to be_nil end end describe "#has_facebook_identity" do let(:user) { create(:user) } context "when the user has no identities" do it "returns false" do expect(user).to_not have_facebook_identity end end context "when the user has an identity with another provider" do let!(:identity) { create(:identity, provider: 'twitter', user: user)} it "returns false" do expect(user).to_not have_facebook_identity end end context "when the user has an identity with facebook" do let!(:identity) { create(:identity, provider: 'facebook', user: user)} it "returns true" do expect(user).to have_facebook_identity end end context "when the user identities with multiple providers, including facebook" do let!(:identity1) { create(:identity, provider: 'twitter', user: user)} let!(:identity2) { create(:identity, provider: 'facebook', user: user)} it "returns true" do expect(user).to have_facebook_identity end end end end
AjuntamentdeBarcelona/decidim.barcelona
spec/models/user_spec.rb
Ruby
agpl-3.0
10,196
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2016 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.snmp; public class ErrorStatusException extends SnmpException { private static final long serialVersionUID = 1L; public ErrorStatusException(final ErrorStatus status) { super("SNMP error-status: " + status.toString() + "(" + status.ordinal() + ")"); } public ErrorStatusException(final ErrorStatus status, final Throwable t) { super("SNMP error-status: " + status.toString() + "(" + status.ordinal() + ")", t); } public ErrorStatusException(final ErrorStatus status, final String message) { super("SNMP error-status: " + status.toString() + "(" + status.ordinal() + "): " + message); } }
aihua/opennms
core/snmp/api/src/main/java/org/opennms/netmgt/snmp/ErrorStatusException.java
Java
agpl-3.0
1,874
package am.extension.multiUserFeedback.login; import java.util.ArrayList; import am.app.mappingEngine.Mapping; import am.extension.multiUserFeedback.experiment.MUExperiment; public class ServerLogin extends UFLLogin{ MUExperiment experiment; @Override public void login(MUExperiment exp, String id) { // TODO Auto-generated method stub this.experiment=exp; exp.usersMappings.put(id, new ArrayList<Mapping>()); exp.usersGroup.put(id, getGroup()); } private int getGroup() { int size=experiment.usersMappings.size(); return size%3; } }
Stanwar/agreementmaker
AgreementMaker-OSGi/AgreementMaker-UserFeedback/src/main/java/am/extension/multiUserFeedback/login/ServerLogin.java
Java
agpl-3.0
560
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2015 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2015. All rights reserved". ********************************************************************************/ /** * Factory class for making SanitizerUtil objects. */ class ImportSanitizerUtilFactory { public static function make($attributeValueSanitizerUtilType, $modelClassName, $attributeName, $columnName, $columnMappingData, ImportSanitizeResultsUtil $importSanitizeResultsUtil = null, $penultimateModelClassName = null, $penultimateAttributeName = null) { assert('is_string($attributeValueSanitizerUtilType)'); assert('is_string($modelClassName)'); assert('is_string($attributeName) || $attributeName == null'); assert('is_string($columnName)'); assert('$columnMappingData == null || is_array($columnMappingData)'); $sanitizerUtilClassName = $attributeValueSanitizerUtilType . 'SanitizerUtil'; return new $sanitizerUtilClassName($modelClassName, $attributeName, $columnName, $columnMappingData, $importSanitizeResultsUtil, $penultimateModelClassName, $penultimateAttributeName); } } ?>
raymondlamwu/zurmotest
app/protected/modules/import/utils/sanitizers/ImportSanitizerUtilFactory.php
PHP
agpl-3.0
3,223
if(!dojo._hasResource["dojox.collections.Stack"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojox.collections.Stack"] = true; dojo.provide("dojox.collections.Stack"); dojo.require("dojox.collections._base"); dojox.collections.Stack=function(/* array? */arr){ // summary // returns an object of type dojox.collections.Stack var q=[]; if (arr) q=q.concat(arr); this.count=q.length; this.clear=function(){ // summary // Clear the internal array and reset the count q=[]; this.count=q.length; }; this.clone=function(){ // summary // Create and return a clone of this Stack return new dojox.collections.Stack(q); }; this.contains=function(/* object */o){ // summary // check to see if the stack contains object o for (var i=0; i<q.length; i++){ if (q[i] == o){ return true; // bool } } return false; // bool }; this.copyTo=function(/* array */ arr, /* int */ i){ // summary // copy the stack into array arr at index i arr.splice(i,0,q); }; this.forEach=function(/* function */ fn, /* object? */ scope){ // summary // functional iterator, following the mozilla spec. dojo.forEach(q, fn, scope); }; this.getIterator=function(){ // summary // get an iterator for this collection return new dojox.collections.Iterator(q); // dojox.collections.Iterator }; this.peek=function(){ // summary // Return the next item without altering the stack itself. return q[(q.length-1)]; // object }; this.pop=function(){ // summary // pop and return the next item on the stack var r=q.pop(); this.count=q.length; return r; // object }; this.push=function(/* object */ o){ // summary // Push object o onto the stack this.count=q.push(o); }; this.toArray=function(){ // summary // create and return an array based on the internal collection return [].concat(q); // array }; } }
235/gwt-odb-ui
src/net/pleso/odbui/public/js/dojo-release-1.0.2/dojox/collections/Stack.js
JavaScript
agpl-3.0
1,921
# frozen_string_literal: true module Decidim # Shared behaviour for signed_in users that require the latest TOS accepted module NeedsTosAccepted extend ActiveSupport::Concern included do before_action :tos_accepted_by_user helper_method :terms_and_conditions_page end private def tos_accepted_by_user return true unless request.format.html? return true unless current_user return if current_user.tos_accepted? return if permitted_paths? redirect_to_tos end def terms_and_conditions_page @terms_and_conditions_page ||= Decidim::StaticPage.find_by(slug: "terms-and-conditions", organization: current_organization) end def permitted_paths? permitted_paths = [tos_path, decidim.delete_account_path, decidim.accept_tos_path, decidim.data_portability_path, decidim.export_data_portability_path, decidim.download_file_data_portability_path] # ensure that path with or without query string pass permitted_paths.find { |el| el.split("?").first == request.path } end def tos_path decidim.page_path terms_and_conditions_page end def redirect_to_tos # Store the location where the user needs to be redirected to after the # TOS is agreed. store_location_for( current_user, stored_location_for(current_user) || request.path ) flash[:notice] = flash[:notice] if flash[:notice] flash[:secondary] = t("required_review.alert", scope: "decidim.pages.terms_and_conditions") redirect_to tos_path end end end
AjuntamentdeBarcelona/decidim
decidim-core/app/controllers/concerns/decidim/needs_tos_accepted.rb
Ruby
agpl-3.0
1,715
#include <openvibe/ov_all.h> #include "ovp_defines.h" #include "box-algorithms/ovpCVRPNAnalogServer.h" #include "box-algorithms/ovpCVRPNButtonServer.h" #include "box-algorithms/ovpCBoxAlgorithmVRPNAnalogClient.h" #include "box-algorithms/ovpCBoxAlgorithmVRPNButtonClient.h" #include <vector> OVP_Declare_Begin(); #if defined TARGET_HAS_ThirdPartyVRPN OVP_Declare_New(OpenViBEPlugins::VRPN::CVRPNAnalogServerDesc); OVP_Declare_New(OpenViBEPlugins::VRPN::CVRPNButtonServerDesc); OVP_Declare_New(OpenViBEPlugins::VRPN::CBoxAlgorithmVRPNAnalogClientDesc); OVP_Declare_New(OpenViBEPlugins::VRPN::CBoxAlgorithmVRPNButtonClientDesc); #endif OVP_Declare_End();
alexandrebarachant/openvibe
plugins/processing/vrpn/src/ovp_main.cpp
C++
agpl-3.0
662
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd. * Copyright (C) 2011 - 2014 Salesagility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". ********************************************************************************/ /********************************************************************************* * Description: TODO: To be written. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. * All Rights Reserved. * Contributor(s): ______________________________________.. ********************************************************************************/ /**************************** general UI Stuff *******************/ require_once('modules/Campaigns/utils.php'); global $app_strings; global $timedate; global $app_list_strings; global $mod_strings; global $current_user; global $sugar_version, $sugar_config; /**************************** GENERAL SETUP WORK*******************/ $campaign_focus = new Campaign(); if (isset($_REQUEST['campaign_id']) && !empty($_REQUEST['campaign_id'])) { $campaign_focus->retrieve($_REQUEST['campaign_id']); }else{ sugar_die($app_strings['ERROR_NO_RECORD']); } global $theme; $json = getJSONobj(); $GLOBALS['log']->info("Wizard Continue Create Wizard"); if($campaign_focus->campaign_type=='NewsLetter'){ echo getClassicModuleTitle($mod_strings['LBL_MODULE_NAME'], array($mod_strings['LBL_NEWSLETTER WIZARD_TITLE'].' '.$campaign_focus->name), true); }else{ echo getClassicModuleTitle($mod_strings['LBL_MODULE_NAME'], array($mod_strings['LBL_CAMPAIGN'].' '.$campaign_focus->name), true); } $ss = new Sugar_Smarty(); $ss->assign("MOD", $mod_strings); $ss->assign("APP", $app_strings); if (isset($_REQUEST['return_module'])) $ss->assign("RETURN_MODULE", $_REQUEST['return_module']); if (isset($_REQUEST['return_action'])) $ss->assign("RETURN_ACTION", $_REQUEST['return_action']); if (isset($_REQUEST['return_id'])) $ss->assign("RETURN_ID", $_REQUEST['return_id']); // handle Create $module then Cancel $ss->assign('CAMPAIGN_ID', $campaign_focus->id); $seps = get_number_seperators(); $ss->assign("NUM_GRP_SEP", $seps[0]); $ss->assign("DEC_SEP", $seps[1]); /**************************** MARKETING UI DIV Stuff *******************/ //$campaign_focus->load_relationship('emailmarketing'); //$mrkt_ids = $campaign_focus->emailmarketing->get(); $mrkt_focus = new EmailMarketing(); //override marketing by session stored selection earlier.. if(isset($_REQUEST['func']) && $_REQUEST['func'] == 'createEmailMarketing') { unset($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']); } else { //check to see if this campaign has an email marketing already attached, and if so, create duplicate $campaign_focus->load_relationship('emailmarketing'); $mrkt_lists = $campaign_focus->emailmarketing->get(); } if(!empty($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']) && !in_array($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'], $mrkt_lists)) { unset($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']); } if(!empty($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'])) { if(!empty($_REQUEST['record']) && in_array($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'], $mrkt_lists)) { $_REQUEST['record'] = $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']; } if(!empty($_REQUEST['marketing_id']) && in_array($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'], $mrkt_lists)) { if(!empty($_REQUEST['func']) && $_REQUEST['func'] == 'editEmailMarketing') { $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'] = $_REQUEST['marketing_id']; } else { $_REQUEST['marketing_id'] = $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']; } } } //if record param exists and it is not empty, then retrieve this bean if(isset($_REQUEST['record']) and !empty($_REQUEST['record'])){ $mrkt_focus->retrieve($_REQUEST['record']); $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'] = $mrkt_focus->id; } else if(isset($_REQUEST['marketing_id']) and !empty($_REQUEST['marketing_id'])) { $mrkt_focus->retrieve($_REQUEST['marketing_id']); $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'] = $mrkt_focus->id; }else{ if(!isset($mrkt_lists) || !$mrkt_lists) { unset($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']); } else if(count($mrkt_lists) == 1){ if(empty($_REQUEST['func']) && isset($_REQUEST['func']) && $_REQUEST['func'] != 'createEmailMarketing') { $mrkt_focus->retrieve($mrkt_lists[0]); $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'] = $mrkt_lists[0]; } else { // if user clicks create from the email marking sub panel $mrkt_focus->retrieve($mrkt_lists[0]); $mrkt_focus->id = create_guid(); $mrkt_focus->name = ''; // clone $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'] = $mrkt_focus->id; } } else if(count($mrkt_lists) > 1) { if(!empty($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']) && in_array($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'], $mrkt_lists)) { if (!isset($_REQUEST['func']) || (empty($_REQUEST['func']) && $_REQUEST['func'] != 'createEmailMarketing')) { $mrkt_focus->retrieve($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']); } else { // if user clicks create from the email marking sub panel $mrkt_focus->retrieve($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']); $mrkt_focus->id = create_guid(); $mrkt_focus->name = ''; // clone $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'] = $mrkt_focus->id; } } else { unset($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']); } // if(!empty($mrkt_lists)){ // //reverse array so we always use the most recent one: // $mrkt_lists = array_reverse($mrkt_lists); // $mrkt_focus->retrieve($mrkt_lists[0]); // $mrkt_focus->id = ''; // //$mrkt_focus->name = $mod_strings['LBL_COPY_OF'] . ' '. $mrkt_focus->name; // } } else { unset($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']); //throw new Exception('illegal related marketing list'); } } $ss->assign("CALENDAR_LANG", "en"); $ss->assign("USER_DATEFORMAT", '('. $timedate->get_user_date_format().')'); $ss->assign("CALENDAR_DATEFORMAT", $timedate->get_cal_date_format()); $ss->assign("TIME_MERIDIEM", $timedate->AMPMMenu('', $mrkt_focus->time_start)); $ss->assign("MRKT_ID", $mrkt_focus->id); $ss->assign("MRKT_NAME", $mrkt_focus->name); $ss->assign("MRKT_FROM_NAME", $mrkt_focus->from_name); $ss->assign("MRKT_FROM_ADDR", $mrkt_focus->from_addr); $def = $mrkt_focus->getFieldDefinition('from_name'); $ss->assign("MRKT_FROM_NAME_LEN", $def['len']); //jc: bug 15498 // assigning the length of the reply name from the var defs to the template to be used // as the max length for the input field $def = $mrkt_focus->getFieldDefinition('reply_to_name'); $ss->assign("MRKT_REPLY_NAME_LEN", $def['len']); $ss->assign("MRKT_REPLY_NAME", $mrkt_focus->reply_to_name); $def = $mrkt_focus->getFieldDefinition('reply_to_addr'); $ss->assign("MRKT_REPLY_ADDR_LEN", $def['len']); // end bug 15498 $ss->assign("MRKT_REPLY_ADDR", $mrkt_focus->reply_to_addr); $ss->assign("MRKT_DATE_START", $mrkt_focus->date_start); $ss->assign("MRKT_TIME_START", $mrkt_focus->time_start); //$_REQUEST['mass'] = $mrkt_focus->id; $ss->assign("MRKT_ID", $mrkt_focus->id); $emails=array(); $mailboxes=get_campaign_mailboxes($emails); /* * get full array of stored options */ $IEStoredOptions = get_campaign_mailboxes_with_stored_options(); $IEStoredOptionsJSON = (!empty($IEStoredOptions)) ? $json->encode($IEStoredOptions, false) : 'new Object()'; $ss->assign("IEStoredOptions", $IEStoredOptionsJSON); //add empty options. $emails['']='nobody@example.com'; $mailboxes['']=''; //inbound_email_id $default_email_address='nobody@example.com'; $from_emails = ''; foreach ($mailboxes as $id=>$name) { if (!empty($from_emails)) { $from_emails.=','; } if ($id=='') { $from_emails.="'EMPTY','$name','$emails[$id]'"; } else { $from_emails.="'$id','$name','$emails[$id]'"; } } $ss->assign("FROM_EMAILS",$from_emails); $ss->assign("DEFAULT_FROM_EMAIL",$default_email_address); $ss->assign("STATUS_OPTIONS", get_select_options_with_id($app_list_strings['email_marketing_status_dom'],$mrkt_focus->status ? $mrkt_focus->status : 'active')); if (empty($mrkt_focus->inbound_email_id)) { $defaultMailboxId = ''; $mailboxIds = array(); foreach($mailboxes as $mailboxId => $mailboxName) { if($mailboxId) { $mailboxIds[] = $mailboxId; } } if(count($mailboxIds) == 1) { $defaultMailboxId = $mailboxIds[0]; } $ss->assign("MAILBOXES", get_select_options_with_id($mailboxes, $defaultMailboxId)); $ss->assign("MAILBOXES_DEAULT", $defaultMailboxId); } else { $ss->assign("MAILBOXES", get_select_options_with_id($mailboxes, $mrkt_focus->inbound_email_id)); } $outboundEmailAccountLabels = array(); $outboundEmailLabels = array(); $outboundEmailAccounts = BeanFactory::getBean('OutboundEmailAccounts')->get_full_list(); if ($outboundEmailAccounts) { foreach ($outboundEmailAccounts as $outboundEmailAccount) { $outboundEmailLabels[$outboundEmailAccount->id] = $outboundEmailAccount->name; } } else { $GLOBALS['log']->warn('There are no outbound email accounts available.'); $GLOBALS['log']->info('Please ensure that the email settings are configured correctly'); } $ss->assign('OUTBOUND_MAILBOXES', get_select_options_with_id($outboundEmailLabels, $mrkt_focus->outbound_email_id)); $ss->assign("TIME_MERIDIEM", $timedate->AMPMMenu('', $mrkt_focus->time_start)); $ss->assign("TIME_FORMAT", '('. $timedate->get_user_time_format().')'); $email_templates_arr = get_bean_select_array(true, 'EmailTemplate','name','','name'); if($mrkt_focus->template_id) { $ss->assign("TEMPLATE_ID", $mrkt_focus->template_id); $templateId = $mrkt_focus->template_id; if(!$templateId && !empty($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedTemplateId'])) { $templateId = $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedTemplateId']; } $ss->assign("EMAIL_TEMPLATE_OPTIONS", get_select_options_with_id($email_templates_arr, $templateId)); $ss->assign("EDIT_TEMPLATE","visibility:inline"); $ss->assign('email_template_already_selected', $mrkt_focus->template_id); } else { $templateId = isset($_REQUEST['template_id']) && $_REQUEST['template_id'] ? $_REQUEST['template_id'] : ""; if(!$templateId && !empty($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedTemplateId'])) { $templateId = $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedTemplateId']; } $ss->assign("EMAIL_TEMPLATE_OPTIONS", get_select_options_with_id($email_templates_arr, isset($_REQUEST['func']) && $_REQUEST['func'] == 'createEmailMarketing' ? null : $templateId)); $ss->assign("EDIT_TEMPLATE","visibility:hidden"); } $scope_options=get_message_scope_dom($campaign_focus->id,$campaign_focus->name,$mrkt_focus->db); $prospectlists=array(); if (isset($mrkt_focus->all_prospect_lists) && $mrkt_focus->all_prospect_lists==1) { $ss->assign("ALL_PROSPECT_LISTS_CHECKED","checked"); $ss->assign("MESSAGE_FOR_DISABLED","disabled"); } else { //get select prospect list. if (!empty($mrkt_focus->id)) { $mrkt_focus->load_relationship('prospectlists'); $prospectlists=$mrkt_focus->prospectlists->get(); } else { $ss->assign("ALL_PROSPECT_LISTS_CHECKED","checked"); $ss->assign("MESSAGE_FOR_DISABLED","disabled"); }; } // force to check all prospect list by default.. $ss->assign("ALL_PROSPECT_LISTS_CHECKED","checked"); $ss->assign("MESSAGE_FOR_DISABLED","disabled"); if (empty($prospectlists)) $prospectlists=array(); if (empty($scope_options)) $scope_options=array(); $ss->assign("SCOPE_OPTIONS", get_select_options_with_id($scope_options, $prospectlists)); $ss->assign("SAVE_CONFIRM_MESSAGE", $mod_strings['LBL_CONFIRM_SEND_SAVE']); $javascript = new javascript(); $javascript->setFormName('wizform'); $javascript->setSugarBean($mrkt_focus); $javascript->addAllFields(''); echo $javascript->getScript(); /**************************** Final Step UI DIV *******************/ //Grab the prospect list of type default $default_pl_focus = ' '; $campaign_focus->load_relationship('prospectlists'); $prospectlists=$campaign_focus->prospectlists->get(); $pl_count = 0; $pl_lists = 0; if(!empty($prospectlists)){ foreach ($prospectlists as $prospect_id){ $pl_focus = new ProspectList(); $pl_focus->retrieve($prospect_id); if (($pl_focus->list_type == 'default') || ($pl_focus->list_type == 'seed')){ $default_pl_focus= $pl_focus; // get count of all attached target types $pl_count = $default_pl_focus->get_entry_count(); } $pl_lists = $pl_lists+1; } } //if count is 0, then hide inputs and and print warning message $pl_diabled_test_too = true; if ($pl_count==0){ if ($pl_lists==0){ //print no target list warning if($campaign_focus->campaign_type != "Email" || $campaign_focus->campaign_type != "NewsLetter"){ $ss->assign("WARNING_MESSAGE", $mod_strings['LBL_NO_TARGETS_WARNING_NON_EMAIL']); $ss->assign('error_on_target_list', $mod_strings['LBL_NO_TARGETS_WARNING_NON_EMAIL']); } else{ $ss->assign("WARNING_MESSAGE", $mod_strings['LBL_NO_TARGETS_WARNING']); $ss->assign('error_on_target_list', $mod_strings['LBL_NO_TARGETS_WARNING']); } }else{ //print no entries warning if($campaign_focus->campaign_type=='NewsLetter'){ $ss->assign("WARNING_MESSAGE", $mod_strings['LBL_NO_SUBS_ENTRIES_WARNING']); $ss->assign('error_on_target_list', $mod_strings['LBL_NO_SUBS_ENTRIES_WARNING']); $pl_diabled_test_too = false; }elseif($campaign_focus->campaign_type=='Email'){ $ss->assign("WARNING_MESSAGE", $mod_strings['LBL_NO_TARGET_ENTRIES_WARNING']); $ss->assign('error_on_target_list', $mod_strings['LBL_NO_TARGET_ENTRIES_WARNING']); } else{ $ss->assign("WARNING_MESSAGE", $mod_strings['LBL_NO_TARGET_ENTRIES_WARNING_NON_EMAIL']); $ss->assign('error_on_target_list', $mod_strings['LBL_NO_TARGET_ENTRIES_WARNING_NON_EMAIL']); } } //disable the send email options $ss->assign("PL_DISABLED",'disabled'); $ss->assign("PL_DISABLED_TEST", $pl_diabled_test_too ? 'disabled' : false); }else{ //show inputs and assign type to be radio } if(!$list = BeanFactory::getBean('EmailMarketing')->get_full_list("", "campaign_id = '{$campaign_focus->id}' AND template_id IS NOT NULL AND template_id != ''")) { $ss->assign('error_on_templates', $mod_strings['LBL_NO_TEMPLATE_SELECTED']); } /**************************** WIZARD UI DIV Stuff *******************/ $additionalParams = ''; if(isset($_REQUEST['template_id']) && $_REQUEST['template_id']) { $additionalParams .= '&template_id=' . $_REQUEST['template_id']; } if(isset($_REQUEST['marketing_id']) && $_REQUEST['marketing_id']) { $additionalParams .= '&marketing_id=' . $_REQUEST['marketing_id']; } $camp_url = "index.php?action=WizardNewsletter&module=Campaigns&return_module=Campaigns&return_action=WizardHome"; $camp_url .= "&return_id=".$campaign_focus->id."&record=".$campaign_focus->id . $additionalParams ."&direct_step="; $ss->assign("CAMP_WIZ_URL", $camp_url); $summ_url = $mod_strings['LBL_NAVIGATION_MENU_SUMMARY']; if(!empty($focus->id)){ $summ_url = "<a href='index.php?action=WizardHome&module=Campaigns"; $summ_url .= "&return_id=".$focus->id."&record=".$focus->id; $summ_url .= "'> ". $mod_strings['LBL_NAVIGATION_MENU_SUMMARY']."</a>"; } $summ_url = $mod_strings['LBL_NAVIGATION_MENU_SUMMARY']; if(!empty($focus->id)){ $summ_url = "index.php?action=WizardHome&module=Campaigns&return_id=".$focus->id."&record=".$focus->id; } $ss->assign("SUMM_URL", $summ_url); // this is the wizard control script that resides in page $divScript = <<<EOQ <script type="text/javascript" language="javascript"> /* * this is the custom validation script that will call the right validation for each div */ function validate_wiz_form(step){ switch (step){ case 'step1': if (!validate_step1()) { check_form('wizform') return false; } clear_all_errors(); break; case 'step2': return check_form('wizform'); break; default://no additional validation needed } return true; } function validate_step1() { if(!$('#template_id').val()) return false; return true; } showfirst('marketing') </script> EOQ; //$ss->assign("WIZ_JAVASCRIPT", print_wizard_jscript()); $ss->assign("DIV_JAVASCRIPT", $divScript); /**************************** FINAL END OF PAGE UI Stuff *******************/ if($campaign_focus->campaign_type != 'Telesales' && (!isset($_REQUEST['campaign_type']) || $_REQUEST['campaign_type'] != 'Telesales')) { //$templateURLForProgressBar = '#'; $templateURLForProgressBar = "index.php?action=WizardMarketing&module=Campaigns&return_module=Campaigns&return_action=WizardHome&return_id={$campaign_focus->id}&campaign_id={$campaign_focus->id}&jump=1&campaign_type=Email"; if (isset($campaign_focus->id) && $campaign_focus->id && isset($mrkt_focus->id) && $mrkt_focus->id && isset($mrkt_focus->template_id) && $mrkt_focus->template_id) { $templateURLForProgressBar = "index.php?action=WizardMarketing&module=Campaigns&return_module=Campaigns&return_action=WizardHome&return_id={$campaign_focus->id}&campaign_id={$campaign_focus->id}&jump=1&marketing_id={$mrkt_focus->id}&record={$mrkt_focus->id}&campaign_type=Email&template_id={$mrkt_focus->template_id}"; } if (isset($campaign_focus->id) && $campaign_focus->id && isset($mrkt_focus->template_id) && $mrkt_focus->template_id) { $templateURLForProgressBar = "index.php?action=WizardMarketing&module=Campaigns&return_module=Campaigns&return_action=WizardHome&return_id={$campaign_focus->id}&campaign_id={$campaign_focus->id}&jump=1&campaign_type=Email&template_id={$mrkt_focus->template_id}"; } $marketingURLForProgressBar = false; if (isset($campaign_focus->id) && $campaign_focus->id && isset($mrkt_focus->id) && $mrkt_focus->id && isset($mrkt_focus->template_id) && $mrkt_focus->template_id) { $marketingURLForProgressBar = "index.php?action=WizardMarketing&module=Campaigns&return_module=Campaigns&return_action=WizardHome&return_id={$campaign_focus->id}&campaign_id={$campaign_focus->id}&jump=2&show_wizard_marketing=1&marketing_id={$mrkt_focus->id}&record={$mrkt_focus->id}&campaign_type=Email&template_id={$mrkt_focus->template_id}"; } } $summaryURLForProgressBar = '#'; if(isset($campaign_focus->id) && $campaign_focus->id && isset($mrkt_focus->id) && $mrkt_focus->id && isset($mrkt_focus->template_id) && $mrkt_focus->template_id) { $summaryURLForProgressBar = "index.php?action=WizardMarketing&module=Campaigns&return_module=Campaigns&return_action=WizardHome&return_id={$campaign_focus->id}&campaign_id={$campaign_focus->id}&jump=3&show_wizard_marketing=1&marketing_id={$mrkt_focus->id}&record={$mrkt_focus->id}&campaign_type=Email&template_id={$mrkt_focus->template_id}"; } $steps = array(); $steps[$mod_strings['LBL_NAVIGATION_MENU_GEN1']] = $camp_url.'1'; if($campaign_focus->campaign_type == 'Telesales' || (isset($_REQUEST['campaign_type']) && $_REQUEST['campaign_type'] == 'Telesales')) { $steps[$mod_strings['LBL_NAVIGATION_MENU_GEN2']] = 'index.php?action=WizardNewsletter&module=Campaigns&return_module=Campaigns&return_action=WizardHome&return_id=' . $campaign_focus->id . '&record=' . $campaign_focus->id . '&direct_step=2'; $steps[$mod_strings['LBL_TARGET_LIST']] = $camp_url.'2&show_target_list=1'; } else { $steps[$mod_strings['LBL_TARGET_LIST']] = $camp_url . '2'; } if($campaign_focus->campaign_type != 'Telesales' && (!isset($_REQUEST['campaign_type']) || $_REQUEST['campaign_type'] != 'Telesales')) { $steps[$mod_strings['LBL_SELECT_TEMPLATE']] = $templateURLForProgressBar; if(!$marketingURLForProgressBar) { $marketingURLForProgressBar = "index.php?action=WizardMarketing&module=Campaigns&return_module=Campaigns&return_action=WizardHome&return_id={$campaign_focus->id}&campaign_id={$campaign_focus->id}&jump=2&show_wizard_marketing=1&marketing_id={$mrkt_focus->id}&record={$mrkt_focus->id}&campaign_type=Email&template_id={$mrkt_focus->template_id}"; } $steps[$mod_strings['LBL_NAVIGATION_MENU_MARKETING']] = $marketingURLForProgressBar; if($summaryURLForProgressBar == '#') { $summaryURLForProgressBar = 'javascript:$(\'#wiz_cancel_button\').click();'; } $steps[$mod_strings['LBL_NAVIGATION_MENU_SEND_EMAIL_AND_SUMMARY']] = $summaryURLForProgressBar; } else { if($summaryURLForProgressBar == '#') { $summaryURLForProgressBar = 'javascript:$("#wiz_cancel_button").click();'; } $steps[$mod_strings['LBL_NAVIGATION_MENU_SUMMARY']] = $summaryURLForProgressBar; } include_once('modules/Campaigns/DotListWizardMenu.php'); $dotListWizardMenu = new DotListWizardMenu($mod_strings, $steps, true); // array( // $mod_strings['LBL_NAVIGATION_MENU_GEN1'] => $camp_url.'1', // $mod_strings['LBL_TARGET_LIST'] => $camp_url.'2', // //$mod_strings['LBL_NAVIGATION_MENU_GEN2'] => $camp_url.'2', // //$mod_strings['LBL_NAVIGATION_MENU_TRACKERS'] => $camp_url.'3', // $mod_strings['LBL_SELECT_TEMPLATE'] => $templateURLForProgressBar, // $mod_strings['LBL_NAVIGATION_MENU_MARKETING'] => $marketingURLForProgressBar, //$camp_url.'3', // $mod_strings['LBL_NAVIGATION_MENU_SEND_EMAIL_AND_SUMMARY'] => $summaryURLForProgressBar, // //$mod_strings['LBL_NAVIGATION_MENU_SUMMARY'] => false, // ) // , true); if(isset($_REQUEST['redirectToTargetList']) && $_REQUEST['redirectToTargetList']) { $ss->assign('hideScreen', true); $dotListWizardMenu .= <<<JS <script type="text/javascript"> $(function(){ document.location.href = $('#nav_step2 a').first().attr('href'); }); </script> JS; } $ss->assign('WIZMENU', $dotListWizardMenu); $diagnose = diagnose($errors, $links); $ss->assign('diagnose', $diagnose); // validate sender details if($mrkt_focus->id) { foreach($marketingErrorResults = $mrkt_focus->validate() as $errorKey => $errorMsg) { $errors['marketing'] = $mod_strings['LBL_ERROR_ON_MARKETING']; $errors['marketing_' . $errorKey] = $errorMsg; } } foreach($errors as $error => $msg) { if($msg) { $ss->assign('error_on_' . $error, $msg); } } foreach($links as $link => $url) { if($url) { $ss->assign('link_to_' . $link, $url); } } $ss->assign('link_to_campaign_header', $camp_url.'1'); if($campaign_focus->campaign_type == 'Telesales') { $stepValues = array_values($steps); $ss->assign('link_to_target_list', $stepValues[2]); } else { $ss->assign('link_to_target_list', $camp_url.'2'); } $ss->assign('link_to_choose_template', 'index.php?return_module=Campaigns&module=Campaigns&action=WizardMarketing&campaign_id=' . $campaign_focus->id); $ss->assign('link_to_sender_details', 'index.php?return_module=Campaigns&module=Campaigns&action=WizardMarketing&campaign_id=' . $campaign_focus->id . '&jump=2'); // --------------------------------- // ------------ EDITOR ------------- // --------------------------------- require_once 'include/SuiteEditor/SuiteEditorConnector.php'; $templateWidth = 600; $ss->assign('template_width', $templateWidth); $ss->assign('BODY_EDITOR', SuiteEditorConnector::getHtml(SuiteEditorConnector::getSuiteSettings(isset($focus->body_html) ? html_entity_decode($focus->body_html) : '', $templateWidth))); $ss->assign('hide_width_set', $current_user->getEditorType() != 'mozaik'); // --------------------------------- // --------------------------------- // --------------------------------- if(!empty($_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'])) { $ss->assign('EmailMarketingId', $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId']); } else if(isset($mrkt_lists[0])) { $_SESSION['campaignWizard'][$campaign_focus->id]['defaultSelectedMarketingId'] = $mrkt_lists[0]; $ss->assign('EmailMarketingId', $mrkt_lists[0]); } //if campaign_id is passed then we assume this is being invoked from the campaign module and in a popup. $has_campaign = true; $inboundEmail = true; if (!isset($_REQUEST['campaign_id']) || empty($_REQUEST['campaign_id'])) { $has_campaign = false; } if (!isset($_REQUEST['inboundEmail']) || empty($_REQUEST['inboundEmail'])) { $inboundEmail = false; } // todo : its for testing, remove this! //$has_campaign = false; include_once 'modules/EmailTemplates/templateFields.php'; $ss->assign("FIELD_DEFS_JS", generateFieldDefsJS2()); /////////////////////////////////////// //// CAMPAIGNS if ($has_campaign || $inboundEmail) { //$ss->assign("INPOPUPWINDOW", 'true'); $ss->assign("INSERT_URL_ONCLICK", "insert_variable_html_link(document.wizform.tracker_url.value)"); $get_campaign_urls = function ($campaign_id) { $return_array=array(); if (!empty($campaign_id)) { $db = DBManagerFactory::getInstance(); $campaign_id = $db->quote($campaign_id); $query1="select * from campaign_trkrs where campaign_id='$campaign_id' and deleted=0"; $current=$db->query($query1); while (($row=$db->fetchByAssoc($current)) != null) { $return_array['{'.$row['tracker_name'].'}'] = array( 'text' => $row['tracker_name'] . ' : ' . $row['tracker_url'], 'url' => $row['tracker_url'], 'id' => $row['id'] ); } } return $return_array; }; if ($has_campaign) { $campaign_urls = $get_campaign_urls($_REQUEST['campaign_id']); } if (!empty($campaign_urls)) { $ss->assign("DEFAULT_URL_TEXT", key($campaign_urls)); } if ($has_campaign) { $get_tracker_options = function ($label_list, $key_list, $selected_key, $massupdate = false) { global $app_strings; $select_options = ''; //for setting null selection values to human readable --None-- $pattern = "/'0?'></"; $replacement = "''>".$app_strings['LBL_NONE'].'<'; if ($massupdate) { $replacement .= "/OPTION>\n<OPTION value='__SugarMassUpdateClearField__'><"; // Giving the user the option to unset a drop down list. I.e. none means that it won't get updated } if (empty($key_list)) { $key_list = array(); } //create the type dropdown domain and set the selected value if $opp value already exists foreach ($key_list as $option_key => $option_value) { $select_options .= '<OPTION value="'.$option_key.'" data-id="'.$label_list[$option_key]['id'].'" data-url="'.$label_list[$option_key]['url'].'">'.$label_list[$option_key]['text'].'</OPTION>'; } $select_options = preg_replace($pattern, $replacement, $select_options); return $select_options; }; $ss->assign("TRACKER_KEY_OPTIONS", $get_tracker_options($campaign_urls, $campaign_urls, null)); //$ss->parse("main.NoInbound.tracker_url"); // create tracker URL fields $campaignTracker = new CampaignTracker(); if(isset($_REQUEST['campaign_tracker_id']) && $_REQUEST['campaign_tracker_id']) { $campaignTracker->retrieve((int) $_REQUEST['campaign_tracker_id']); } // todo: hide tracker select if it has no trackers $ss->assign("TRACKER_NAME", isset($focus) ? $focus->tracker_name : null); $ss->assign("TRACKER_URL", isset($focus) ? $focus->tracker_url : null); if (!empty($focus->is_optout) && $focus->is_optout == 1) { $ss->assign("IS_OPTOUT_CHECKED","checked"); $ss->assign("TRACKER_URL_DISABLED","disabled"); } } } // create option of "Contact/Lead/Task" from corresponding module // translations $lblContactAndOthers = implode('/', array( isset($app_list_strings['moduleListSingular']['Contacts']) ? $app_list_strings['moduleListSingular']['Contacts'] : 'Contact', isset($app_list_strings['moduleListSingular']['Leads']) ? $app_list_strings['moduleListSingular']['Leads'] : 'Lead', isset($app_list_strings['moduleListSingular']['Prospects']) ? $app_list_strings['moduleListSingular']['Prospects'] : 'Target', )); // The insert variable drodown should be conditionally displayed. // If it's campaign then hide the Account. if ($has_campaign) { $dropdown = "<option value='Contacts'> " . $lblContactAndOthers . " </option>"; $ss->assign("DROPDOWN", $dropdown); $ss->assign("DEFAULT_MODULE", 'Contacts'); //$xtpl->assign("CAMPAIGN_POPUP_JS", '<script type="text/javascript" src="include/javascript/sugar_3.js"></script>'); } else { $ss->assign("DROPDOWN", genDropDownJS2()); $ss->assign("DEFAULT_MODULE", 'Accounts'); } $ss->assign("INSERT_VARIABLE_ONCLICK", "insert_variable(document.wizform.variable_text.value, \"email_template_editor\")"); /////////////////////////////////////// //// ATTACHMENTS $attachments = ''; if (!empty($mrkt_focus->id)) { $etid = $mrkt_focus->id; } elseif (!empty($old_id)) { $ss->assign('OLD_ID', $old_id); $etid = $old_id; } if (!empty($etid)) { $note = new Note(); $where = "notes.parent_id='{$etid}' AND notes.filename IS NOT NULL"; $notes_list = $note->get_full_list("", $where, true); if (!isset($notes_list)) { $notes_list = array(); } for ($i = 0; $i < count($notes_list); $i++) { $the_note = $notes_list[$i]; if (empty($the_note->filename)) { continue; } $secureLink = 'index.php?entryPoint=download&id=' . $the_note->id . '&type=Notes'; $attachments .= '<input type="checkbox" name="remove_attachment[]" value="' . $the_note->id . '"> ' . $app_strings['LNK_REMOVE'] . '&nbsp;&nbsp;'; $attachments .= '<a href="' . $secureLink . '" target="_blank">' . $the_note->filename . '</a><br>'; } } $attJs = '<script type="text/javascript">'; $attJs .= 'var lnk_remove = "' . $app_strings['LNK_REMOVE'] . '";'; $attJs .= '</script>'; $ss->assign('ATTACHMENTS', $attachments); $ss->assign('ATTACHMENTS_JAVASCRIPT', $attJs); //// END ATTACHMENTS /////////////////////////////////////// $ss->assign('campaign_type', isset($_REQUEST['campaign_type']) && $_REQUEST['campaign_type'] ? $_REQUEST['campaign_type'] : $campaign_focus->campaign_type); $ss->assign('fields', array( 'date_start' => array( 'name' => 'date_start', 'value' => $mrkt_focus->date_start . ' ' . $mrkt_focus->time_start, ) )); if(isset($_SESSION['msg']) && $_SESSION['msg']) { $ss->assign('msg', $mod_strings[$_SESSION['msg']]); unset($_SESSION['msg']); } if(!empty($_REQUEST['func'])) { echo '<input type="hidden" id="func" value="'.$_REQUEST['func'].'">'; } $ss->display('modules/Campaigns/WizardMarketing.html'); ?>
shogunpol/SuiteCRM
modules/Campaigns/WizardMarketing.php
PHP
agpl-3.0
34,825
require File.dirname(__FILE__) + '/../spec_helper' describe PersonMailer do before(:each) do @preferences = preferences(:one) @mailer = PersonMailer @server = @mailer.server @domain = @mailer.domain end pending "message notification" do before(:each) do @message = people(:quentin).received_messages.first @email = PersonMailer.message_notification(@message) end it "should have the right sender" do @email.from.first.should == "message@#{@domain}" end it "should have the right recipient" do @email.to.first.should == @message.recipient.email end it "should have the right domain in the body" do @email.body.should =~ /#{@server}/ end end pending "connection request" do before(:each) do @person = people(:quentin) @contact = people(:aaron) Connection.request(@person, @contact) @connection = Connection.conn(@contact, @person) @email = PersonMailer.connection_request(@connection) end it "should have the right recipient" do @email.to.first.should == @contact.email end it "should have the right requester" do @email.body.should =~ /#{@person.name}/ end it "should have a URL to the connection" do url = "http://#{@server}/connections/#{@connection.id}/edit" @email.body.should =~ /#{url}/ end it "should have the right domain in the body" do @email.body.should =~ /#{@server}/ end it "should have a link to the recipient's preferences" do prefs_url = "http://#{@server}" prefs_url += "/people/#{@contact.to_param}/edit" @email.body.should =~ /#{prefs_url}/ end end end
cgorringe/oscurrency
spec/models/person_mailer_spec.rb
Ruby
agpl-3.0
1,747
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package provisioner import ( "fmt" "math/rand" "sort" "strings" "github.com/juju/errors" "github.com/juju/loggo" "github.com/juju/names" "github.com/juju/utils/set" "github.com/juju/juju/apiserver/common" "github.com/juju/juju/apiserver/params" "github.com/juju/juju/cloudconfig/instancecfg" "github.com/juju/juju/constraints" "github.com/juju/juju/container" "github.com/juju/juju/environs" "github.com/juju/juju/environs/tags" "github.com/juju/juju/instance" "github.com/juju/juju/network" "github.com/juju/juju/provider" "github.com/juju/juju/state" "github.com/juju/juju/state/multiwatcher" "github.com/juju/juju/state/watcher" "github.com/juju/juju/storage" "github.com/juju/juju/storage/poolmanager" "github.com/juju/juju/storage/provider/registry" ) var logger = loggo.GetLogger("juju.apiserver.provisioner") func init() { common.RegisterStandardFacade("Provisioner", 0, NewProvisionerAPI) // Version 1 has the same set of methods as 0, with the same // signatures, but its ProvisioningInfo returns additional // information. Clients may require version 1 so that they // receive this additional information; otherwise they are // compatible. common.RegisterStandardFacade("Provisioner", 1, NewProvisionerAPI) } // ProvisionerAPI provides access to the Provisioner API facade. type ProvisionerAPI struct { *common.Remover *common.StatusSetter *common.StatusGetter *common.DeadEnsurer *common.PasswordChanger *common.LifeGetter *common.StateAddresser *common.APIAddresser *common.EnvironWatcher *common.EnvironMachinesWatcher *common.InstanceIdGetter *common.ToolsFinder *common.ToolsGetter st *state.State resources *common.Resources authorizer common.Authorizer getAuthFunc common.GetAuthFunc } // NewProvisionerAPI creates a new server-side ProvisionerAPI facade. func NewProvisionerAPI(st *state.State, resources *common.Resources, authorizer common.Authorizer) (*ProvisionerAPI, error) { if !authorizer.AuthMachineAgent() && !authorizer.AuthEnvironManager() { return nil, common.ErrPerm } getAuthFunc := func() (common.AuthFunc, error) { isEnvironManager := authorizer.AuthEnvironManager() isMachineAgent := authorizer.AuthMachineAgent() authEntityTag := authorizer.GetAuthTag() return func(tag names.Tag) bool { if isMachineAgent && tag == authEntityTag { // A machine agent can always access its own machine. return true } switch tag := tag.(type) { case names.MachineTag: parentId := state.ParentId(tag.Id()) if parentId == "" { // All top-level machines are accessible by the // environment manager. return isEnvironManager } // All containers with the authenticated machine as a // parent are accessible by it. // TODO(dfc) sometimes authEntity tag is nil, which is fine because nil is // only equal to nil, but it suggests someone is passing an authorizer // with a nil tag. return isMachineAgent && names.NewMachineTag(parentId) == authEntityTag default: return false } }, nil } getAuthOwner := func() (common.AuthFunc, error) { return authorizer.AuthOwner, nil } env, err := st.Environment() if err != nil { return nil, err } urlGetter := common.NewToolsURLGetter(env.UUID(), st) return &ProvisionerAPI{ Remover: common.NewRemover(st, false, getAuthFunc), StatusSetter: common.NewStatusSetter(st, getAuthFunc), StatusGetter: common.NewStatusGetter(st, getAuthFunc), DeadEnsurer: common.NewDeadEnsurer(st, getAuthFunc), PasswordChanger: common.NewPasswordChanger(st, getAuthFunc), LifeGetter: common.NewLifeGetter(st, getAuthFunc), StateAddresser: common.NewStateAddresser(st), APIAddresser: common.NewAPIAddresser(st, resources), EnvironWatcher: common.NewEnvironWatcher(st, resources, authorizer), EnvironMachinesWatcher: common.NewEnvironMachinesWatcher(st, resources, authorizer), InstanceIdGetter: common.NewInstanceIdGetter(st, getAuthFunc), ToolsFinder: common.NewToolsFinder(st, st, urlGetter), ToolsGetter: common.NewToolsGetter(st, st, st, urlGetter, getAuthOwner), st: st, resources: resources, authorizer: authorizer, getAuthFunc: getAuthFunc, }, nil } func (p *ProvisionerAPI) getMachine(canAccess common.AuthFunc, tag names.MachineTag) (*state.Machine, error) { if !canAccess(tag) { return nil, common.ErrPerm } entity, err := p.st.FindEntity(tag) if err != nil { return nil, err } // The authorization function guarantees that the tag represents a // machine. return entity.(*state.Machine), nil } func (p *ProvisionerAPI) watchOneMachineContainers(arg params.WatchContainer) (params.StringsWatchResult, error) { nothing := params.StringsWatchResult{} canAccess, err := p.getAuthFunc() if err != nil { return nothing, common.ErrPerm } tag, err := names.ParseMachineTag(arg.MachineTag) if err != nil { return nothing, common.ErrPerm } if !canAccess(tag) { return nothing, common.ErrPerm } machine, err := p.st.Machine(tag.Id()) if err != nil { return nothing, err } var watch state.StringsWatcher if arg.ContainerType != "" { watch = machine.WatchContainers(instance.ContainerType(arg.ContainerType)) } else { watch = machine.WatchAllContainers() } // Consume the initial event and forward it to the result. if changes, ok := <-watch.Changes(); ok { return params.StringsWatchResult{ StringsWatcherId: p.resources.Register(watch), Changes: changes, }, nil } return nothing, watcher.EnsureErr(watch) } // WatchContainers starts a StringsWatcher to watch containers deployed to // any machine passed in args. func (p *ProvisionerAPI) WatchContainers(args params.WatchContainers) (params.StringsWatchResults, error) { result := params.StringsWatchResults{ Results: make([]params.StringsWatchResult, len(args.Params)), } for i, arg := range args.Params { watcherResult, err := p.watchOneMachineContainers(arg) result.Results[i] = watcherResult result.Results[i].Error = common.ServerError(err) } return result, nil } // WatchAllContainers starts a StringsWatcher to watch all containers deployed to // any machine passed in args. func (p *ProvisionerAPI) WatchAllContainers(args params.WatchContainers) (params.StringsWatchResults, error) { return p.WatchContainers(args) } // SetSupportedContainers updates the list of containers supported by the machines passed in args. func (p *ProvisionerAPI) SetSupportedContainers(args params.MachineContainersParams) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Params)), } canAccess, err := p.getAuthFunc() if err != nil { return result, err } for i, arg := range args.Params { tag, err := names.ParseMachineTag(arg.MachineTag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } machine, err := p.getMachine(canAccess, tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } if len(arg.ContainerTypes) == 0 { err = machine.SupportsNoContainers() } else { err = machine.SetSupportedContainers(arg.ContainerTypes) } if err != nil { result.Results[i].Error = common.ServerError(err) } } return result, nil } // ContainerManagerConfig returns information from the environment config that is // needed for configuring the container manager. func (p *ProvisionerAPI) ContainerManagerConfig(args params.ContainerManagerConfigParams) (params.ContainerManagerConfig, error) { var result params.ContainerManagerConfig config, err := p.st.EnvironConfig() if err != nil { return result, err } cfg := make(map[string]string) cfg[container.ConfigName] = container.DefaultNamespace switch args.Type { case instance.LXC: if useLxcClone, ok := config.LXCUseClone(); ok { cfg["use-clone"] = fmt.Sprint(useLxcClone) } if useLxcCloneAufs, ok := config.LXCUseCloneAUFS(); ok { cfg["use-aufs"] = fmt.Sprint(useLxcCloneAufs) } if lxcDefaultMTU, ok := config.LXCDefaultMTU(); ok { logger.Debugf("using default MTU %v for all LXC containers NICs", lxcDefaultMTU) cfg[container.ConfigLXCDefaultMTU] = fmt.Sprintf("%d", lxcDefaultMTU) } } if !environs.AddressAllocationEnabled() { // No need to even try checking the environ for support. logger.Debugf("address allocation feature flag not enabled") result.ManagerConfig = cfg return result, nil } // Create an environment to verify networking support. env, err := environs.New(config) if err != nil { return result, err } if netEnv, ok := environs.SupportsNetworking(env); ok { // Passing network.AnySubnet below should be interpreted by // the provider as "does ANY subnet support this". supported, err := netEnv.SupportsAddressAllocation(network.AnySubnet) if err == nil && supported { cfg[container.ConfigIPForwarding] = "true" } else if err != nil { // We log the error, but it's safe to ignore as it's not // critical. logger.Debugf("address allocation not supported (%v)", err) } // AWS requires NAT in place in order for hosted containers to // reach outside. if config.Type() == provider.EC2 { cfg[container.ConfigEnableNAT] = "true" } } result.ManagerConfig = cfg return result, nil } // ContainerConfig returns information from the environment config that is // needed for container cloud-init. func (p *ProvisionerAPI) ContainerConfig() (params.ContainerConfig, error) { result := params.ContainerConfig{} config, err := p.st.EnvironConfig() if err != nil { return result, err } result.UpdateBehavior = &params.UpdateBehavior{ config.EnableOSRefreshUpdate(), config.EnableOSUpgrade(), } result.ProviderType = config.Type() result.AuthorizedKeys = config.AuthorizedKeys() result.SSLHostnameVerification = config.SSLHostnameVerification() result.Proxy = config.ProxySettings() result.AptProxy = config.AptProxySettings() result.PreferIPv6 = config.PreferIPv6() result.AllowLXCLoopMounts, _ = config.AllowLXCLoopMounts() return result, nil } // MachinesWithTransientErrors returns status data for machines with provisioning // errors which are transient. func (p *ProvisionerAPI) MachinesWithTransientErrors() (params.StatusResults, error) { var results params.StatusResults canAccessFunc, err := p.getAuthFunc() if err != nil { return results, err } // TODO (wallyworld) - add state.State API for more efficient machines query machines, err := p.st.AllMachines() if err != nil { return results, err } for _, machine := range machines { if !canAccessFunc(machine.Tag()) { continue } if _, provisionedErr := machine.InstanceId(); provisionedErr == nil { // Machine may have been provisioned but machiner hasn't set the // status to Started yet. continue } var result params.StatusResult statusInfo, err := machine.Status() if err != nil { continue } result.Status = params.Status(statusInfo.Status) result.Info = statusInfo.Message result.Data = statusInfo.Data if result.Status != params.StatusError { continue } // Transient errors are marked as such in the status data. if transient, ok := result.Data["transient"].(bool); !ok || !transient { continue } result.Id = machine.Id() result.Life = params.Life(machine.Life().String()) results.Results = append(results.Results, result) } return results, nil } // Series returns the deployed series for each given machine entity. func (p *ProvisionerAPI) Series(args params.Entities) (params.StringResults, error) { result := params.StringResults{ Results: make([]params.StringResult, len(args.Entities)), } canAccess, err := p.getAuthFunc() if err != nil { return result, err } for i, entity := range args.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } machine, err := p.getMachine(canAccess, tag) if err == nil { result.Results[i].Result = machine.Series() } result.Results[i].Error = common.ServerError(err) } return result, nil } // ProvisioningInfo returns the provisioning information for each given machine entity. func (p *ProvisionerAPI) ProvisioningInfo(args params.Entities) (params.ProvisioningInfoResults, error) { result := params.ProvisioningInfoResults{ Results: make([]params.ProvisioningInfoResult, len(args.Entities)), } canAccess, err := p.getAuthFunc() if err != nil { return result, err } for i, entity := range args.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } machine, err := p.getMachine(canAccess, tag) if err == nil { result.Results[i].Result, err = p.getProvisioningInfo(machine) } result.Results[i].Error = common.ServerError(err) } return result, nil } func (p *ProvisionerAPI) getProvisioningInfo(m *state.Machine) (*params.ProvisioningInfo, error) { cons, err := m.Constraints() if err != nil { return nil, err } volumes, err := p.machineVolumeParams(m) if err != nil { return nil, errors.Trace(err) } // TODO(dimitern) Drop this once we only use spaces for // deployments. networks, err := m.RequestedNetworks() if err != nil { return nil, err } var jobs []multiwatcher.MachineJob for _, job := range m.Jobs() { jobs = append(jobs, job.ToParams()) } tags, err := p.machineTags(m, jobs) if err != nil { return nil, errors.Trace(err) } subnetsToZones, err := p.machineSubnetsAndZones(m) if err != nil { return nil, errors.Annotate(err, "cannot match subnets to zones") } return &params.ProvisioningInfo{ Constraints: cons, Series: m.Series(), Placement: m.Placement(), Networks: networks, Jobs: jobs, Volumes: volumes, Tags: tags, SubnetsToZones: subnetsToZones, }, nil } // DistributionGroup returns, for each given machine entity, // a slice of instance.Ids that belong to the same distribution // group as that machine. This information may be used to // distribute instances for high availability. func (p *ProvisionerAPI) DistributionGroup(args params.Entities) (params.DistributionGroupResults, error) { result := params.DistributionGroupResults{ Results: make([]params.DistributionGroupResult, len(args.Entities)), } canAccess, err := p.getAuthFunc() if err != nil { return result, err } for i, entity := range args.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } machine, err := p.getMachine(canAccess, tag) if err == nil { // If the machine is an environment manager, return // environment manager instances. Otherwise, return // instances with services in common with the machine // being provisioned. if machine.IsManager() { result.Results[i].Result, err = environManagerInstances(p.st) } else { result.Results[i].Result, err = commonServiceInstances(p.st, machine) } } result.Results[i].Error = common.ServerError(err) } return result, nil } // environManagerInstances returns all environ manager instances. func environManagerInstances(st *state.State) ([]instance.Id, error) { info, err := st.StateServerInfo() if err != nil { return nil, err } instances := make([]instance.Id, 0, len(info.MachineIds)) for _, id := range info.MachineIds { machine, err := st.Machine(id) if err != nil { return nil, err } instanceId, err := machine.InstanceId() if err == nil { instances = append(instances, instanceId) } else if !errors.IsNotProvisioned(err) { return nil, err } } return instances, nil } // commonServiceInstances returns instances with // services in common with the specified machine. func commonServiceInstances(st *state.State, m *state.Machine) ([]instance.Id, error) { units, err := m.Units() if err != nil { return nil, err } instanceIdSet := make(set.Strings) for _, unit := range units { if !unit.IsPrincipal() { continue } instanceIds, err := state.ServiceInstances(st, unit.ServiceName()) if err != nil { return nil, err } for _, instanceId := range instanceIds { instanceIdSet.Add(string(instanceId)) } } instanceIds := make([]instance.Id, instanceIdSet.Size()) // Sort values to simplify testing. for i, instanceId := range instanceIdSet.SortedValues() { instanceIds[i] = instance.Id(instanceId) } return instanceIds, nil } // Constraints returns the constraints for each given machine entity. func (p *ProvisionerAPI) Constraints(args params.Entities) (params.ConstraintsResults, error) { result := params.ConstraintsResults{ Results: make([]params.ConstraintsResult, len(args.Entities)), } canAccess, err := p.getAuthFunc() if err != nil { return result, err } for i, entity := range args.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } machine, err := p.getMachine(canAccess, tag) if err == nil { var cons constraints.Value cons, err = machine.Constraints() if err == nil { result.Results[i].Constraints = cons } } result.Results[i].Error = common.ServerError(err) } return result, nil } // machineVolumeParams retrieves VolumeParams for the volumes that should be // provisioned with, and attached to, the machine. The client should ignore // parameters that it does not know how to handle. func (p *ProvisionerAPI) machineVolumeParams(m *state.Machine) ([]params.VolumeParams, error) { volumeAttachments, err := m.VolumeAttachments() if err != nil { return nil, err } if len(volumeAttachments) == 0 { return nil, nil } envConfig, err := p.st.EnvironConfig() if err != nil { return nil, err } poolManager := poolmanager.New(state.NewStateSettings(p.st)) allVolumeParams := make([]params.VolumeParams, 0, len(volumeAttachments)) for _, volumeAttachment := range volumeAttachments { volumeTag := volumeAttachment.Volume() volume, err := p.st.Volume(volumeTag) if err != nil { return nil, errors.Annotatef(err, "getting volume %q", volumeTag.Id()) } storageInstance, err := common.MaybeAssignedStorageInstance( volume.StorageInstance, p.st.StorageInstance, ) if err != nil { return nil, errors.Annotatef(err, "getting volume %q storage instance", volumeTag.Id()) } volumeParams, err := common.VolumeParams(volume, storageInstance, envConfig, poolManager) if err != nil { return nil, errors.Annotatef(err, "getting volume %q parameters", volumeTag.Id()) } provider, err := registry.StorageProvider(storage.ProviderType(volumeParams.Provider)) if err != nil { return nil, errors.Annotate(err, "getting storage provider") } if provider.Dynamic() { // Leave dynamic storage to the storage provisioner. continue } volumeAttachmentParams, ok := volumeAttachment.Params() if !ok { // Attachment is already provisioned; this is an insane // state, so we should not proceed with the volume. return nil, errors.Errorf( "volume %s already attached to machine %s", volumeTag.Id(), m.Id(), ) } // Not provisioned yet, so ask the cloud provisioner do it. volumeParams.Attachment = &params.VolumeAttachmentParams{ volumeTag.String(), m.Tag().String(), "", // we're creating the volume, so it has no volume ID. "", // we're creating the machine, so it has no instance ID. volumeParams.Provider, volumeAttachmentParams.ReadOnly, } allVolumeParams = append(allVolumeParams, volumeParams) } return allVolumeParams, nil } // storageConfig returns the provider type and config attributes for the // specified poolName. If no such pool exists, we check to see if poolName is // actually a provider type, in which case config will be empty. func storageConfig(st *state.State, poolName string) (storage.ProviderType, map[string]interface{}, error) { pm := poolmanager.New(state.NewStateSettings(st)) p, err := pm.Get(poolName) // If not a storage pool, then maybe a provider type. if errors.IsNotFound(err) { providerType := storage.ProviderType(poolName) if _, err1 := registry.StorageProvider(providerType); err1 != nil { return "", nil, errors.Trace(err) } return providerType, nil, nil } if err != nil { return "", nil, errors.Trace(err) } return p.Provider(), p.Attrs(), nil } // volumeAttachmentsToState converts a slice of storage.VolumeAttachment to a // mapping of volume names to state.VolumeAttachmentInfo. func volumeAttachmentsToState(in []params.VolumeAttachment) (map[names.VolumeTag]state.VolumeAttachmentInfo, error) { m := make(map[names.VolumeTag]state.VolumeAttachmentInfo) for _, v := range in { if v.VolumeTag == "" { return nil, errors.New("Tag is empty") } volumeTag, err := names.ParseVolumeTag(v.VolumeTag) if err != nil { return nil, errors.Trace(err) } m[volumeTag] = state.VolumeAttachmentInfo{ v.Info.DeviceName, v.Info.BusAddress, v.Info.ReadOnly, } } return m, nil } func networkParamsToStateParams(networks []params.Network, ifaces []params.NetworkInterface) ( []state.NetworkInfo, []state.NetworkInterfaceInfo, error, ) { stateNetworks := make([]state.NetworkInfo, len(networks)) for i, net := range networks { tag, err := names.ParseNetworkTag(net.Tag) if err != nil { return nil, nil, err } stateNetworks[i] = state.NetworkInfo{ Name: tag.Id(), ProviderId: network.Id(net.ProviderId), CIDR: net.CIDR, VLANTag: net.VLANTag, } } stateInterfaces := make([]state.NetworkInterfaceInfo, len(ifaces)) for i, iface := range ifaces { tag, err := names.ParseNetworkTag(iface.NetworkTag) if err != nil { return nil, nil, err } stateInterfaces[i] = state.NetworkInterfaceInfo{ MACAddress: iface.MACAddress, NetworkName: tag.Id(), InterfaceName: iface.InterfaceName, IsVirtual: iface.IsVirtual, Disabled: iface.Disabled, } } return stateNetworks, stateInterfaces, nil } // RequestedNetworks returns the requested networks for each given // machine entity. Each entry in both lists is returned with its // provider specific id. func (p *ProvisionerAPI) RequestedNetworks(args params.Entities) (params.RequestedNetworksResults, error) { result := params.RequestedNetworksResults{ Results: make([]params.RequestedNetworkResult, len(args.Entities)), } canAccess, err := p.getAuthFunc() if err != nil { return result, err } for i, entity := range args.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } machine, err := p.getMachine(canAccess, tag) if err == nil { var networks []string networks, err = machine.RequestedNetworks() if err == nil { // TODO(dimitern) For now, since network names and // provider ids are the same, we return what we got // from state. In the future, when networks can be // added before provisioning, we should convert both // slices from juju network names to provider-specific // ids before returning them. result.Results[i].Networks = networks } } result.Results[i].Error = common.ServerError(err) } return result, nil } // SetProvisioned sets the provider specific instance id, nonce and // metadata for each given machine. Once set, the instance id cannot // be changed. // // TODO(dimitern) This is not used anymore (as of 1.19.0) and is // retained only for backwards-compatibility. It should be removed as // deprecated. SetInstanceInfo is used instead. func (p *ProvisionerAPI) SetProvisioned(args params.SetProvisioned) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Machines)), } canAccess, err := p.getAuthFunc() if err != nil { return result, err } for i, arg := range args.Machines { tag, err := names.ParseMachineTag(arg.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } machine, err := p.getMachine(canAccess, tag) if err == nil { err = machine.SetProvisioned(arg.InstanceId, arg.Nonce, arg.Characteristics) } result.Results[i].Error = common.ServerError(err) } return result, nil } // SetInstanceInfo sets the provider specific machine id, nonce, // metadata and network info for each given machine. Once set, the // instance id cannot be changed. func (p *ProvisionerAPI) SetInstanceInfo(args params.InstancesInfo) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Machines)), } canAccess, err := p.getAuthFunc() if err != nil { return result, err } setInstanceInfo := func(arg params.InstanceInfo) error { tag, err := names.ParseMachineTag(arg.Tag) if err != nil { return common.ErrPerm } machine, err := p.getMachine(canAccess, tag) if err != nil { return err } networks, interfaces, err := networkParamsToStateParams(arg.Networks, arg.Interfaces) if err != nil { return err } volumes, err := common.VolumesToState(arg.Volumes) if err != nil { return err } volumeAttachments, err := common.VolumeAttachmentInfosToState(arg.VolumeAttachments) if err != nil { return err } if err = machine.SetInstanceInfo( arg.InstanceId, arg.Nonce, arg.Characteristics, networks, interfaces, volumes, volumeAttachments); err != nil { return errors.Annotatef( err, "cannot record provisioning info for %q", arg.InstanceId, ) } return nil } for i, arg := range args.Machines { err := setInstanceInfo(arg) result.Results[i].Error = common.ServerError(err) } return result, nil } // WatchMachineErrorRetry returns a NotifyWatcher that notifies when // the provisioner should retry provisioning machines with transient errors. func (p *ProvisionerAPI) WatchMachineErrorRetry() (params.NotifyWatchResult, error) { result := params.NotifyWatchResult{} if !p.authorizer.AuthEnvironManager() { return result, common.ErrPerm } watch := newWatchMachineErrorRetry() // Consume any initial event and forward it to the result. if _, ok := <-watch.Changes(); ok { result.NotifyWatcherId = p.resources.Register(watch) } else { return result, watcher.EnsureErr(watch) } return result, nil } // ReleaseContainerAddresses finds addresses allocated to a container // and marks them as Dead, to be released and removed. It accepts // container tags as arguments. If address allocation feature flag is // not enabled, it will return a NotSupported error. func (p *ProvisionerAPI) ReleaseContainerAddresses(args params.Entities) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Entities)), } if !environs.AddressAllocationEnabled() { return result, errors.NotSupportedf("address allocation") } canAccess, err := p.getAuthFunc() if err != nil { logger.Errorf("failed to get an authorisation function: %v", err) return result, errors.Trace(err) } // Loop over the passed container tags. for i, entity := range args.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { logger.Warningf("failed to parse machine tag %q: %v", entity.Tag, err) result.Results[i].Error = common.ServerError(common.ErrPerm) continue } // The auth function (canAccess) checks that the machine is a // top level machine (we filter those out next) or that the // machine has the host as a parent. container, err := p.getMachine(canAccess, tag) if err != nil { logger.Warningf("failed to get machine %q: %v", tag, err) result.Results[i].Error = common.ServerError(err) continue } else if !container.IsContainer() { err = errors.Errorf("cannot mark addresses for removal for %q: not a container", tag) result.Results[i].Error = common.ServerError(err) continue } id := container.Id() addresses, err := p.st.AllocatedIPAddresses(id) if err != nil { logger.Warningf("failed to get Id for container %q: %v", tag, err) result.Results[i].Error = common.ServerError(err) continue } deadErrors := []error{} logger.Debugf("for container %q found addresses %v", tag, addresses) for _, addr := range addresses { err = addr.EnsureDead() if err != nil { deadErrors = append(deadErrors, err) continue } } if len(deadErrors) != 0 { err = errors.Errorf("failed to mark all addresses for removal for %q: %v", tag, deadErrors) result.Results[i].Error = common.ServerError(err) } } return result, nil } // PrepareContainerInterfaceInfo allocates an address and returns // information to configure networking for a container. It accepts // container tags as arguments. If the address allocation feature flag // is not enabled, it returns a NotSupported error. func (p *ProvisionerAPI) PrepareContainerInterfaceInfo(args params.Entities) ( params.MachineNetworkConfigResults, error) { return p.prepareOrGetContainerInterfaceInfo(args, true) } // GetContainerInterfaceInfo returns information to configure networking // for a container. It accepts container tags as arguments. If the address // allocation feature flag is not enabled, it returns a NotSupported error. func (p *ProvisionerAPI) GetContainerInterfaceInfo(args params.Entities) ( params.MachineNetworkConfigResults, error) { return p.prepareOrGetContainerInterfaceInfo(args, false) } // MACAddressTemplate is used to generate a unique MAC address for a // container. Every '%x' is replaced by a random hexadecimal digit, // while the rest is kept as-is. const MACAddressTemplate = "00:16:3e:%02x:%02x:%02x" // generateMACAddress creates a random MAC address within the space defined by // MACAddressTemplate above. func generateMACAddress() string { digits := make([]interface{}, 3) for i := range digits { digits[i] = rand.Intn(256) } return fmt.Sprintf(MACAddressTemplate, digits...) } // prepareOrGetContainerInterfaceInfo optionally allocates an address and returns information // for configuring networking on a container. It accepts container tags as arguments. func (p *ProvisionerAPI) prepareOrGetContainerInterfaceInfo( args params.Entities, provisionContainer bool) ( params.MachineNetworkConfigResults, error) { result := params.MachineNetworkConfigResults{ Results: make([]params.MachineNetworkConfigResult, len(args.Entities)), } if !environs.AddressAllocationEnabled() { return result, errors.NotSupportedf("address allocation") } // Some preparations first. environ, host, canAccess, err := p.prepareContainerAccessEnvironment() if err != nil { return result, errors.Trace(err) } instId, err := host.InstanceId() if err != nil && errors.IsNotProvisioned(err) { // If the host machine is not provisioned yet, we have nothing // to do. NotProvisionedf will append " not provisioned" to // the message. err = errors.NotProvisionedf("cannot allocate addresses: host machine %q", host) return result, err } subnet, subnetInfo, interfaceInfo, err := p.prepareAllocationNetwork(environ, host, instId) if err != nil { return result, errors.Annotate(err, "cannot allocate addresses") } // Loop over the passed container tags. for i, entity := range args.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } // The auth function (canAccess) checks that the machine is a // top level machine (we filter those out next) or that the // machine has the host as a parent. container, err := p.getMachine(canAccess, tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } else if !container.IsContainer() { err = errors.Errorf("cannot allocate address for %q: not a container", tag) result.Results[i].Error = common.ServerError(err) continue } else if ciid, cerr := container.InstanceId(); provisionContainer == true && cerr == nil { // Since we want to configure and create NICs on the // container before it starts, it must also be not // provisioned yet. err = errors.Errorf("container %q already provisioned as %q", container, ciid) result.Results[i].Error = common.ServerError(err) continue } else if cerr != nil && !errors.IsNotProvisioned(cerr) { // Any other error needs to be reported. result.Results[i].Error = common.ServerError(cerr) continue } var macAddress string var address *state.IPAddress if provisionContainer { // Allocate and set address. macAddress = generateMACAddress() address, err = p.allocateAddress(environ, subnet, host, container, instId, macAddress) if err != nil { err = errors.Annotatef(err, "failed to allocate an address for %q", container) result.Results[i].Error = common.ServerError(err) continue } } else { id := container.Id() addresses, err := p.st.AllocatedIPAddresses(id) if err != nil { logger.Warningf("failed to get Id for container %q: %v", tag, err) result.Results[i].Error = common.ServerError(err) continue } // TODO(dooferlad): if we get more than 1 address back, we ignore everything after // the first. The calling function expects exactly one result though, // so we don't appear to have a way of allocating >1 address to a // container... if len(addresses) != 1 { logger.Warningf("got %d addresses for container %q - expected 1: %v", len(addresses), tag, err) result.Results[i].Error = common.ServerError(err) continue } address = addresses[0] macAddress = address.MACAddress() } // Store it on the machine, construct and set an interface result. dnsServers := make([]string, len(interfaceInfo.DNSServers)) for i, dns := range interfaceInfo.DNSServers { dnsServers[i] = dns.Value } if macAddress == "" { macAddress = interfaceInfo.MACAddress } // TODO(dimitern): Support allocating one address per NIC on // the host, effectively creating the same number of NICs in // the container. result.Results[i] = params.MachineNetworkConfigResult{ Config: []params.NetworkConfig{{ DeviceIndex: interfaceInfo.DeviceIndex, MACAddress: macAddress, CIDR: subnetInfo.CIDR, NetworkName: interfaceInfo.NetworkName, ProviderId: string(interfaceInfo.ProviderId), ProviderSubnetId: string(subnetInfo.ProviderId), VLANTag: interfaceInfo.VLANTag, InterfaceName: interfaceInfo.InterfaceName, Disabled: interfaceInfo.Disabled, NoAutoStart: interfaceInfo.NoAutoStart, DNSServers: dnsServers, ConfigType: string(network.ConfigStatic), Address: address.Value(), // container's gateway is the host's primary NIC's IP. GatewayAddress: interfaceInfo.Address.Value, ExtraConfig: interfaceInfo.ExtraConfig, }}, } } return result, nil } // prepareContainerAccessEnvironment retrieves the environment, host machine, and access // for working with containers. func (p *ProvisionerAPI) prepareContainerAccessEnvironment() (environs.NetworkingEnviron, *state.Machine, common.AuthFunc, error) { cfg, err := p.st.EnvironConfig() if err != nil { return nil, nil, nil, errors.Annotate(err, "failed to get environment config") } environ, err := environs.New(cfg) if err != nil { return nil, nil, nil, errors.Annotate(err, "failed to construct an environment from config") } netEnviron, supported := environs.SupportsNetworking(environ) if !supported { // " not supported" will be appended to the message below. return nil, nil, nil, errors.NotSupportedf("environment %q networking", cfg.Name()) } canAccess, err := p.getAuthFunc() if err != nil { return nil, nil, nil, errors.Annotate(err, "cannot authenticate request") } hostAuthTag := p.authorizer.GetAuthTag() if hostAuthTag == nil { return nil, nil, nil, errors.Errorf("authenticated entity tag is nil") } hostTag, err := names.ParseMachineTag(hostAuthTag.String()) if err != nil { return nil, nil, nil, errors.Trace(err) } host, err := p.getMachine(canAccess, hostTag) if err != nil { return nil, nil, nil, errors.Trace(err) } return netEnviron, host, canAccess, nil } // prepareAllocationNetwork retrieves the subnet, its info, and the interface info // for the allocations. func (p *ProvisionerAPI) prepareAllocationNetwork( environ environs.NetworkingEnviron, host *state.Machine, instId instance.Id, ) ( *state.Subnet, network.SubnetInfo, network.InterfaceInfo, error, ) { var subnetInfo network.SubnetInfo var interfaceInfo network.InterfaceInfo interfaces, err := environ.NetworkInterfaces(instId) if err != nil { return nil, subnetInfo, interfaceInfo, errors.Trace(err) } else if len(interfaces) == 0 { return nil, subnetInfo, interfaceInfo, errors.Errorf("no interfaces available") } logger.Tracef("interfaces for instance %q: %v", instId, interfaces) subnetSet := make(set.Strings) subnetIds := []network.Id{} subnetIdToInterface := make(map[network.Id]network.InterfaceInfo) for _, iface := range interfaces { if iface.ProviderSubnetId == "" { logger.Debugf("no subnet associated with interface %#v (skipping)", iface) continue } else if iface.Disabled { logger.Debugf("interface %#v disabled (skipping)", iface) continue } if !subnetSet.Contains(string(iface.ProviderSubnetId)) { subnetIds = append(subnetIds, iface.ProviderSubnetId) subnetSet.Add(string(iface.ProviderSubnetId)) // This means that multiple interfaces on the same subnet will // only appear once. subnetIdToInterface[iface.ProviderSubnetId] = iface } } subnets, err := environ.Subnets(instId, subnetIds) if err != nil { return nil, subnetInfo, interfaceInfo, errors.Trace(err) } else if len(subnets) == 0 { return nil, subnetInfo, interfaceInfo, errors.Errorf("no subnets available") } logger.Tracef("subnets for instance %q: %v", instId, subnets) // TODO(mfoord): we need a better strategy for picking a subnet to // allocate an address on. (dimitern): Right now we just pick the // first subnet with allocatable range set. Instead, we should // allocate an address per interface, assuming each interface is // on a subnet with allocatable range set, and skipping those // which do not have a range set. var success bool for _, sub := range subnets { logger.Tracef("trying to allocate a static IP on subnet %q", sub.ProviderId) if sub.AllocatableIPHigh == nil { logger.Tracef("ignoring subnet %q - no allocatable range set", sub.ProviderId) // this subnet has no allocatable IPs continue } ok, err := environ.SupportsAddressAllocation(sub.ProviderId) if err == nil && ok { subnetInfo = sub interfaceInfo = subnetIdToInterface[sub.ProviderId] success = true break } logger.Tracef( "subnet %q supports address allocation: %v (error: %v)", sub.ProviderId, ok, err, ) } if !success { // " not supported" will be appended to the message below. return nil, subnetInfo, interfaceInfo, errors.NotSupportedf( "address allocation on any available subnets is", ) } subnet, err := p.createOrFetchStateSubnet(subnetInfo) return subnet, subnetInfo, interfaceInfo, nil } // These are defined like this to allow mocking in tests. var ( allocateAddrTo = func(a *state.IPAddress, m *state.Machine, macAddress string) error { // TODO(mfoord): populate proper interface ID (in state). return a.AllocateTo(m.Id(), "", macAddress) } setAddrsTo = func(a *state.IPAddress, m *state.Machine) error { return m.SetProviderAddresses(a.Address()) } setAddrState = func(a *state.IPAddress, st state.AddressState) error { return a.SetState(st) } ) // allocateAddress tries to pick an address out of the given subnet and // allocates it to the container. func (p *ProvisionerAPI) allocateAddress( environ environs.NetworkingEnviron, subnet *state.Subnet, host, container *state.Machine, instId instance.Id, macAddress string, ) (*state.IPAddress, error) { subnetId := network.Id(subnet.ProviderId()) name := names.NewMachineTag(container.Id()).String() for { addr, err := subnet.PickNewAddress() if err != nil { return nil, err } logger.Tracef("picked new address %q on subnet %q", addr.String(), subnetId) // Attempt to allocate with environ. err = environ.AllocateAddress(instId, subnetId, addr.Address(), macAddress, name) if err != nil { logger.Warningf( "allocating address %q on instance %q and subnet %q failed: %v (retrying)", addr.String(), instId, subnetId, err, ) // It's as good as unavailable for us, so mark it as // such. err = setAddrState(addr, state.AddressStateUnavailable) if err != nil { logger.Warningf( "cannot set address %q to %q: %v (ignoring and retrying)", addr.String(), state.AddressStateUnavailable, err, ) continue } logger.Tracef( "setting address %q to %q and retrying", addr.String(), state.AddressStateUnavailable, ) continue } logger.Infof( "allocated address %q on instance %q and subnet %q", addr.String(), instId, subnetId, ) err = p.setAllocatedOrRelease(addr, environ, instId, container, subnetId, macAddress) if err != nil { // Something went wrong - retry. continue } return addr, nil } } // setAllocatedOrRelease tries to associate the newly allocated // address addr with the container. On failure it makes the best // effort to cleanup and release addr, logging issues along the way. func (p *ProvisionerAPI) setAllocatedOrRelease( addr *state.IPAddress, environ environs.NetworkingEnviron, instId instance.Id, container *state.Machine, subnetId network.Id, macAddress string, ) (err error) { defer func() { if errors.Cause(err) == nil { // Success! return } logger.Warningf( "failed to mark address %q as %q to container %q: %v (releasing and retrying)", addr.String(), state.AddressStateAllocated, container, err, ) // It's as good as unavailable for us, so mark it as // such. err = setAddrState(addr, state.AddressStateUnavailable) if err != nil { logger.Warningf( "cannot set address %q to %q: %v (ignoring and releasing)", addr.String(), state.AddressStateUnavailable, err, ) } err = environ.ReleaseAddress(instId, subnetId, addr.Address(), addr.MACAddress()) if err == nil { logger.Infof("address %q released; trying to allocate new", addr.String()) return } logger.Warningf( "failed to release address %q on instance %q and subnet %q: %v (ignoring and retrying)", addr.String(), instId, subnetId, err, ) }() // Any errors returned below will trigger the release/cleanup // steps above. if err = allocateAddrTo(addr, container, macAddress); err != nil { return errors.Trace(err) } if err = setAddrsTo(addr, container); err != nil { return errors.Trace(err) } logger.Infof("assigned address %q to container %q", addr.String(), container) return nil } func (p *ProvisionerAPI) createOrFetchStateSubnet(subnetInfo network.SubnetInfo) (*state.Subnet, error) { stateSubnetInfo := state.SubnetInfo{ ProviderId: string(subnetInfo.ProviderId), CIDR: subnetInfo.CIDR, VLANTag: subnetInfo.VLANTag, AllocatableIPHigh: subnetInfo.AllocatableIPHigh.String(), AllocatableIPLow: subnetInfo.AllocatableIPLow.String(), } subnet, err := p.st.AddSubnet(stateSubnetInfo) if err != nil { if errors.IsAlreadyExists(err) { subnet, err = p.st.Subnet(subnetInfo.CIDR) } if err != nil { return subnet, errors.Trace(err) } } return subnet, nil } // machineTags returns machine-specific tags to set on the instance. func (p *ProvisionerAPI) machineTags(m *state.Machine, jobs []multiwatcher.MachineJob) (map[string]string, error) { // Names of all units deployed to the machine. // // TODO(axw) 2015-06-02 #1461358 // We need a worker that periodically updates // instance tags with current deployment info. units, err := m.Units() if err != nil { return nil, errors.Trace(err) } unitNames := make([]string, 0, len(units)) for _, unit := range units { if !unit.IsPrincipal() { continue } unitNames = append(unitNames, unit.Name()) } sort.Strings(unitNames) cfg, err := p.st.EnvironConfig() if err != nil { return nil, errors.Trace(err) } machineTags := instancecfg.InstanceTags(cfg, jobs) if len(unitNames) > 0 { machineTags[tags.JujuUnitsDeployed] = strings.Join(unitNames, " ") } return machineTags, nil } // machineSubnetsAndZones returns a map of subnet provider-specific id // to list of availability zone names for that subnet. The result can // be empty if there are no spaces constraints specified for the // machine, or there's an error fetching them. func (p *ProvisionerAPI) machineSubnetsAndZones(m *state.Machine) (map[string][]string, error) { mcons, err := m.Constraints() if err != nil { return nil, errors.Annotate(err, "cannot get machine constraints") } includeSpaces := mcons.IncludeSpaces() if len(includeSpaces) < 1 { // Nothing to do. return nil, nil } // TODO(dimitern): For the network model MVP we only use the first // included space and ignore the rest. spaceName := includeSpaces[0] if len(includeSpaces) > 1 { logger.Debugf( "using space %q from constraints for machine %q (ignoring remaining: %v)", spaceName, m.Id(), includeSpaces[1:], ) } space, err := p.st.Space(spaceName) if err != nil { return nil, errors.Trace(err) } subnets, err := space.Subnets() if err != nil { return nil, errors.Trace(err) } subnetsToZones := make(map[string][]string, len(subnets)) for _, subnet := range subnets { warningPrefix := fmt.Sprintf( "not using subnet %q in space %q for machine %q provisioning: ", subnet.CIDR(), spaceName, m.Id(), ) // TODO(dimitern): state.Subnet.ProviderId needs to be of type // network.Id. providerId := subnet.ProviderId() if providerId == "" { logger.Warningf(warningPrefix + "no ProviderId set") continue } // TODO(dimitern): Once state.Subnet supports multiple zones, // use all of them below. zone := subnet.AvailabilityZone() if zone == "" { logger.Warningf(warningPrefix + "no availability zone(s) set") continue } subnetsToZones[providerId] = []string{zone} } return subnetsToZones, nil }
mhilton/juju
apiserver/provisioner/provisioner.go
GO
agpl-3.0
46,652
# -*- coding: utf-8 -*- { 'sequence': 500, "name" : "ChriCar unique View ID" , "version" : "0.2" , "author" : "Network Gulf IT - India" , "website" : "http://www.chricar.at/ChriCar/index.html" , "description" : """ This module is funded by | ChriCar Beteiligungs- und Beratungs- GmbH | http://www.chricar.at/ChriCar/index.html Developed by | Network Gulf IT - India | http://www.networkgulf.com/ usage: get_id('your_view_name',param1,param2,param3,param4) This function will always return the SAME unique id for a certain combination of parameters for a view. Hint 1: you do not need this function if the unique id can easily be calculated during the grouping. Example: - easy: group by product_id - more complex: group by account_id, period_id - very complex: group by account_id, period_id, currency_id Hint 2: for large tables (100000 rec) performance gain of factor 10x and more split the grouping operation and the get_id into 2 views slow: | select get_id(tablename,param1,param2,...), param1, param2, ... sum(field1), ... | from | group by get_id(tablename,param1,param2,...) ,param1,param2,... fast: 1) view1: | select .... | from | group by param1,param2,... 2) view2: | select get_id('view1',param1,param2,...),* from view1; | (no group by here) """ , "depends" : ["base"] , "init_xml" : [] , "demo" : [] , "data" : [] , "auto_install" : False , 'installable': False , 'application' : False }
VitalPet/c2c-rd-addons
chricar_view_id/__openerp__.py
Python
agpl-3.0
1,460
package im.actor.core.modules.calls.peers; import java.util.HashMap; import java.util.List; import im.actor.core.api.ApiICEServer; import im.actor.core.modules.ModuleContext; import im.actor.core.modules.calls.peers.messages.RTCAdvertised; import im.actor.core.modules.calls.peers.messages.RTCAnswer; import im.actor.core.modules.calls.peers.messages.RTCCandidate; import im.actor.core.modules.calls.peers.messages.RTCCloseSession; import im.actor.core.modules.calls.peers.messages.RTCDispose; import im.actor.core.modules.calls.peers.messages.RTCMasterAdvertised; import im.actor.core.modules.calls.peers.messages.RTCMediaStateUpdated; import im.actor.core.modules.calls.peers.messages.RTCNeedOffer; import im.actor.core.modules.calls.peers.messages.RTCOffer; import im.actor.core.modules.calls.peers.messages.RTCStart; import im.actor.core.modules.ModuleActor; import im.actor.runtime.Log; import im.actor.runtime.WebRTC; import im.actor.runtime.actors.messages.PoisonPill; import im.actor.runtime.function.CountedReference; import im.actor.runtime.webrtc.WebRTCMediaStream; import im.actor.runtime.webrtc.WebRTCMediaTrack; /** * Manages Connections to all Nodes */ public class PeerCallActor extends ModuleActor { private static final String TAG = "PeerCallActor"; // Parent Actor for handling events private final PeerCallCallback callback; // Peer Settings private final PeerSettings selfSettings; // WebRTC objects private List<ApiICEServer> iceServers; private HashMap<Long, PeerNodeInt> refs = new HashMap<>(); private CountedReference<WebRTCMediaStream> currentMediaStream; private boolean isCurrentStreamAudioRequired; private boolean isCurrentStreamVideoRequired; private boolean isAudioRequired; private boolean isVideoRequired; // State objects private boolean isOwnStarted = false; private boolean isBuildingStream = false; private boolean isAudioEnabled = true; private boolean isVideoEnabled = false; public PeerCallActor(PeerCallCallback callback, PeerSettings selfSettings, ModuleContext context) { super(context); this.callback = callback; this.selfSettings = selfSettings; this.isAudioRequired = true; this.isVideoRequired = false; } // // Media Settings // public void onAudioEnabled(boolean isAudioEnabled) { if (this.isAudioEnabled != isAudioEnabled) { this.isAudioEnabled = isAudioEnabled; if (!isAudioRequired) { isAudioRequired = true; } if (currentMediaStream != null) { for (WebRTCMediaTrack audio : currentMediaStream.get().getAudioTracks()) { audio.setEnabled(isAudioEnabled); if (isAudioEnabled) { callback.onOwnTrackAdded(audio); } else { callback.onOwnTrackRemoved(audio); } } } requestStreamIfNeeded(); for (Long deviceId : refs.keySet()) { callback.onMediaStreamsChanged(deviceId, isAudioEnabled, isVideoEnabled); } } } public void onVideoEnabled(boolean isVideoEnabled) { if (this.isVideoEnabled != isVideoEnabled) { this.isVideoEnabled = isVideoEnabled; if (!isVideoRequired) { isVideoRequired = true; } if (currentMediaStream != null) { for (WebRTCMediaTrack video : currentMediaStream.get().getVideoTracks()) { video.setEnabled(isVideoEnabled); if (isVideoEnabled) { callback.onOwnTrackAdded(video); } else { callback.onOwnTrackRemoved(video); } } } requestStreamIfNeeded(); for (Long deviceId : refs.keySet()) { callback.onMediaStreamsChanged(deviceId, isAudioEnabled, isVideoEnabled); } } } public void onOwnStarted() { if (isOwnStarted) { return; } isOwnStarted = true; requestStreamIfNeeded(); } private void requestStreamIfNeeded() { if (!isBuildingStream && isOwnStarted && ((currentMediaStream == null) || (isCurrentStreamAudioRequired != isAudioRequired) || (isCurrentStreamVideoRequired != isVideoRequired))) { isBuildingStream = true; isCurrentStreamAudioRequired = isAudioRequired; isCurrentStreamVideoRequired = isVideoRequired; WebRTC.getUserMedia(isAudioRequired, isVideoRequired).then(mediaStream -> { isBuildingStream = false; // Checking if required types are not changed if (isCurrentStreamAudioRequired != isAudioRequired || isCurrentStreamVideoRequired != isVideoRequired) { // Closing unwanted media stream mediaStream.close(); requestStreamIfNeeded(); return; } // Update Stream Locally CountedReference<WebRTCMediaStream> newStream = new VerboseReference(mediaStream); CountedReference<WebRTCMediaStream> oldStream = currentMediaStream; currentMediaStream = newStream; // Releasing old stream if (oldStream != null) { if (isAudioEnabled) { for (WebRTCMediaTrack track : oldStream.get().getAudioTracks()) { callback.onOwnTrackRemoved(track); } } if (isVideoEnabled) { for (WebRTCMediaTrack track : oldStream.get().getVideoTracks()) { callback.onOwnTrackRemoved(track); } } oldStream.release(); } // Connecting to a new stream for (WebRTCMediaTrack audio : mediaStream.getAudioTracks()) { audio.setEnabled(isAudioEnabled); if (isAudioEnabled) { callback.onOwnTrackAdded(audio); } } for (WebRTCMediaTrack video : mediaStream.getVideoTracks()) { video.setEnabled(isVideoEnabled); if (isVideoEnabled) { callback.onOwnTrackAdded(video); } } // Update references in all active nodes for (PeerNodeInt node : refs.values()) { node.replaceOwnStream(newStream); } }).failure(e -> { Log.d(TAG, "Unable to load stream"); self().send(PoisonPill.INSTANCE); }); } } public void onMasterAdvertised(List<ApiICEServer> iceServers) { if (this.iceServers == null) { this.iceServers = iceServers; for (PeerNodeInt node : refs.values()) { node.onAdvertisedMaster(iceServers); } } } // // Peer Collection // public PeerNodeInt getPeer(long deviceId) { if (!refs.containsKey(deviceId)) { return createNewPeer(deviceId); } return refs.get(deviceId); } public PeerNodeInt createNewPeer(final long deviceId) { // Creating Peer Node PeerNodeInt peerNodeInt = new PeerNodeInt(deviceId, new NodeCallback(), selfSettings, self(), context()); // Setting Own Stream if available if (currentMediaStream != null) { peerNodeInt.replaceOwnStream(currentMediaStream); } // Set advertise info if available if (this.iceServers != null) { peerNodeInt.onAdvertisedMaster(iceServers); } // Notify new node about current streams configuration callback.onMediaStreamsChanged(deviceId, isAudioEnabled, isVideoEnabled); refs.put(deviceId, peerNodeInt); return peerNodeInt; } public void disposePeer(long deviceId) { PeerNodeInt peerNodeInt = refs.remove(deviceId); if (peerNodeInt != null) { peerNodeInt.kill(); } } @Override public void postStop() { super.postStop(); for (PeerNodeInt d : refs.values()) { d.kill(); } refs.clear(); if (currentMediaStream != null) { if (isAudioEnabled) { for (WebRTCMediaTrack track : currentMediaStream.get().getAudioTracks()) { callback.onOwnTrackRemoved(track); } } if (isVideoEnabled) { for (WebRTCMediaTrack track : currentMediaStream.get().getVideoTracks()) { callback.onOwnTrackRemoved(track); } } currentMediaStream.release(); currentMediaStream = null; } } @Override public void onReceive(Object message) { if (message instanceof RTCStart) { RTCStart start = (RTCStart) message; getPeer(start.getDeviceId()).startConnection(); } else if (message instanceof RTCDispose) { RTCDispose dispose = (RTCDispose) message; disposePeer(dispose.getDeviceId()); } else if (message instanceof RTCOffer) { RTCOffer offer = (RTCOffer) message; getPeer(offer.getDeviceId()).onOffer(offer.getSessionId(), offer.getSdp()); } else if (message instanceof RTCAnswer) { RTCAnswer answer = (RTCAnswer) message; getPeer(answer.getDeviceId()).onAnswer(answer.getSessionId(), answer.getSdp()); } else if (message instanceof RTCCandidate) { RTCCandidate candidate = (RTCCandidate) message; getPeer(candidate.getDeviceId()).onCandidate(candidate.getSessionId(), candidate.getMdpIndex(), candidate.getId(), candidate.getSdp()); } else if (message instanceof RTCNeedOffer) { RTCNeedOffer needOffer = (RTCNeedOffer) message; getPeer(needOffer.getDeviceId()).onOfferNeeded(needOffer.getSessionId()); } else if (message instanceof RTCAdvertised) { RTCAdvertised advertised = (RTCAdvertised) message; getPeer(advertised.getDeviceId()).onAdvertised(advertised.getSettings()); } else if (message instanceof RTCCloseSession) { RTCCloseSession closeSession = (RTCCloseSession) message; getPeer(closeSession.getDeviceId()).closeSession(closeSession.getSessionId()); } else if (message instanceof RTCMediaStateUpdated) { RTCMediaStateUpdated mediaStateUpdated = (RTCMediaStateUpdated) message; getPeer(mediaStateUpdated.getDeviceId()).onMediaStateChanged(mediaStateUpdated.isAudioEnabled(), mediaStateUpdated.isVideoEnabled()); } else if (message instanceof RTCMasterAdvertised) { RTCMasterAdvertised masterAdvertised = (RTCMasterAdvertised) message; onMasterAdvertised(masterAdvertised.getIceServers()); } else if (message instanceof AudioEnabled) { AudioEnabled muteChanged = (AudioEnabled) message; onAudioEnabled(muteChanged.isEnabled()); } else if (message instanceof VideoEnabled) { VideoEnabled videoEnabled = (VideoEnabled) message; onVideoEnabled(videoEnabled.isEnabled()); } else if (message instanceof OwnStarted) { onOwnStarted(); } else { super.onReceive(message); } } public static class AudioEnabled { private boolean isEnabled; public AudioEnabled(boolean isEnabled) { this.isEnabled = isEnabled; } public boolean isEnabled() { return isEnabled; } } public static class VideoEnabled { private boolean enabled; public VideoEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled; } } public static class OwnStarted { } private class NodeCallback implements PeerNodeCallback { @Override public void onOffer(long deviceId, long sessionId, String sdp) { callback.onOffer(deviceId, sessionId, sdp); } @Override public void onAnswer(long deviceId, long sessionId, String sdp) { callback.onAnswer(deviceId, sessionId, sdp); } @Override public void onNegotiationSuccessful(long deviceId, long sessionId) { callback.onNegotiationSuccessful(deviceId, sessionId); } @Override public void onNegotiationNeeded(long deviceId, long sessionId) { callback.onNegotiationNeeded(deviceId, sessionId); } @Override public void onCandidate(long deviceId, long sessionId, int mdpIndex, String id, String sdp) { callback.onCandidate(deviceId, sessionId, mdpIndex, id, sdp); } @Override public void onPeerStateChanged(long deviceId, PeerState state) { callback.onPeerStateChanged(deviceId, state); } @Override public void onTrackAdded(long deviceId, WebRTCMediaTrack track) { callback.onTrackAdded(deviceId, track); } @Override public void onTrackRemoved(long deviceId, WebRTCMediaTrack track) { callback.onTrackRemoved(deviceId, track); } } private static int referenceId = 0; private static class VerboseReference extends CountedReference<WebRTCMediaStream> { private int id = referenceId++; public VerboseReference(WebRTCMediaStream value) { super(value); } @Override public synchronized void acquire(int counter) { Log.d("CountedReference(" + id + ")", "acquire(" + counter + ")"); } @Override public synchronized void release(int counter) { Log.d("CountedReference(" + id + ")", "release(" + counter + ")"); } } }
EaglesoftZJ/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/calls/peers/PeerCallActor.java
Java
agpl-3.0
14,440
/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved. */ package org.pentaho.agilebi.modeler.nodes; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.pentaho.agilebi.modeler.ModelerException; import org.pentaho.agilebi.modeler.ModelerMessagesHolder; import org.pentaho.agilebi.modeler.ModelerWorkspace; import org.pentaho.agilebi.modeler.propforms.MainModelerNodePropertiesForm; import org.pentaho.ui.xul.stereotype.Bindable; public class MainModelNode extends AbstractMetaDataModelNode<AbstractMetaDataModelNode> implements IRootModelNode { private static final long serialVersionUID = 2399128598598210134L; String name = "Untitled"; // BaseMessages.getString(ModelerWorkspace.class, "Main.Model.Name.Untitled"); private MeasuresCollection measures = new MeasuresCollection(); private DimensionMetaDataCollection dimensions = new DimensionMetaDataCollection(); private transient PropertyChangeListener listener; private ModelerWorkspace workspace; private static final String CLASSNAME = "pentaho-smallmodelbutton"; public MainModelNode() { super( CLASSNAME ); add( measures ); add( dimensions ); setExpanded( true ); dimensions.setExpanded( true ); } public MainModelNode( ModelerWorkspace workspace ) { this(); this.workspace = workspace; } @Bindable public String getName() { return name; } @Bindable public String getDisplayName() { return ModelerMessagesHolder.getMessages().getString( "Main.Model.Name.Template", getName() ); //$NON-NLS-1$ // return ModelerController.MESSAGES.getString("Main.Model.Name.Template", getName()); } @Bindable public void setName( String name ) { if ( !name.equals( this.name ) ) { String oldName = this.name; String prevDisplay = getDisplayName(); this.name = name; this.firePropertyChange( "name", oldName, this.name ); //$NON-NLS-1$ this.firePropertyChange( "displayName", prevDisplay, getName() ); //BaseMessages.getString(ModelerWorkspace.class, "Main.Model.Name.Template", getName())); //$NON-NLS-1$ validateNode(); } } @Bindable public String getImage() { return "images/sm_model_icon.png"; //$NON-NLS-1$ } @Bindable public boolean isUiExpanded() { return true; } protected void fireCollectionChanged() { this.changeSupport.firePropertyChange( "children", null, this ); //$NON-NLS-1$ } @Override public void onAdd( AbstractMetaDataModelNode child ) { child.addPropertyChangeListener( "children", getListener() ); //$NON-NLS-1$ child.addPropertyChangeListener( "valid", validListener ); //$NON-NLS-1$ } @Override public void onRemove( AbstractMetaDataModelNode child ) { child.removePropertyChangeListener( getListener() ); child.removePropertyChangeListener( validListener ); } public DimensionMetaDataCollection getDimensions() { return dimensions; } public MeasuresCollection getMeasures() { return measures; } @Bindable public boolean isEditingDisabled() { return true; } @Override public Class<MainModelerNodePropertiesForm> getPropertiesForm() { return MainModelerNodePropertiesForm.class; } @Override @Bindable public String getValidImage() { return getImage(); } @Override public void validate() { valid = true; this.validationMessages.clear(); if ( "".equals( this.getName() ) ) { valid = false; this.validationMessages.add( "Node is emtpy" ); //BaseMessages.getString(ModelerWorkspace.class, "MainModelNode.ModelNameEmpty")); //$NON-NLS-1$ } if ( this.children.size() != 2 ) { valid = false; this.validationMessages.add( "Invalid Structure" ); //BaseMessages.getString(ModelerWorkspace.class, "MainModelNode.ModelStructureInvalid")); //$NON-NLS-1$ } for ( AbstractMetaDataModelNode child : children ) { valid &= child.isValid(); this.validationMessages.addAll( child.getValidationMessages() ); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ( ( dimensions == null ) ? 0 : dimensions.hashCode() ); result = prime * result + ( ( listener == null ) ? 0 : listener.hashCode() ); result = prime * result + ( ( measures == null ) ? 0 : measures.hashCode() ); result = prime * result + ( ( name == null ) ? 0 : name.hashCode() ); return result; } public boolean equals( MainModelNode obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } MainModelNode other = obj; if ( dimensions == null ) { if ( other.dimensions != null ) { return false; } } else if ( !dimensions.equals( other.dimensions ) ) { return false; } if ( listener == null ) { if ( other.listener != null ) { return false; } } else if ( !listener.equals( other.listener ) ) { return false; } if ( measures == null ) { if ( other.measures != null ) { return false; } } else if ( !measures.equals( other.measures ) ) { return false; } if ( name == null ) { if ( other.name != null ) { return false; } } else if ( !name.equals( other.name ) ) { return false; } return true; } private PropertyChangeListener getListener() { if ( listener == null ) { listener = new PropertyChangeListener() { public void propertyChange( PropertyChangeEvent evt ) { if ( !suppressEvents ) { fireCollectionChanged(); } } }; } return listener; } public void setSupressEvents( boolean suppress ) { super.setSupressEvents( suppress ); if ( !suppress ) { firePropertyChange( "valid", !isValid(), isValid() ); } } public boolean getSuppressEvents() { return suppressEvents; } @Override public boolean acceptsDrop( Object obj ) { return false; } @Override public Object onDrop( Object data ) throws ModelerException { throw new ModelerException( new IllegalArgumentException( ModelerMessagesHolder.getMessages().getString( "invalid_drop" ) ) ); } @Override public ModelerWorkspace getWorkspace() { return workspace; } public void setWorkspace( ModelerWorkspace workspace ) { this.workspace = workspace; } }
bytekast/modeler
src/org/pentaho/agilebi/modeler/nodes/MainModelNode.java
Java
lgpl-2.1
7,272
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.server.group; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.Externalizer; import org.wildfly.clustering.marshalling.spi.Formatter; import org.wildfly.clustering.marshalling.spi.StringExternalizer; /** * Resolver for a {@link LocalNode}. * @author Paul Ferraro */ @MetaInfServices(Formatter.class) public class LocalNodeFormatter implements Formatter<LocalNode> { @Override public Class<LocalNode> getTargetClass() { return LocalNode.class; } @Override public LocalNode parse(String name) { return new LocalNode(name); } @Override public String format(LocalNode node) { return node.getName(); } @MetaInfServices(Externalizer.class) public static class LocalNodeExternalizer extends StringExternalizer<LocalNode> { public LocalNodeExternalizer() { super(new LocalNodeFormatter()); } } }
iweiss/wildfly
clustering/server/src/main/java/org/wildfly/clustering/server/group/LocalNodeFormatter.java
Java
lgpl-2.1
1,981
/* * $Id: LaserConsoleException.java,v 1.2 2006/09/25 08:52:36 acaproni Exp $ * * $Date: 2006/09/25 08:52:36 $ * $Revision: 1.2 $ * $Author: acaproni $ * * Copyright CERN, All Rights Reserved. */ package cern.laser.console; import cern.laser.client.LaserException; /** Laser console exception. */ public class LaserConsoleException extends LaserException { /** Default constructor. */ public LaserConsoleException() { super(); } /** Constructor. Build a new exception and set the message. * @param message the message */ public LaserConsoleException(String message) { super(message); } /** Constructor. Build a new exception and set the message and the root * exception. * @param message the message * @param rootCause the root exception */ public LaserConsoleException(String message, Throwable rootCause) { super(message, rootCause); } }
jbarriosc/ACSUFRO
LGPL/CommonSoftware/ACSLaser/laser-console/src/cern/laser/console/LaserConsoleException.java
Java
lgpl-2.1
913
package alma.acs.monitoring; import java.util.ArrayList; import java.util.List; /** * Holds the value(s) of a logical monitor point at one instant of time. */ public class MonitorPointValue { /** * Timestamp of the data. */ private final long time; /** * The data list. * Contains one Number, Boolean, String etc object for a single-valued monitor point, * or several such objects for a multi-valued monitor point. */ private final List<Object> data = new ArrayList<Object>(); public MonitorPointValue(long time) { this.time = time; } public void addValue(Object value) { data.add(value); } public long getTime() { return time; } /** * Gets the data list that contains a single Number, Boolean, String etc object for a single-valued monitor point, * or several such objects for a multi-valued monitor point. */ public List<Object> getData() { return data; } public boolean isMultiValued() { return (data.size() > 1); } }
jbarriosc/ACSUFRO
LGPL/CommonSoftware/monitoring/monicd/ws/src/alma/acs/monitoring/MonitorPointValue.java
Java
lgpl-2.1
984
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGPropeller.cpp Author: Jon S. Berndt Date started: 08/24/00 Purpose: Encapsulates the propeller object ------------- Copyright (C) 2000 Jon S. Berndt (jon@jsbsim.org) ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- HISTORY -------------------------------------------------------------------------------- 08/24/00 JSB Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include <iostream> #include <sstream> #include "FGPropeller.h" #include "input_output/FGXMLElement.h" using namespace std; namespace JSBSim { static const char *IdSrc = "$Id: FGPropeller.cpp,v 1.46 2013/01/06 22:11:42 jentron Exp $"; static const char *IdHdr = ID_PROPELLER; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ // This class currently makes certain assumptions when calculating torque and // p-factor. That is, that the axis of rotation is the X axis of the aircraft - // not just the X-axis of the engine/propeller. This may or may not work for a // helicopter. FGPropeller::FGPropeller(FGFDMExec* exec, Element* prop_element, int num) : FGThruster(exec, prop_element, num) { string token; Element *table_element, *local_element; string name=""; FGPropertyManager* PropertyManager = exec->GetPropertyManager(); MaxPitch = MinPitch = P_Factor = Pitch = Advance = MinRPM = MaxRPM = 0.0; Sense = 1; // default clockwise rotation ReversePitch = 0.0; Reversed = false; Feathered = false; Reverse_coef = 0.0; GearRatio = 1.0; CtFactor = CpFactor = 1.0; ConstantSpeed = 0; cThrust = cPower = CtMach = CpMach = 0; Vinduced = 0.0; if (prop_element->FindElement("ixx")) Ixx = prop_element->FindElementValueAsNumberConvertTo("ixx", "SLUG*FT2"); if (prop_element->FindElement("diameter")) Diameter = prop_element->FindElementValueAsNumberConvertTo("diameter", "FT"); if (prop_element->FindElement("numblades")) numBlades = (int)prop_element->FindElementValueAsNumber("numblades"); if (prop_element->FindElement("gearratio")) GearRatio = prop_element->FindElementValueAsNumber("gearratio"); if (prop_element->FindElement("minpitch")) MinPitch = prop_element->FindElementValueAsNumber("minpitch"); if (prop_element->FindElement("maxpitch")) MaxPitch = prop_element->FindElementValueAsNumber("maxpitch"); if (prop_element->FindElement("minrpm")) MinRPM = prop_element->FindElementValueAsNumber("minrpm"); if (prop_element->FindElement("maxrpm")) { MaxRPM = prop_element->FindElementValueAsNumber("maxrpm"); ConstantSpeed = 1; } if (prop_element->FindElement("constspeed")) ConstantSpeed = (int)prop_element->FindElementValueAsNumber("constspeed"); if (prop_element->FindElement("reversepitch")) ReversePitch = prop_element->FindElementValueAsNumber("reversepitch"); while((table_element = prop_element->FindNextElement("table")) != 0) { name = table_element->GetAttributeValue("name"); try { if (name == "C_THRUST") { cThrust = new FGTable(PropertyManager, table_element); } else if (name == "C_POWER") { cPower = new FGTable(PropertyManager, table_element); } else if (name == "CT_MACH") { CtMach = new FGTable(PropertyManager, table_element); } else if (name == "CP_MACH") { CpMach = new FGTable(PropertyManager, table_element); } else { cerr << "Unknown table type: " << name << " in propeller definition." << endl; } } catch (std::string str) { throw("Error loading propeller table:" + name + ". " + str); } } if( (cPower == 0) || (cThrust == 0)){ cerr << "Propeller configuration must contain C_THRUST and C_POWER tables!" << endl; } local_element = prop_element->GetParent()->FindElement("sense"); if (local_element) { double Sense = local_element->GetDataAsNumber(); SetSense(Sense >= 0.0 ? 1.0 : -1.0); } local_element = prop_element->GetParent()->FindElement("p_factor"); if (local_element) { P_Factor = local_element->GetDataAsNumber(); } if (P_Factor < 0) { cerr << "P-Factor value in propeller configuration file must be greater than zero" << endl; } if (prop_element->FindElement("ct_factor")) SetCtFactor( prop_element->FindElementValueAsNumber("ct_factor") ); if (prop_element->FindElement("cp_factor")) SetCpFactor( prop_element->FindElementValueAsNumber("cp_factor") ); Type = ttPropeller; RPM = 0; vTorque.InitMatrix(); D4 = Diameter*Diameter*Diameter*Diameter; D5 = D4*Diameter; Pitch = MinPitch; string property_name, base_property_name; base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNum); property_name = base_property_name + "/engine-rpm"; PropertyManager->Tie( property_name.c_str(), this, &FGPropeller::GetEngineRPM ); property_name = base_property_name + "/advance-ratio"; PropertyManager->Tie( property_name.c_str(), &J ); property_name = base_property_name + "/blade-angle"; PropertyManager->Tie( property_name.c_str(), &Pitch ); property_name = base_property_name + "/thrust-coefficient"; PropertyManager->Tie( property_name.c_str(), this, &FGPropeller::GetThrustCoefficient ); property_name = base_property_name + "/propeller-rpm"; PropertyManager->Tie( property_name.c_str(), this, &FGPropeller::GetRPM ); property_name = base_property_name + "/helical-tip-Mach"; PropertyManager->Tie( property_name.c_str(), this, &FGPropeller::GetHelicalTipMach ); property_name = base_property_name + "/constant-speed-mode"; PropertyManager->Tie( property_name.c_str(), this, &FGPropeller::GetConstantSpeed, &FGPropeller::SetConstantSpeed ); property_name = base_property_name + "/prop-induced-velocity_fps"; PropertyManager->Tie( property_name.c_str(), this, &FGPropeller::GetInducedVelocity, &FGPropeller::SetInducedVelocity ); Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGPropeller::~FGPropeller() { delete cThrust; delete cPower; delete CtMach; delete CpMach; Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // // We must be getting the aerodynamic velocity here, NOT the inertial velocity. // We need the velocity with respect to the wind. // // Remembering that Torque * omega = Power, we can derive the torque on the // propeller and its acceleration to give a new RPM. The current RPM will be // used to calculate thrust. // // Because RPM could be zero, we need to be creative about what RPM is stated as. double FGPropeller::Calculate(double EnginePower) { FGColumnVector3 localAeroVel = Transform().Transposed() * in.AeroUVW; double omega, PowerAvailable; double Vel = localAeroVel(eU); double rho = in.Density; double RPS = RPM/60.0; // Calculate helical tip Mach double Area = 0.25*Diameter*Diameter*M_PI; double Vtip = RPS * Diameter * M_PI; HelicalTipMach = sqrt(Vtip*Vtip + Vel*Vel) / in.Soundspeed; PowerAvailable = EnginePower - GetPowerRequired(); if (RPS > 0.0) J = Vel / (Diameter * RPS); // Calculate J normally else J = Vel / Diameter; if (MaxPitch == MinPitch) { // Fixed pitch prop ThrustCoeff = cThrust->GetValue(J); } else { // Variable pitch prop ThrustCoeff = cThrust->GetValue(J, Pitch); } // Apply optional scaling factor to Ct (default value = 1) ThrustCoeff *= CtFactor; // Apply optional Mach effects from CT_MACH table if (CtMach) ThrustCoeff *= CtMach->GetValue(HelicalTipMach); Thrust = ThrustCoeff*RPS*RPS*D4*rho; // Induced velocity in the propeller disk area. This formula is obtained // from momentum theory - see B. W. McCormick, "Aerodynamics, Aeronautics, // and Flight Mechanics" 1st edition, eqn. 6.15 (propeller analysis chapter). // Since Thrust and Vel can both be negative we need to adjust this formula // To handle sign (direction) separately from magnitude. double Vel2sum = Vel*abs(Vel) + 2.0*Thrust/(rho*Area); if( Vel2sum > 0.0) Vinduced = 0.5 * (-Vel + sqrt(Vel2sum)); else Vinduced = 0.5 * (-Vel - sqrt(-Vel2sum)); // We need to drop the case where the downstream velocity is opposite in // direction to the aircraft velocity. For example, in such a case, the // direction of the airflow on the tail would be opposite to the airflow on // the wing tips. When such complicated airflows occur, the momentum theory // breaks down and the formulas above are no longer applicable // (see H. Glauert, "The Elements of Airfoil and Airscrew Theory", // 2nd edition, §16.3, pp. 219-221) if ((Vel+2.0*Vinduced)*Vel < 0.0) { // The momentum theory is no longer applicable so let's assume the induced // saturates to -0.5*Vel so that the total velocity Vel+2*Vinduced equals 0. Vinduced = -0.5*Vel; } // P-factor is simulated by a shift of the acting location of the thrust. // The shift is a multiple of the angle between the propeller shaft axis // and the relative wind that goes through the propeller disk. if (P_Factor > 0.0001) { double tangentialVel = localAeroVel.Magnitude(eV, eW); if (tangentialVel > 0.0001) { double angle = atan2(tangentialVel, localAeroVel(eU)); double factor = Sense * P_Factor * angle / tangentialVel; SetActingLocationY( GetLocationY() + factor * localAeroVel(eW)); SetActingLocationZ( GetLocationZ() + factor * localAeroVel(eV)); } } omega = RPS*2.0*M_PI; vFn(eX) = Thrust; // The Ixx value and rotation speed given below are for rotation about the // natural axis of the engine. The transform takes place in the base class // FGForce::GetBodyForces() function. vH(eX) = Ixx*omega*Sense; vH(eY) = 0.0; vH(eZ) = 0.0; if (omega > 0.0) ExcessTorque = PowerAvailable / omega; else ExcessTorque = PowerAvailable / 1.0; RPM = (RPS + ((ExcessTorque / Ixx) / (2.0 * M_PI)) * deltaT) * 60.0; if (RPM < 0.0) RPM = 0.0; // Engine won't turn backwards // Transform Torque and momentum first, as PQR is used in this // equation and cannot be transformed itself. vMn = in.PQR*(Transform()*vH) + Transform()*vTorque; return Thrust; // return thrust in pounds } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGPropeller::GetPowerRequired(void) { double cPReq, J; double rho = in.Density; double Vel = in.AeroUVW(eU); double RPS = RPM / 60.0; if (RPS != 0.0) J = Vel / (Diameter * RPS); else J = Vel / Diameter; if (MaxPitch == MinPitch) { // Fixed pitch prop cPReq = cPower->GetValue(J); } else { // Variable pitch prop if (ConstantSpeed != 0) { // Constant Speed Mode // do normal calculation when propeller is neither feathered nor reversed // Note: This method of feathering and reversing was added to support the // turboprop model. It's left here for backward compatablity, but // now feathering and reversing should be done in Manual Pitch Mode. if (!Feathered) { if (!Reversed) { double rpmReq = MinRPM + (MaxRPM - MinRPM) * Advance; double dRPM = rpmReq - RPM; // The pitch of a variable propeller cannot be changed when the RPMs are // too low - the oil pump does not work. if (RPM > 200) Pitch -= dRPM * deltaT; if (Pitch < MinPitch) Pitch = MinPitch; else if (Pitch > MaxPitch) Pitch = MaxPitch; } else { // Reversed propeller // when reversed calculate propeller pitch depending on throttle lever position // (beta range for taxing full reverse for braking) double PitchReq = MinPitch - ( MinPitch - ReversePitch ) * Reverse_coef; // The pitch of a variable propeller cannot be changed when the RPMs are // too low - the oil pump does not work. if (RPM > 200) Pitch += (PitchReq - Pitch) / 200; if (RPM > MaxRPM) { Pitch += (MaxRPM - RPM) / 50; if (Pitch < ReversePitch) Pitch = ReversePitch; else if (Pitch > MaxPitch) Pitch = MaxPitch; } } } else { // Feathered propeller // ToDo: Make feathered and reverse settings done via FGKinemat Pitch += (MaxPitch - Pitch) / 300; // just a guess (about 5 sec to fully feathered) } } else { // Manual Pitch Mode, pitch is controlled externally } cPReq = cPower->GetValue(J, Pitch); } // Apply optional scaling factor to Cp (default value = 1) cPReq *= CpFactor; // Apply optional Mach effects from CP_MACH table if (CpMach) cPReq *= CpMach->GetValue(HelicalTipMach); double local_RPS = RPS < 0.01 ? 0.01 : RPS; PowerRequired = cPReq*local_RPS*RPS*local_RPS*D5*rho; vTorque(eX) = -Sense*PowerRequired / (local_RPS*2.0*M_PI); return PowerRequired; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGColumnVector3 FGPropeller::GetPFactor() const { double px=0.0, py, pz; py = Thrust * Sense * (GetActingLocationY() - GetLocationY()) / 12.0; pz = Thrust * Sense * (GetActingLocationZ() - GetLocationZ()) / 12.0; return FGColumnVector3(px, py, pz); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropeller::GetThrusterLabels(int id, const string& delimeter) { std::ostringstream buf; buf << Name << " Torque (engine " << id << ")" << delimeter << Name << " PFactor Pitch (engine " << id << ")" << delimeter << Name << " PFactor Yaw (engine " << id << ")" << delimeter << Name << " Thrust (engine " << id << " in lbs)" << delimeter; if (IsVPitch()) buf << Name << " Pitch (engine " << id << ")" << delimeter; buf << Name << " RPM (engine " << id << ")"; return buf.str(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropeller::GetThrusterValues(int id, const string& delimeter) { std::ostringstream buf; FGColumnVector3 vPFactor = GetPFactor(); buf << vTorque(eX) << delimeter << vPFactor(ePitch) << delimeter << vPFactor(eYaw) << delimeter << Thrust << delimeter; if (IsVPitch()) buf << Pitch << delimeter; buf << RPM; return buf.str(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print // out the normally expected messages, essentially echoing // the config files as they are read. If the environment // variable is not set, debug_lvl is set to 1 internally // 0: This requests JSBSim not to output any messages // whatsoever. // 1: This value explicity requests the normal JSBSim // startup messages // 2: This value asks for a message to be printed out when // a class is instantiated // 4: When this value is set, a message is displayed when a // FGModel object executes its Run() method // 8: When this value is set, various runtime state variables // are printed out periodically // 16: When set various parameters are sanity checked and // a message is printed out when they go out of bounds void FGPropeller::Debug(int from) { if (debug_lvl <= 0) return; if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor cout << "\n Propeller Name: " << Name << endl; cout << " IXX = " << Ixx << endl; cout << " Diameter = " << Diameter << " ft." << endl; cout << " Number of Blades = " << numBlades << endl; cout << " Gear Ratio = " << GearRatio << endl; cout << " Minimum Pitch = " << MinPitch << endl; cout << " Maximum Pitch = " << MaxPitch << endl; cout << " Minimum RPM = " << MinRPM << endl; cout << " Maximum RPM = " << MaxRPM << endl; // Tables are being printed elsewhere... // cout << " Thrust Coefficient: " << endl; // cThrust->Print(); // cout << " Power Coefficient: " << endl; // cPower->Print(); // cout << " Mach Thrust Coefficient: " << endl; // if(CtMach) // { // CtMach->Print(); // } else { // cout << " NONE" << endl; // } // cout << " Mach Power Coefficient: " << endl; // if(CpMach) // { // CpMach->Print(); // } else { // cout << " NONE" << endl; // } } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification if (from == 0) cout << "Instantiated: FGPropeller" << endl; if (from == 1) cout << "Destroyed: FGPropeller" << endl; } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } if (debug_lvl & 8 ) { // Runtime state variables } if (debug_lvl & 16) { // Sanity checking } if (debug_lvl & 64) { if (from == 0) { // Constructor cout << IdSrc << endl; cout << IdHdr << endl; } } } }
adrcad/jsbsim
src/models/propulsion/FGPropeller.cpp
C++
lgpl-2.1
18,356
/*************************************************************************** * Copyright (c) 2017 Abdullah Tahiri <abdullah.tahiri.yo@gmail.com> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <cfloat> # include <QMessageBox> # include <Precision.hxx> # include <QApplication> # include <Standard_Version.hxx> # include <QMessageBox> #endif #include <Base/Console.h> #include <App/Application.h> #include <Gui/Application.h> #include <Gui/Document.h> #include <Gui/Selection.h> #include <Gui/CommandT.h> #include <Gui/MainWindow.h> #include <Gui/DlgEditFileIncludePropertyExternal.h> #include <Gui/Action.h> #include <Gui/BitmapFactory.h> #include "ViewProviderSketch.h" #include "DrawSketchHandler.h" #include <Mod/Part/App/Geometry.h> #include <Mod/Sketcher/App/SketchObject.h> #include "CommandConstraints.h" using namespace std; using namespace SketcherGui; using namespace Sketcher; bool isSketcherVirtualSpaceActive(Gui::Document *doc, bool actsOnSelection ) { if (doc) { // checks if a Sketch Viewprovider is in Edit and is in no special mode if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { if (static_cast<SketcherGui::ViewProviderSketch*>(doc->getInEdit())->getSketchMode() == ViewProviderSketch::STATUS_NONE) { if (!actsOnSelection) return true; else if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0) return true; } } } return false; } void ActivateVirtualSpaceHandler(Gui::Document *doc, DrawSketchHandler *handler) { if (doc) { if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { SketcherGui::ViewProviderSketch* vp = static_cast<SketcherGui::ViewProviderSketch*>(doc->getInEdit()); vp->purgeHandler(); vp->activateHandler(handler); } } } // Show/Hide B-spline degree DEF_STD_CMD_A(CmdSketcherSwitchVirtualSpace) CmdSketcherSwitchVirtualSpace::CmdSketcherSwitchVirtualSpace() : Command("Sketcher_SwitchVirtualSpace") { sAppModule = "Sketcher"; sGroup = QT_TR_NOOP("Sketcher"); sMenuText = QT_TR_NOOP("Switch virtual space"); sToolTipText = QT_TR_NOOP("Switches the selected constraints or the view to the other virtual space"); sWhatsThis = "Sketcher_SwitchVirtualSpace"; sStatusTip = sToolTipText; sPixmap = "Sketcher_SwitchVirtualSpace"; sAccel = ""; eType = ForEdit; } void CmdSketcherSwitchVirtualSpace::activated(int iMsg) { Q_UNUSED(iMsg); bool modeChange = true; std::vector<Gui::SelectionObject> selection; if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0) { // Now we check whether we have a constraint selected or not. selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("Select constraint(s) from the sketch.")); return; } // get the needed lists and objects const std::vector<std::string> &SubNames = selection[0].getSubNames(); if (SubNames.empty()) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("Select constraint(s) from the sketch.")); return; } for (std::vector<std::string>::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { // see if we have constraints, if we do it is not a mode change, but a toggle. if (it->size() > 10 && it->substr(0, 10) == "Constraint") modeChange = false; } } if (modeChange) { Gui::Document * doc = getActiveGuiDocument(); SketcherGui::ViewProviderSketch* vp = static_cast<SketcherGui::ViewProviderSketch*>(doc->getInEdit()); vp->setIsShownVirtualSpace(!vp->getIsShownVirtualSpace()); } // toggle the selected constraint(s) else { // get the needed lists and objects const std::vector<std::string> &SubNames = selection[0].getSubNames(); if (SubNames.empty()) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("Select constraint(s) from the sketch.")); return; } SketcherGui::ViewProviderSketch* sketchgui = static_cast<SketcherGui::ViewProviderSketch*>(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Toggle constraints to the other virtual space")); int successful = SubNames.size(); // go through the selected subelements for (std::vector<std::string>::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { // only handle constraints if (it->size() > 10 && it->substr(0,10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(*it); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Update constraint's virtual space")); try { Gui::cmdAppObjectArgs(Obj, "toggleVirtualSpace(%d)", ConstrId); } catch (const Base::Exception&) { successful--; } } } if (successful > 0) commitCommand(); else abortCommand(); // recomputer and clear the selection (convenience) tryAutoRecompute(Obj); getSelection().clearSelection(); } } bool CmdSketcherSwitchVirtualSpace::isActive(void) { return isSketcherVirtualSpaceActive(getActiveGuiDocument(), false); } void CreateSketcherCommandsVirtualSpace(void) { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdSketcherSwitchVirtualSpace()); }
Fat-Zer/FreeCAD_sf_master
src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp
C++
lgpl-2.1
7,905
/* * Hibernate OGM, Domain model persistence for NoSQL datastores * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.ogm.datastore.infinispan.test.dialect.impl; import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.assertTrue; import org.hibernate.ogm.datastore.infinispan.persistencestrategy.kind.externalizer.impl.IdSourceKeyExternalizer; import org.hibernate.ogm.model.impl.DefaultIdSourceKeyMetadata; import org.hibernate.ogm.model.key.spi.IdSourceKey; import org.hibernate.ogm.model.key.spi.IdSourceKeyMetadata; import org.junit.Before; import org.junit.Test; /** * Unit test for {@link IdSourceKeyExternalizer}. * * @author Gunnar Morling */ public class IdSourceKeyExternalizerTest { private ExternalizerTestHelper<IdSourceKey, IdSourceKeyExternalizer> externalizerHelper; @Before public void setupMarshallerFactory() { externalizerHelper = ExternalizerTestHelper.getInstance( IdSourceKeyExternalizer.INSTANCE ); } @Test public void shouldSerializeAndDeserializeRowKey() throws Exception { IdSourceKeyMetadata keyMetadata = DefaultIdSourceKeyMetadata.forTable( "Hibernate_Sequences", "sequence_name", "next_val" ); // given IdSourceKey key = IdSourceKey.forTable( keyMetadata, "Foo_Sequence" ); // when byte[] bytes = externalizerHelper.marshall( key ); IdSourceKey unmarshalledKey = externalizerHelper.unmarshall( bytes ); // then assertThat( unmarshalledKey.getTable() ).isEqualTo( key.getTable() ); assertThat( unmarshalledKey.getColumnName() ).isEqualTo( key.getColumnName() ); assertThat( unmarshalledKey.getColumnValue() ).isEqualTo( key.getColumnValue() ); assertTrue( key.equals( unmarshalledKey ) ); assertTrue( unmarshalledKey.equals( key ) ); assertThat( unmarshalledKey.hashCode() ).isEqualTo( key.hashCode() ); } }
schernolyas/hibernate-ogm
infinispan/src/test/java/org/hibernate/ogm/datastore/infinispan/test/dialect/impl/IdSourceKeyExternalizerTest.java
Java
lgpl-2.1
1,967
/* * Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). * Contact: http://www.qt-project.org/legal * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include "ecntviewcount1_cstep.h" //TO BE SAFE IMPORT_C TInt StartDialogThread(); CECntViewCount1Step::CECntViewCount1Step() /** Each test step initialises it's own name */ { // store the name of this test case // this is the name that is used by the script file //DEF iTestStepName = _L("CECntViewCount1Step"); //The server name and IPC number is obtained and all messages are checked Sync SR_ServerName = _L("CNTSRV"); SR_MESSAGE_TYPE = 2; SR_MESSAGE_ID = 5; SR_MESSAGE_MASK = 2147483648LL; //The iServer_Panic is a unique name from Server,but always truncated to KMaxExitCategoryName iServer_Panic = _L("CNTMODEL"); TCapability cap[] = {ECapability_None, ECapability_Limit}; TSecurityInfo info; info.Set(RProcess()); TBool result = EFalse; for (TInt i = 0; cap[i] != ECapability_Limit; i++) { if (!(info.iCaps.HasCapability(cap[i]))) { result=ETrue; } } iExpect_Rejection = result; iStepCap = 2147483648LL; //Get a unique thread name ChildThread_SR.Format(_L("ChildThread_%S_%d"),&SR_ServerName,SR_MESSAGE_ID); } /* Exec_SendReceive(): This Fn is called by the Child Thread 1. Create a session with the server 2. Test an SendReceive call 3. Informs the main thread about the status of the call using a. iSessionCreated, if the a connection is established b. iResult_Server, holds the return value for connection c. iResult_SR, the return value of SendReceive call */ TInt CECntViewCount1Step::Exec_SendReceive() { iResult_Server = CreateSession(SR_ServerName,Version(),2); if (iResult_Server!=KErrNone) { iResult_Server=StartServer(); if (iResult_Server!=KErrNone) return(iResult_Server); iResult_Server = CreateSession(SR_ServerName,TVersion(),2); } if(iResult_Server == 0) { iSessionCreated = ETrue; if(SR_MESSAGE_ID >= 0) iResult_SR = SendReceive(SR_MESSAGE_ID,TIpcArgs(0,0,0,0)); } return iResult_Server; }
enthought/qt-mobility
plugins/contacts/symbian/contactsmodel/tsrc/integration/tcntpolice/srcsql/ecntviewcount1_cstep.cpp
C++
lgpl-2.1
2,372
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "PorousFlowDarcyVelocityComponent.h" template <> InputParameters validParams<PorousFlowDarcyVelocityComponent>() { InputParameters params = validParams<AuxKernel>(); params.addRequiredParam<RealVectorValue>("gravity", "Gravitational acceleration vector downwards (m/s^2)"); params.addRequiredParam<UserObjectName>( "PorousFlowDictator", "The UserObject that holds the list of PorousFlow variable names"); params.addParam<unsigned int>("fluid_phase", 0, "The index corresponding to the fluid phase"); MooseEnum component("x=0 y=1 z=2"); params.addRequiredParam<MooseEnum>( "component", component, "The spatial component of the Darcy flux to return"); params.addClassDescription("Darcy velocity (in m^3.s^-1.m^-2, or m.s^-1) -(k_ij * krel /mu " "(nabla_j P - w_j)), where k_ij is the permeability tensor, krel is " "the relative permeability, mu is the fluid viscosity, P is the fluid " "pressure, and w_j is the fluid weight."); return params; } PorousFlowDarcyVelocityComponent::PorousFlowDarcyVelocityComponent( const InputParameters & parameters) : AuxKernel(parameters), _relative_permeability( getMaterialProperty<std::vector<Real>>("PorousFlow_relative_permeability_qp")), _fluid_viscosity(getMaterialProperty<std::vector<Real>>("PorousFlow_viscosity_qp")), _permeability(getMaterialProperty<RealTensorValue>("PorousFlow_permeability_qp")), _grad_p(getMaterialProperty<std::vector<RealGradient>>("PorousFlow_grad_porepressure_qp")), _fluid_density_qp(getMaterialProperty<std::vector<Real>>("PorousFlow_fluid_phase_density_qp")), _dictator(getUserObject<PorousFlowDictator>("PorousFlowDictator")), _ph(getParam<unsigned int>("fluid_phase")), _component(getParam<MooseEnum>("component")), _gravity(getParam<RealVectorValue>("gravity")) { if (_ph >= _dictator.numPhases()) mooseError( "The Dictator proclaims that the number of phases in this simulation is ", _dictator.numPhases(), " whereas you have used the AuxKernel PorousFlowDarcyVelocityComponent with fluid_phase = ", _ph, ". The Dictator is watching you, to ensure your wellbeing."); } Real PorousFlowDarcyVelocityComponent::computeValue() { // note that in the following, _relative_permeaility and _fluid_viscosity are upwinded (nodal) // values return -(_permeability[_qp] * (_grad_p[_qp][_ph] - _fluid_density_qp[_qp][_ph] * _gravity) * _relative_permeability[_qp][_ph] / _fluid_viscosity[_qp][_ph])(_component); }
Chuban/moose
modules/porous_flow/src/auxkernels/PorousFlowDarcyVelocityComponent.C
C++
lgpl-2.1
3,535
/* * #%L * Alfresco greenmail implementation * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ /* ------------------------------------------------------------------- * Copyright (c) 2006 Wael Chatila / Icegreen Technologies. All Rights Reserved. * This software is released under the LGPL which is available at http://www.gnu.org/copyleft/lesser.html * This file has been modified by the copyright holder. Original file can be found at http://james.apache.org * ------------------------------------------------------------------- * * 2012 - Alfresco Software, Ltd. * Alfresco Software has modified source of this file * The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src */ package com.icegreen.greenmail.imap; import com.icegreen.greenmail.AbstractServer; import com.icegreen.greenmail.Managers; import com.icegreen.greenmail.util.DummySSLServerSocketFactory; import com.icegreen.greenmail.util.ServerSetup; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.SSLServerSocket; public class ImapServer extends AbstractServer { private AtomicReference<Exception> serverOpeningExceptionRef; public ImapServer(ServerSetup setup, Managers managers) { super(setup, managers); } public ImapServer(ServerSetup setup, Managers managers, AtomicReference<Exception> serverOpeningExceptionRef ) { this(setup, managers); this.serverOpeningExceptionRef = serverOpeningExceptionRef; } protected synchronized ServerSocket openServerSocket() throws IOException { ServerSocket ret; if (setup.isSecure()) { ret = (SSLServerSocket) DummySSLServerSocketFactory.getDefault().createServerSocket( setup.getPort(), 0, bindTo); } else { ret = new ServerSocket(setup.getPort(), 0, bindTo); } return ret; } public synchronized void quit() { try { List copyOfData = new ArrayList(handlers); for (Iterator iterator = copyOfData.iterator(); iterator.hasNext();) { ImapHandler imapHandler = (ImapHandler) iterator.next(); imapHandler.resetHandler(); } handlers.clear(); } catch (Exception e) { throw new RuntimeException(e); } try { if (null != serverSocket && !serverSocket.isClosed()) { serverSocket.close(); serverSocket = null; } } catch (IOException e) { throw new RuntimeException(e); } } public void run() { try { IOException serverOpeningException = null; try { serverSocket = openServerSocket(); } catch (IOException e) { serverOpeningException = e; throw new RuntimeException(e); } finally { if (serverOpeningExceptionRef != null){ synchronized (serverOpeningExceptionRef) { serverOpeningExceptionRef.set(serverOpeningException); serverOpeningExceptionRef.notify(); } } } while (keepOn()) { try { Socket clientSocket = serverSocket.accept(); ImapHandler imapHandler = new ImapHandler(managers.getUserManager(), managers.getImapHostManager(), clientSocket, this); handlers.add(imapHandler); imapHandler.start(); } catch (IOException ignored) { //ignored } } } finally{ quit(); } } }
deas/alfresco-community-edition
projects/3rd-party/greenmail/source/java/com/icegreen/greenmail/imap/ImapServer.java
Java
lgpl-3.0
4,970