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
(function() { tinymce.PluginManager.requireLangPack('kotofey_shortcodes'); tinymce.create('tinymce.plugins.kotofey_shortcodes', { init : function(ed, url) { ed.addCommand('mcekotofey_shortcodes', function() { ed.windowManager.open({ file : url + '/interface.php', width : 290 + ed.getLang('kotofey_shortcodes.delta_width', 0), height : 150 + ed.getLang('kotofey_shortcodes.delta_height', 0), inline : 1 }, { plugin_url : url }); }); ed.addButton('kotofey_shortcodes', { title : 'Click to add a shortcode', cmd : 'mcekotofey_shortcodes', image : url + '/shortcode_button.png' }); ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('kotofey_shortcodes', n.nodeName == 'IMG'); }); }, createControl : function(n, cm) { return null; }, getInfo : function() { return { longname : 'kotofey_shortcodes', author : 'kotofey', authorurl : 'http://themeforest.net/user/kotofey', infourl : 'http://themeforest.net/user/kotofey', version : "1.0" }; } }); tinymce.PluginManager.add('kotofey_shortcodes', tinymce.plugins.kotofey_shortcodes); })();
nizaranand/New-Life-Office
dev/wp-content/themes/teardrop/extends/wysiwyg/editor.js
JavaScript
gpl-2.0
1,181
package com.lj.learning.dao; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your custom includes here // KEEP INCLUDES END /** * Entity mapped to table "SHEET". */ public class Sheet implements java.io.Serializable { private Long id; /** Not-null value. */ /** * 表格页签名称 */ private String sheetname; /** Not-null value. */ /** * 数据库表名称 */ private String databasename; // KEEP FIELDS - put your custom fields here // KEEP FIELDS END public Sheet() { } public Sheet(Long id) { this.id = id; } public Sheet(Long id, String sheetname, String databasename) { this.id = id; this.sheetname = sheetname; this.databasename = databasename; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** Not-null value. */ public String getSheetname() { return sheetname; } /** Not-null value; ensure this value is available before it is saved to the database. */ public void setSheetname(String sheetname) { this.sheetname = sheetname; } /** Not-null value. */ public String getDatabasename() { return databasename; } /** Not-null value; ensure this value is available before it is saved to the database. */ public void setDatabasename(String databasename) { this.databasename = databasename; } // KEEP METHODS - put your custom methods here // KEEP METHODS END }
wbhqf3/test
Learning/app/src/main/java/com/lj/learning/dao/Sheet.java
Java
gpl-2.0
1,601
<?php /** * This houses all the code to integrate with X */ class Cornerstone_Integration_X_Theme { /** * Theme integrations should provide a stylesheet function returning the stylesheet name * This will be matched with get_stylesheet() to determine if the integration will load */ public static function stylesheet() { return 'x'; } /** * Theme integrations are loaded on the after_theme_setup hook */ public function __construct() { add_action( 'init', array( $this, 'init' ) ); add_action( 'cornerstone_load_preview', array( $this, 'load_preview' ) ); add_filter( 'cornerstone_config_common_default-settings', array( $this, 'addDefaultSettings' ) ); // Don't enqueue native styles add_filter( 'cornerstone_enqueue_styles', '__return_false' ); add_filter( 'cornerstone_inline_styles', '__return_false' ); // Don't load the Customizer add_filter( 'cornerstone_use_customizer', '__return_false' ); // Enable X specific settings pane items add_filter( 'x_settings_pane', '__return_true' ); // Declare support for page builder features add_filter( 'cornerstone_looks_like_support', '__return_true' ); // Shortcode generator tweaks add_action('cornerstone_generator_preview_before', array( $this, 'shortcodeGeneratorPreviewBefore' ), -9999 ); add_filter('cornerstone_generator_map', array( $this, 'shortcodeGeneratorDemoURL' ) ); // Alias legacy shortcode names. add_action('cornerstone_shortcodes_loaded', array( $this, 'aliasShortcodes' ) ); add_filter('cornerstone_scrolltop_selector', array( $this, 'scrollTopSelector' ) ); add_filter('cs_recent_posts_post_types', array( $this, 'recentPostTypes' ) ); // Use Audio and Video shortcodes for X native players. add_filter( 'wp_audio_shortcode_library', 'x_wp_native_audio_shortcode_library' ); add_filter( 'wp_audio_shortcode', 'x_wp_native_audio_shortcode' ); add_filter( 'wp_audio_shortcode_class', 'x_wp_native_audio_shortcode_class' ); add_filter( 'wp_video_shortcode_library', 'x_wp_native_video_shortcode_library' ); add_filter( 'wp_video_shortcode', 'x_wp_native_video_shortcode' ); add_filter( 'wp_video_shortcode_class', 'x_wp_native_video_shortcode_class' ); } public function init() { // Add Logic for additional contact methods if not overridden in a child theme if ( ! function_exists( 'x_modify_contact_methods' ) ) add_filter( 'user_contactmethods', array( $this, 'modifyContactMethods' ) ); add_action( 'admin_menu', array( $this, 'optionsPage' ) ); // Remove empty p and br HTML elements for legacy pages not using Cornerstone sections add_filter( 'the_content', 'cs_noemptyp' ); // Enqueue Legacy font classes $settings = CS()->settings(); if ( isset( $settings['enable_legacy_font_classes'] ) && $settings['enable_legacy_font_classes'] ) { add_filter( 'cornerstone_legacy_font_classes', '__return_true' ); } } public function aliasShortcodes() { // // Alias [social] to [icon] for backwards compatability. // cs_alias_shortcode( 'social', 'x_icon', false ); // // Alias deprecated shortcode names. // // Mk2 cs_alias_shortcode( array( 'alert', 'x_alert' ), 'cs_alert' ); cs_alias_shortcode( array( 'x_text' ), 'cs_text' ); cs_alias_shortcode( array( 'icon_list', 'x_icon_list' ), 'cs_icon_list' ); cs_alias_shortcode( array( 'icon_list_item', 'x_icon_list_item' ), 'cs_icon_list_item' ); // Mk1 cs_alias_shortcode( 'accordion', 'x_accordion', false ); cs_alias_shortcode( 'accordion_item', 'x_accordion_item', false ); cs_alias_shortcode( 'author', 'x_author', false ); cs_alias_shortcode( 'block_grid', 'x_block_grid', false ); cs_alias_shortcode( 'block_grid_item', 'x_block_grid_item', false ); cs_alias_shortcode( 'blockquote', 'x_blockquote', false ); cs_alias_shortcode( 'button', 'x_button', false ); cs_alias_shortcode( 'callout', 'x_callout', false ); cs_alias_shortcode( 'clear', 'x_clear', false ); cs_alias_shortcode( 'code', 'x_code', false ); cs_alias_shortcode( 'column', 'x_column', false ); cs_alias_shortcode( 'columnize', 'x_columnize', false ); cs_alias_shortcode( 'container', 'x_container', false ); cs_alias_shortcode( 'content_band', 'x_content_band', false ); cs_alias_shortcode( 'counter', 'x_counter', false ); cs_alias_shortcode( 'custom_headline', 'x_custom_headline', false ); cs_alias_shortcode( 'dropcap', 'x_dropcap', false ); cs_alias_shortcode( 'extra', 'x_extra', false ); cs_alias_shortcode( 'feature_headline', 'x_feature_headline', false ); cs_alias_shortcode( 'gap', 'x_gap', false ); cs_alias_shortcode( 'google_map', 'x_google_map', false ); cs_alias_shortcode( 'google_map_marker', 'x_google_map_marker', false ); cs_alias_shortcode( 'highlight', 'x_highlight', false ); cs_alias_shortcode( 'icon', 'x_icon', false ); cs_alias_shortcode( 'image', 'x_image', false ); cs_alias_shortcode( 'lightbox', 'x_lightbox', false ); cs_alias_shortcode( 'line', 'x_line', false ); cs_alias_shortcode( 'map', 'x_map', false ); cs_alias_shortcode( 'pricing_table', 'x_pricing_table', false ); cs_alias_shortcode( 'pricing_table_column', 'x_pricing_table_column', false ); cs_alias_shortcode( 'promo', 'x_promo', false ); cs_alias_shortcode( 'prompt', 'x_prompt', false ); cs_alias_shortcode( 'protect', 'x_protect', false ); cs_alias_shortcode( 'pullquote', 'x_pullquote', false ); cs_alias_shortcode( 'raw_output', 'x_raw_output', false ); cs_alias_shortcode( 'recent_posts', 'x_recent_posts', false ); cs_alias_shortcode( 'responsive_text', 'x_responsive_text', false ); cs_alias_shortcode( 'search', 'x_search', false ); cs_alias_shortcode( 'share', 'x_share', false ); cs_alias_shortcode( 'skill_bar', 'x_skill_bar', false ); cs_alias_shortcode( 'slider', 'x_slider', false ); cs_alias_shortcode( 'slide', 'x_slide', false ); cs_alias_shortcode( 'tab_nav', 'x_tab_nav', false ); cs_alias_shortcode( 'tab_nav_item', 'x_tab_nav_item', false ); cs_alias_shortcode( 'tabs', 'x_tabs', false ); cs_alias_shortcode( 'tab', 'x_tab', false ); cs_alias_shortcode( 'toc', 'x_toc', false ); cs_alias_shortcode( 'toc_item', 'x_toc_item', false ); cs_alias_shortcode( 'visibility', 'x_visibility', false ); } public function recentPostTypes( $types ) { $types['portfolio'] = 'x-portfolio'; return $types; } public function scrollTopSelector() { return '.x-navbar-fixed-top'; } public function modifyContactMethods( $user_contactmethods ) { if ( isset( $user_contactmethods['yim'] ) ) unset( $user_contactmethods['yim'] ); if ( isset( $user_contactmethods['aim'] ) ) unset( $user_contactmethods['aim'] ); if ( isset( $user_contactmethods['jabber'] ) ) unset( $user_contactmethods['jabber'] ); $user_contactmethods['facebook'] = __( 'Facebook Profile', csl18n() ); $user_contactmethods['twitter'] = __( 'Twitter Profile', csl18n() ); $user_contactmethods['googleplus'] = __( 'Google+ Profile', csl18n() ); return $user_contactmethods; } public function shortcodeGeneratorPreviewBefore() { remove_all_actions( 'cornerstone_generator_preview_before' ); $list_stacks = array( 'integrity' => __( 'Integrity', csl18n() ), 'renew' => __( 'Renew', csl18n() ), 'icon' => __( 'Icon', csl18n() ), 'ethos' => __( 'Ethos', csl18n() ) ); $stack = $this->x_get_stack(); $stack_name = ( isset( $list_stacks[ $stack ] ) ) ? $list_stacks[ $stack ] : 'X'; printf( __('You&apos;re using %s. Click the button below to check out a live example of this shortcode when using this Stack.', csl18n() ), '<strong>' . $stack_name . '</strong>' ); } public function shortcodeGeneratorDemoURL( $attributes ) { if ( isset($attributes['demo']) ) $attributes['demo'] = str_replace( 'integrity', $this->x_get_stack(), $attributes['demo'] ); return $attributes; } public function x_get_stack() { // Some plugins abort the theme loading process in certain contexts. // This provide a safe fallback for x_get_stack calls if ( function_exists( 'x_get_stack' ) ) return x_get_stack(); return apply_filters( 'x_option_x_stack', get_option( 'x_stack', 'integrity' ) ); } public function addDefaultSettings( $settings ) { $settings['enable_legacy_font_classes'] = get_option( 'x_pre_v4', false ); return $settings; } /** * Swap out the Design and Product Validation Metaboxes on the Options page */ public function optionsPage() { remove_action( 'cornerstone_options_mb_validation', array( CS()->component( 'Admin' ), 'renderValidationMB' ) ); add_action( 'cornerstone_options_mb_settings', array( $this, 'legacyFontClasses' ) ); add_action( 'cornerstone_options_mb_validation', array( $this, 'renderValidationMB' ) ); add_filter( 'cornerstone_config_admin_info-items', array( $this, 'removeInfoItems' ) ); } /** * */ public function legacyFontClasses() { ?> <tr> <th> <label for="cornerstone-fields-enable_legacy_font_classes"> <strong><?php _e( 'Enable Legacy Font Classes', csl18n() ); ?></strong> <span><?php _e( 'Check to enable legacy font classes.', csl18n() ); ?></span> </label> </th> <td> <fieldset> <?php echo CS()->component( 'Admin' )->settings->renderField( 'enable_legacy_font_classes', array( 'type' => 'checkbox', 'value' => '1', 'label' => __( 'Enable', csl18n() ) ) ) ?> </fieldset> </td> </tr> <?php } /** * Output custom Product Validation Metabox */ public function renderValidationMB() { ?> <?php if ( x_is_validated() ) : ?> <p class="cs-validated"><strong>Congrats! X is active and validated</strong>. Because of this you don't need to validate Cornerstone and automatic updates are up and running.</p> <?php else : ?> <p class="cs-not-validated"><strong>Uh oh! It looks like X isn't validated</strong>. Cornerstone validates through X, which enables automatic updates. Head over to the product validation page to get that setup.<br><a href="<?php echo x_addons_get_link_product_validation(); ?>">Validate</a></p> <?php endif; } public function removeInfoItems( $info_items ) { unset( $info_items['api-key'] ); unset( $info_items['design-options'] ); $info_items['enable-legacy-font-classes' ] = array( 'title' => __( 'Enable Legacy Font Classes', csl18n() ), 'content' => __( 'X no longer provides the <strong>.x-icon*</strong> classes. This was done for performance reasons. If you need these classes, you can enable them again with this setting.', csl18n() ) ); return $info_items; } public function load_preview() { if ( defined( 'X_VIDEO_LOCK_VERSION' ) ) remove_action( 'wp_footer', 'x_video_lock_output' ); } } // Native shortcode alterations. // ============================================================================= // [audio] // ============================================================================= // // 1. Library. // 2. Output. // 3. Class. // function x_wp_native_audio_shortcode_library() { // 1 wp_enqueue_script( 'mediaelement' ); return false; } function x_wp_native_audio_shortcode( $html ) { // 2 return '<div class="x-audio player" data-x-element="x_mejs">' . $html . '</div>'; } function x_wp_native_audio_shortcode_class() { // 3 return 'x-mejs x-wp-audio-shortcode advanced-controls'; } // [video] // ============================================================================= // // 1. Library. // 2. Output. // 3. Class. // function x_wp_native_video_shortcode_library() { // 1 wp_enqueue_script( 'mediaelement' ); return false; } function x_wp_native_video_shortcode( $output ) { // 2 return '<div class="x-video player" data-x-element="x_mejs">' . preg_replace('/<div(.*?)>/', '<div class="x-video-inner">', $output ) . '</div>'; } function x_wp_native_video_shortcode_class() { // 3 return 'x-mejs x-wp-video-shortcode advanced-controls'; }
elinberg/ericlinberg
wp-content/plugins/cornerstone/includes/integrations/x-theme.php
PHP
gpl-2.0
12,573
/* $Id$ */ /** @file * * VBox frontends: Qt GUI ("VirtualBox"): * The main() function */ /* * Copyright (C) 2006-2009 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifdef VBOX_WITH_PRECOMPILED_HEADERS #include "precomp.h" #ifdef Q_WS_MAC # include "UICocoaApplication.h" #endif /* Q_WS_MAC */ #else /* !VBOX_WITH_PRECOMPILED_HEADERS */ #include "VBoxGlobal.h" #include "UIMessageCenter.h" #include "UISelectorWindow.h" #include "VBoxUtils.h" #ifdef Q_WS_MAC # include "UICocoaApplication.h" #endif #ifdef Q_WS_X11 #include <QFontDatabase> #include <iprt/env.h> #endif #include <QCleanlooksStyle> #include <QPlastiqueStyle> #include <QMessageBox> #include <QLocale> #include <QTranslator> #ifdef Q_WS_X11 # include <X11/Xlib.h> #endif #include <iprt/buildconfig.h> #include <iprt/err.h> #include <iprt/initterm.h> #include <iprt/process.h> #include <iprt/stream.h> #include <VBox/err.h> #include <VBox/version.h> #endif /* !VBOX_WITH_PRECOMPILED_HEADERS */ #ifdef VBOX_WITH_HARDENING # include <VBox/sup.h> #endif #ifdef RT_OS_LINUX # include <unistd.h> #endif #include <cstdio> /* XXX Temporarily. Don't rely on the user to hack the Makefile himself! */ QString g_QStrHintLinuxNoMemory = QApplication::tr( "This error means that the kernel driver was either not able to " "allocate enough memory or that some mapping operation failed." ); QString g_QStrHintLinuxNoDriver = QApplication::tr( "The VirtualBox Linux kernel driver (vboxdrv) is either not loaded or " "there is a permission problem with /dev/vboxdrv. Please reinstall the kernel " "module by executing<br/><br/>" " <font color=blue>'/etc/init.d/vboxdrv setup'</font><br/><br/>" "as root. If it is available in your distribution, you should install the " "DKMS package first. This package keeps track of Linux kernel changes and " "recompiles the vboxdrv kernel module if necessary." ); QString g_QStrHintOtherWrongDriverVersion = QApplication::tr( "The VirtualBox kernel modules do not match this version of " "VirtualBox. The installation of VirtualBox was apparently not " "successful. Please try completely uninstalling and reinstalling " "VirtualBox." ); QString g_QStrHintLinuxWrongDriverVersion = QApplication::tr( "The VirtualBox kernel modules do not match this version of " "VirtualBox. The installation of VirtualBox was apparently not " "successful. Executing<br/><br/>" " <font color=blue>'/etc/init.d/vboxdrv setup'</font><br/><br/>" "may correct this. Make sure that you do not mix the " "OSE version and the PUEL version of VirtualBox." ); QString g_QStrHintOtherNoDriver = QApplication::tr( "Make sure the kernel module has been loaded successfully." ); /* I hope this isn't (C), (TM) or (R) Microsoft support ;-) */ QString g_QStrHintReinstall = QApplication::tr( "Please try reinstalling VirtualBox." ); #if defined(DEBUG) && defined(Q_WS_X11) && defined(RT_OS_LINUX) #include <signal.h> #include <execinfo.h> /* get REG_EIP from ucontext.h */ #ifndef __USE_GNU #define __USE_GNU #endif #include <ucontext.h> #ifdef RT_ARCH_AMD64 # define REG_PC REG_RIP #else # define REG_PC REG_EIP #endif /** * the signal handler that prints out a backtrace of the call stack. * the code is taken from http://www.linuxjournal.com/article/6391. */ void bt_sighandler (int sig, siginfo_t *info, void *secret) { void *trace[16]; char **messages = (char **)NULL; int i, trace_size = 0; ucontext_t *uc = (ucontext_t *)secret; /* Do something useful with siginfo_t */ if (sig == SIGSEGV) Log (("GUI: Got signal %d, faulty address is %p, from %p\n", sig, info->si_addr, uc->uc_mcontext.gregs[REG_PC])); else Log (("GUI: Got signal %d\n", sig)); trace_size = backtrace (trace, 16); /* overwrite sigaction with caller's address */ trace[1] = (void *) uc->uc_mcontext.gregs [REG_PC]; messages = backtrace_symbols (trace, trace_size); /* skip first stack frame (points here) */ Log (("GUI: [bt] Execution path:\n")); for (i = 1; i < trace_size; ++i) Log (("GUI: [bt] %s\n", messages[i])); exit (0); } #endif /* DEBUG && X11 && LINUX*/ #if defined(RT_OS_DARWIN) # include <dlfcn.h> # include <sys/mman.h> # include <iprt/asm.h> # include <iprt/system.h> /** Really ugly hack to shut up a silly check in AppKit. */ static void ShutUpAppKit(void) { /* Check for Snow Leopard or higher */ char szInfo[64]; int rc = RTSystemQueryOSInfo (RTSYSOSINFO_RELEASE, szInfo, sizeof(szInfo)); if ( RT_SUCCESS (rc) && szInfo[0] == '1') /* higher than 1x.x.x */ { /* * Find issetguid() and make it always return 0 by modifying the code. */ void *addr = dlsym(RTLD_DEFAULT, "issetugid"); int rc = mprotect((void *)((uintptr_t)addr & ~(uintptr_t)0xfff), 0x2000, PROT_WRITE|PROT_READ|PROT_EXEC); if (!rc) ASMAtomicWriteU32((volatile uint32_t *)addr, 0xccc3c031); /* xor eax, eax; ret; int3 */ } } #endif /* DARWIN */ static void QtMessageOutput (QtMsgType type, const char *msg) { #ifndef Q_WS_X11 NOREF(msg); #endif switch (type) { case QtDebugMsg: Log (("Qt DEBUG: %s\n", msg)); break; case QtWarningMsg: Log (("Qt WARNING: %s\n", msg)); #ifdef Q_WS_X11 /* Needed for instance for the message ``cannot connect to X server'' */ RTStrmPrintf(g_pStdErr, "Qt WARNING: %s\n", msg); #endif break; case QtCriticalMsg: Log (("Qt CRITICAL: %s\n", msg)); #ifdef Q_WS_X11 /* Needed for instance for the message ``cannot connect to X server'' */ RTStrmPrintf(g_pStdErr, "Qt CRITICAL: %s\n", msg); #endif break; case QtFatalMsg: Log (("Qt FATAL: %s\n", msg)); #ifdef Q_WS_X11 RTStrmPrintf(g_pStdErr, "Qt FATAL: %s\n", msg); #endif } } /** * Show all available command line parameters. */ static void showHelp() { QString mode = "", dflt = ""; #ifdef VBOX_GUI_USE_SDL mode += "sdl"; #endif #ifdef VBOX_GUI_USE_QIMAGE if (!mode.isEmpty()) mode += "|"; mode += "image"; #endif #ifdef VBOX_GUI_USE_DDRAW if (!mode.isEmpty()) mode += "|"; mode += "ddraw"; #endif #ifdef VBOX_GUI_USE_QUARTZ2D if (!mode.isEmpty()) mode += "|"; mode += "quartz2d"; #endif #if defined (Q_WS_MAC) && defined (VBOX_GUI_USE_QUARTZ2D) dflt = "quartz2d"; #elif (defined (Q_WS_WIN32) || defined (Q_WS_PM)) && defined (VBOX_GUI_USE_QIMAGE) dflt = "image"; #elif defined (Q_WS_X11) && defined (VBOX_GUI_USE_SDL) dflt = "sdl"; #else dflt = "image"; #endif RTPrintf(VBOX_PRODUCT " Manager %s\n" "(C) 2005-" VBOX_C_YEAR " " VBOX_VENDOR "\n" "All rights reserved.\n" "\n" "Usage:\n" " --startvm <vmname|UUID> start a VM by specifying its UUID or name\n" " --seamless switch to seamless mode during startup\n" " --fullscreen switch to fullscreen mode during startup\n" " --rmode %-18s select different render mode (default is %s)\n" " --no-startvm-errormsgbox do not show a message box for VM start errors\n" # ifdef VBOX_GUI_WITH_PIDFILE " --pidfile <file> create a pidfile file when a VM is up and running\n" # endif # ifdef VBOX_WITH_DEBUGGER_GUI " --dbg enable the GUI debug menu\n" " --debug like --dbg and show debug windows at VM startup\n" " --debug-command-line like --dbg and show command line window at VM startup\n" " --debug-statistics like --dbg and show statistics window at VM startup\n" " --no-debug disable the GUI debug menu and debug windows\n" " --start-paused start the VM in the paused state\n" " --start-running start the VM running (for overriding --debug*)\n" "\n" # endif "Expert options:\n" " --disable-patm disable code patching (ignored by AMD-V/VT-x)\n" " --disable-csam disable code scanning (ignored by AMD-V/VT-x)\n" " --recompile-supervisor recompiled execution of supervisor code (*)\n" " --recompile-user recompiled execution of user code (*)\n" " --recompile-all recompiled execution of all code, with disabled\n" " code patching and scanning\n" " (*) For AMD-V/VT-x setups the effect is --recompile-all.\n" "\n" # ifdef VBOX_WITH_DEBUGGER_GUI "The following environment (and extra data) variables are evaluated:\n" " VBOX_GUI_DBG_ENABLED (GUI/Dbg/Enabled)\n" " enable the GUI debug menu if set\n" " VBOX_GUI_DBG_AUTO_SHOW (GUI/Dbg/AutoShow)\n" " show debug windows at VM startup\n" " VBOX_GUI_NO_DEBUGGER disable the GUI debug menu and debug windows\n" # endif "\n", RTBldCfgVersion(), mode.toLatin1().constData(), dflt.toLatin1().constData()); /** @todo Show this as a dialog on windows. */ } extern "C" DECLEXPORT(int) TrustedMain (int argc, char **argv, char ** /*envp*/) { LogFlowFuncEnter(); # if defined(RT_OS_DARWIN) ShutUpAppKit(); # endif for (int i=0; i<argc; i++) if ( !strcmp(argv[i], "-h") || !strcmp(argv[i], "-?") || !strcmp(argv[i], "-help") || !strcmp(argv[i], "--help")) { showHelp(); return 0; } #if defined(DEBUG) && defined(Q_WS_X11) && defined(RT_OS_LINUX) /* install our signal handler to backtrace the call stack */ struct sigaction sa; sa.sa_sigaction = bt_sighandler; sigemptyset (&sa.sa_mask); sa.sa_flags = SA_RESTART | SA_SIGINFO; sigaction (SIGSEGV, &sa, NULL); sigaction (SIGBUS, &sa, NULL); sigaction (SIGUSR1, &sa, NULL); #endif #ifdef QT_MAC_USE_COCOA /* Instantiate our NSApplication derivative before QApplication * forces NSApplication to be instantiated. */ UICocoaApplication::instance(); #endif qInstallMsgHandler (QtMessageOutput); int rc = 1; /* failure */ /* scope the QApplication variable */ { #ifdef Q_WS_X11 /* Qt has a complex algorithm for selecting the right visual which * doesn't always seem to work. So we naively choose a visual - the * default one - ourselves and pass that to Qt. This means that we * also have to open the display ourselves. * We check the Qt parameter list and handle Qt's -display argument * ourselves, since we open the display connection. We also check the * to see if the user has passed Qt's -visual parameter, and if so we * assume that the user wants Qt to handle visual selection after all, * and don't supply a visual. */ char *pszDisplay = NULL; bool useDefaultVisual = true; for (int i = 0; i < argc; ++i) { if (!::strcmp(argv[i], "-display") && (i + 1 < argc)) /* What if it isn't? Rely on QApplication to complain? */ { pszDisplay = argv[i + 1]; ++i; } else if (!::strcmp(argv[i], "-visual")) useDefaultVisual = false; } Display *pDisplay = XOpenDisplay(pszDisplay); if (!pDisplay) { RTPrintf(pszDisplay ? "Failed to open the X11 display \"%s\"!\n" : "Failed to open the X11 display!\n", pszDisplay); return 0; } Visual *pVisual = useDefaultVisual ? DefaultVisual(pDisplay, DefaultScreen(pDisplay)) : NULL; /* Now create the application object */ QApplication a (pDisplay, argc, argv, (Qt::HANDLE) pVisual); #else /* Q_WS_X11 */ QApplication a (argc, argv); #endif /* Q_WS_X11 */ /* Qt4.3 version has the QProcess bug which freezing the application * for 30 seconds. This bug is internally used at initialization of * Cleanlooks style. So we have to change this style to another one. * See http://trolltech.com/developer/task-tracker/index_html?id=179200&method=entry * for details. */ if (VBoxGlobal::qtRTVersionString().startsWith ("4.3") && qobject_cast <QCleanlooksStyle*> (QApplication::style())) QApplication::setStyle (new QPlastiqueStyle); #ifdef Q_OS_SOLARIS /* Use plastique look 'n feel for Solaris instead of the default motif (Qt 4.7.x) */ QApplication::setStyle (new QPlastiqueStyle); #endif #ifdef Q_WS_X11 /* This patch is not used for now on Solaris & OpenSolaris because * there is no anti-aliasing enabled by default, Qt4 to be rebuilt. */ #ifndef Q_OS_SOLARIS /* Cause Qt4 has the conflict with fontconfig application as a result * sometimes substituting some fonts with non scaleable-anti-aliased * bitmap font we are reseting substitutes for the current application * font family if it is non scaleable-anti-aliased. */ QFontDatabase fontDataBase; QString currentFamily (QApplication::font().family()); bool isCurrentScaleable = fontDataBase.isScalable (currentFamily); /* LogFlowFunc (("Font: Current family is '%s'. It is %s.\n", currentFamily.toLatin1().constData(), isCurrentScaleable ? "scalable" : "not scalable")); QStringList subFamilies (QFont::substitutes (currentFamily)); foreach (QString sub, subFamilies) { bool isSubScalable = fontDataBase.isScalable (sub); LogFlowFunc (("Font: Substitute family is '%s'. It is %s.\n", sub.toLatin1().constData(), isSubScalable ? "scalable" : "not scalable")); } */ QString subFamily (QFont::substitute (currentFamily)); bool isSubScaleable = fontDataBase.isScalable (subFamily); if (isCurrentScaleable && !isSubScaleable) QFont::removeSubstitution (currentFamily); #endif /* Q_OS_SOLARIS */ #endif #ifdef Q_WS_WIN /* Drag in the sound drivers and DLLs early to get rid of the delay taking * place when the main menu bar (or any action from that menu bar) is * activated for the first time. This delay is especially annoying if it * happens when the VM is executing in real mode (which gives 100% CPU * load and slows down the load process that happens on the main GUI * thread to several seconds). */ PlaySound (NULL, NULL, 0); #endif #ifdef Q_WS_MAC ::darwinDisableIconsInMenus(); #endif /* Q_WS_MAC */ #ifdef Q_WS_X11 /* version check (major.minor are sensitive, fix number is ignored) */ if (VBoxGlobal::qtRTVersion() < (VBoxGlobal::qtCTVersion() & 0xFFFF00)) { QString msg = QApplication::tr ("Executable <b>%1</b> requires Qt %2.x, found Qt %3.") .arg (qAppName()) .arg (VBoxGlobal::qtCTVersionString().section ('.', 0, 1)) .arg (VBoxGlobal::qtRTVersionString()); QMessageBox::critical ( 0, QApplication::tr ("Incompatible Qt Library Error"), msg, QMessageBox::Abort, 0); qFatal ("%s", msg.toAscii().constData()); } #endif /* load a translation based on the current locale */ VBoxGlobal::loadLanguage(); do { if (!vboxGlobal().isValid()) break; if (vboxGlobal().processArgs()) return 0; msgCenter().checkForMountedWrongUSB(); VBoxGlobalSettings settings = vboxGlobal().settings(); /* Process known keys */ bool noSelector = settings.isFeatureActive ("noSelector"); if (vboxGlobal().isVMConsoleProcess()) { #ifdef VBOX_GUI_WITH_SYSTRAY if (vboxGlobal().trayIconInstall()) { /* Nothing to do here yet. */ } #endif if (vboxGlobal().startMachine (vboxGlobal().managedVMUuid())) { vboxGlobal().setMainWindow (vboxGlobal().vmWindow()); rc = a.exec(); } } else if (noSelector) { msgCenter().cannotRunInSelectorMode(); } else { #ifdef VBOX_BLEEDING_EDGE msgCenter().showBEBWarning(); #else # ifndef DEBUG /* Check for BETA version */ QString vboxVersion (vboxGlobal().virtualBox().GetVersion()); if (vboxVersion.contains ("BETA")) { /* Allow to prevent this message */ QString str = vboxGlobal().virtualBox(). GetExtraData(GUI_PreventBetaWarning); if (str != vboxVersion) msgCenter().showBETAWarning(); } # endif #endif vboxGlobal().setMainWindow (&vboxGlobal().selectorWnd()); #ifdef VBOX_GUI_WITH_SYSTRAY if (vboxGlobal().trayIconInstall()) { /* Nothing to do here yet. */ } if (false == vboxGlobal().isTrayMenu()) { #endif vboxGlobal().selectorWnd().show(); #ifdef VBOX_WITH_REGISTRATION_REQUEST vboxGlobal().showRegistrationDialog (false /* aForce */); #endif #ifdef VBOX_GUI_WITH_SYSTRAY } do { #endif rc = a.exec(); #ifdef VBOX_GUI_WITH_SYSTRAY } while (vboxGlobal().isTrayMenu()); #endif } } while (0); } LogFlowFunc (("rc=%d\n", rc)); LogFlowFuncLeave(); return rc; } #ifndef VBOX_WITH_HARDENING int main (int argc, char **argv, char **envp) { /* Initialize VBox Runtime. Initialize the SUPLib as well only if we * are really about to start a VM. Don't do this if we are only starting * the selector window. */ bool fInitSUPLib = false; for (int i = 1; i < argc; i++) { /* NOTE: the check here must match the corresponding check for the * options to start a VM in hardenedmain.cpp and VBoxGlobal.cpp exactly, * otherwise there will be weird error messages. */ if ( !::strcmp(argv[i], "--startvm") || !::strcmp(argv[i], "-startvm")) { fInitSUPLib = true; break; } } int rc = RTR3InitExe(argc, &argv, fInitSUPLib ? RTR3INIT_FLAGS_SUPLIB : 0); if (RT_FAILURE(rc)) { QApplication a (argc, &argv[0]); #ifdef Q_OS_SOLARIS /* Use plastique look 'n feel for Solaris instead of the default motif (Qt 4.7.x) */ QApplication::setStyle (new QPlastiqueStyle); #endif QString msgTitle = QApplication::tr ("VirtualBox - Runtime Error"); QString msgText = "<html>"; switch (rc) { case VERR_VM_DRIVER_NOT_INSTALLED: case VERR_VM_DRIVER_LOAD_ERROR: msgText += QApplication::tr ( "<b>Cannot access the kernel driver!</b><br/><br/>"); # ifdef RT_OS_LINUX msgText += g_QStrHintLinuxNoDriver; # else msgText += g_QStrHintOtherNoDriver; # endif break; # ifdef RT_OS_LINUX case VERR_NO_MEMORY: msgText += g_QStrHintLinuxNoMemory; break; # endif case VERR_VM_DRIVER_NOT_ACCESSIBLE: msgText += QApplication::tr ("Kernel driver not accessible"); break; case VERR_VM_DRIVER_VERSION_MISMATCH: # ifdef RT_OS_LINUX msgText += g_QStrHintLinuxWrongDriverVersion; # else msgText += g_QStrHintOtherWrongDriverVersion; # endif break; default: msgText += QApplication::tr ( "Unknown error %2 during initialization of the Runtime" ).arg (rc); break; } msgText += "</html>"; QMessageBox::critical ( 0, /* parent */ msgTitle, msgText, QMessageBox::Abort, /* button0 */ 0); /* button1 */ return 1; } return TrustedMain (argc, argv, envp); } #else /* VBOX_WITH_HARDENING */ /** * Hardened main failed, report the error without any unnecessary fuzz. * * @remarks Do not call IPRT here unless really required, it might not be * initialized. */ extern "C" DECLEXPORT(void) TrustedError (const char *pszWhere, SUPINITOP enmWhat, int rc, const char *pszMsgFmt, va_list va) { # if defined(RT_OS_DARWIN) ShutUpAppKit(); # endif /* * Init the Qt application object. This is a bit hackish as we * don't have the argument vector handy. */ int argc = 0; char *argv[2] = { NULL, NULL }; QApplication a (argc, &argv[0]); /* * Compose and show the error message. */ QString msgTitle = QApplication::tr ("VirtualBox - Error In %1").arg (pszWhere); char msgBuf[1024]; vsprintf (msgBuf, pszMsgFmt, va); QString msgText = QApplication::tr ( "<html><b>%1 (rc=%2)</b><br/><br/>").arg (msgBuf).arg (rc); switch (enmWhat) { case kSupInitOp_Driver: # ifdef RT_OS_LINUX msgText += g_QStrHintLinuxNoDriver; # else msgText += g_QStrHintOtherNoDriver; # endif break; # ifdef RT_OS_LINUX case kSupInitOp_IPRT: if (rc == VERR_NO_MEMORY) msgText += g_QStrHintLinuxNoMemory; else # endif if (rc == VERR_VM_DRIVER_VERSION_MISMATCH) # ifdef RT_OS_LINUX msgText += g_QStrHintLinuxWrongDriverVersion; # else msgText += g_QStrHintOtherWrongDriverVersion; # endif else msgText += g_QStrHintReinstall; break; case kSupInitOp_Integrity: case kSupInitOp_RootCheck: msgText += g_QStrHintReinstall; break; default: /* no hints here */ break; } msgText += "</html>"; # ifdef RT_OS_LINUX sleep(2); # endif QMessageBox::critical ( 0, /* parent */ msgTitle, /* title */ msgText, /* text */ QMessageBox::Abort, /* button0 */ 0); /* button1 */ qFatal ("%s", msgText.toAscii().constData()); } #endif /* VBOX_WITH_HARDENING */
dezelin/virtualbox
src/VBox/Frontends/VirtualBox/src/main.cpp
C++
gpl-2.0
23,802
<?php // no direct access defined('_JEXEC') or die('Restricted access'); ?> <div class="jbBoxTopLeft"><div class="jbBoxTopRight"><div class="jbBoxTop"> <div class="jbTextHeader"><?php echo JText::_('COM_JOOBB_BOARDLEGEND'); ?></div> </div></div></div> <div class="jbBoxOuter"><div class="jbBoxInner"> <div class="jbLeft jbMargin10"><?php $iconsBoard = $this->joobbIconSet->getIconsByGroup('iconBoard'); for ($i = 0, $n = count($iconsBoard); $i < $n; $i++) : $icon = $iconsBoard[$i]; ?> <div class="jbLeft jbPaddingRight20" style="text-align: center;"> <img src="<?php echo $icon->fileName; ?>" alt="<?php echo $icon->title; ?>" /> <div style="text-align: center;"><?php echo $icon->title; ?></div> </div><?php endfor; ?> </div> <br clear="all" /> </div></div> <div class="jbBoxBottomLeft"><div class="jbBoxBottomRight"><div class="jbBoxBottom"></div></div></div> <div class="jbMarginBottom10"></div>
srajib/share2learn
components/com_joobb/assets/templates/joobb/joobb_boardfooter.php
PHP
gpl-2.0
945
public class ValueGenerator { }
DB-SE/isp2014.marcus.kamieth
Algorithms_DataStructures_AspectJ/src/base/ValueGenerator.java
Java
gpl-2.0
35
package remasterkit; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.ImageIcon; import javax.swing.border.TitledBorder; import javax.swing.border.LineBorder; import java.awt.Color; import java.awt.Toolkit; import javax.swing.JButton; import java.awt.Font; import javax.swing.JCheckBox; import com.jtattoo.plaf.graphite.GraphiteLookAndFeel; import javax.swing.JComboBox; import javax.swing.DefaultComboBoxModel; import javax.swing.JTextField; public class Menu_Utama extends JFrame { private JPanel contentPane; private JTextField txtName; private JTextField txtURL; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(new GraphiteLookAndFeel()); Menu_Utama frame = new Menu_Utama(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Menu_Utama() { setIconImage(Toolkit.getDefaultToolkit().getImage("/home/newbieilmu/workspace/app.remasterkit/src/icon/logo.png")); setTitle("RemasterKit(Custom Linuxmu Sesuka Hati)"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 589, 357); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panelRKit = new JPanel(); panelRKit.setBorder(new TitledBorder(null, "RemasterKit", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panelRKit.setBounds(146, 12, 421, 163); contentPane.add(panelRKit); panelRKit.setLayout(null); JLabel lblPilihDe = new JLabel("1. Pilih DE "); lblPilihDe.setBounds(12, 27, 105, 18); panelRKit.add(lblPilihDe); JComboBox cmbDE = new JComboBox(); cmbDE.setModel(new DefaultComboBoxModel(new String[] {"LXDE", "MATE", "GNOME", "KDE", "Manokwari"})); cmbDE.setBounds(110, 24, 89, 24); panelRKit.add(cmbDE); JLabel lblUbahSourcelist = new JLabel("2. Source.List"); lblUbahSourcelist.setBounds(12, 57, 105, 18); panelRKit.add(lblUbahSourcelist); JLabel lblPilihConsole = new JLabel("3. Console "); lblPilihConsole.setBounds(12, 87, 105, 18); panelRKit.add(lblPilihConsole); JLabel lblInstallDeb = new JLabel("4. Install DEB"); lblInstallDeb.setBounds(12, 117, 105, 18); panelRKit.add(lblInstallDeb); JLabel lblPaketList = new JLabel("5. Paket List "); lblPaketList.setBounds(217, 27, 105, 18); panelRKit.add(lblPaketList); JLabel lblSynaptic = new JLabel("6. Synaptic "); lblSynaptic.setBounds(217, 58, 105, 18); panelRKit.add(lblSynaptic); JLabel lblDesktop = new JLabel("7. Desktop"); lblDesktop.setBounds(217, 88, 105, 18); panelRKit.add(lblDesktop); JLabel lblUbiquity = new JLabel("8. Ubiquity"); lblUbiquity.setBounds(217, 120, 105, 18); panelRKit.add(lblUbiquity); JButton btnSource = new JButton("Source.list"); btnSource.setEnabled(false); btnSource.setBounds(110, 54, 86, 24); panelRKit.add(btnSource); JButton btnConsole = new JButton("Console"); btnConsole.setEnabled(false); btnConsole.setBounds(110, 84, 86, 24); panelRKit.add(btnConsole); JButton btnDeb = new JButton("DEB"); btnDeb.setEnabled(false); btnDeb.setBounds(110, 114, 86, 24); panelRKit.add(btnDeb); JButton btnPaketList = new JButton("Paket list"); btnPaketList.setEnabled(false); btnPaketList.setBounds(309, 24, 86, 24); panelRKit.add(btnPaketList); JButton btnSynaptic = new JButton("Synaptic"); btnSynaptic.setEnabled(false); btnSynaptic.setBounds(309, 55, 86, 24); panelRKit.add(btnSynaptic); JButton btnDekstop = new JButton("Dekstop"); btnDekstop.setEnabled(false); btnDekstop.setBounds(309, 87, 86, 24); panelRKit.add(btnDekstop); JButton btnUbiquity = new JButton("Ubiquity"); btnUbiquity.setEnabled(false); btnUbiquity.setBounds(309, 117, 86, 24); panelRKit.add(btnUbiquity); JButton btnAbout = new JButton("Tentang"); btnAbout.setBounds(299, 280, 86, 31); contentPane.add(btnAbout); JButton btnCredits = new JButton("Kredits"); btnCredits.setBounds(389, 280, 86, 31); contentPane.add(btnCredits); JButton btnLisensi = new JButton("Lisensi"); btnLisensi.setBounds(481, 280, 86, 31); contentPane.add(btnLisensi); JLabel lblIcon1 = new JLabel(""); lblIcon1.setIcon(new ImageIcon("/home/newbieilmu/workspace/app.remasterkit/src/icon/1374533657__settings.png")); lblIcon1.setBounds(12, 12, 55, 67); contentPane.add(lblIcon1); JLabel lblicon2 = new JLabel(""); lblicon2.setIcon(new ImageIcon("/home/newbieilmu/workspace/app.remasterkit/src/icon/1374533644_Import.png")); lblicon2.setBounds(12, 72, 55, 67); contentPane.add(lblicon2); JLabel lblicon3 = new JLabel(""); lblicon3.setIcon(new ImageIcon("/home/newbieilmu/workspace/app.remasterkit/src/icon/1374533631_Export.png")); lblicon3.setBounds(12, 137, 55, 67); contentPane.add(lblicon3); JLabel lblicon4 = new JLabel(""); lblicon4.setIcon(new ImageIcon("/home/newbieilmu/workspace/app.remasterkit/src/icon/1374534090_118.png")); lblicon4.setBounds(12, 202, 55, 67); contentPane.add(lblicon4); JLabel lblKonfigurasi = new JLabel("Konfigurasi"); lblKonfigurasi.setFont(new Font("Dialog", Font.BOLD, 13)); lblKonfigurasi.setBounds(67, 35, 86, 18); contentPane.add(lblKonfigurasi); JLabel lblImport = new JLabel("Import"); lblImport.setFont(new Font("Dialog", Font.BOLD, 13)); lblImport.setBounds(67, 91, 86, 18); contentPane.add(lblImport); JLabel lblEksport = new JLabel("Eksport"); lblEksport.setFont(new Font("Dialog", Font.BOLD, 13)); lblEksport.setBounds(67, 151, 86, 18); contentPane.add(lblEksport); JLabel lblBuild = new JLabel("Build"); lblBuild.setFont(new Font("Dialog", Font.BOLD, 13)); lblBuild.setBounds(67, 216, 86, 18); contentPane.add(lblBuild); JPanel panelSetting = new JPanel(); panelSetting.setBorder(new TitledBorder(null, "Setting ", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panelSetting.setBounds(146, 181, 421, 88); contentPane.add(panelSetting); panelSetting.setLayout(null); JLabel lblNamaLinuxmu = new JLabel("Nama Linuxmu :"); lblNamaLinuxmu.setBounds(12, 24, 92, 18); panelSetting.add(lblNamaLinuxmu); txtName = new JTextField(); txtName.setColumns(10); txtName.setBounds(122, 22, 179, 22); panelSetting.add(txtName); JLabel lblUrl = new JLabel("URL :"); lblUrl.setBounds(12, 54, 92, 18); panelSetting.add(lblUrl); txtURL = new JTextField(); txtURL.setColumns(10); txtURL.setBounds(122, 52, 179, 22); panelSetting.add(txtURL); JButton btnDonasi = new JButton("Donasi"); btnDonasi.setBounds(207, 280, 86, 31); contentPane.add(btnDonasi); } }
anugrahbsoe/RemasterKit
app.remasterkit/src/remasterkit/Menu_Utama.java
Java
gpl-2.0
6,973
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2016-2017 University of Dundee & Open Microscopy Environment. # All Rights Reserved. # Use is subject to license terms supplied in LICENSE.txt # import requests from Parse_OMERO_Properties import USERNAME, PASSWORD, OMERO_WEB_HOST, \ SERVER_NAME session = requests.Session() # Start by getting supported versions from the base url... api_url = '%s/api/' % OMERO_WEB_HOST print "Starting at:", api_url r = session.get(api_url) # we get a list of versions versions = r.json()['data'] # use most recent version... version = versions[-1] # get the 'base' url base_url = version['url:base'] r = session.get(base_url) # which lists a bunch of urls as starting points urls = r.json() servers_url = urls['url:servers'] login_url = urls['url:login'] projects_url = urls['url:projects'] save_url = urls['url:save'] schema_url = urls['url:schema'] # To login we need to get CSRF token token_url = urls['url:token'] token = session.get(token_url).json()['data'] print 'CSRF token', token # We add this to our session header # Needed for all POST, PUT, DELETE requests session.headers.update({'X-CSRFToken': token, 'Referer': login_url}) # List the servers available to connect to servers = session.get(servers_url).json()['data'] print 'Servers:' for s in servers: print '-id:', s['id'] print ' name:', s['server'] print ' host:', s['host'] print ' port:', s['port'] # find one called SERVER_NAME servers = [s for s in servers if s['server'] == SERVER_NAME] if len(servers) < 1: raise Exception("Found no server called '%s'" % SERVER_NAME) server = servers[0] # Login with username, password and token payload = {'username': USERNAME, 'password': PASSWORD, # 'csrfmiddlewaretoken': token, # Using CSRFToken in header instead 'server': server['id']} r = session.post(login_url, data=payload) login_rsp = r.json() assert r.status_code == 200 assert login_rsp['success'] eventContext = login_rsp['eventContext'] print 'eventContext', eventContext # Can get our 'default' group groupId = eventContext['groupId'] # With successful login, request.session will contain # OMERO session details and reconnect to OMERO on # each subsequent call... # List projects: # Limit number of projects per page payload = {'limit': 2} data = session.get(projects_url, params=payload).json() assert len(data['data']) < 3 print "Projects:" for p in data['data']: print ' ', p['@id'], p['Name'] # Create a project: projType = schema_url + '#Project' # Need to specify target group url = save_url + '?group=' + str(groupId) r = session.post(url, json={'Name': 'API TEST foo', '@type': projType}) assert r.status_code == 201 project = r.json()['data'] project_id = project['@id'] print 'Created Project:', project_id, project['Name'] # Get project by ID project_url = projects_url + str(project_id) + '/' r = session.get(project_url) project = r.json() print project # Update a project project['Name'] = 'API test updated' r = session.put(save_url, json=project) # Delete a project: r = session.delete(project_url)
jburel/openmicroscopy
examples/Training/python/Json_Api/Login.py
Python
gpl-2.0
3,163
package com.algebraweb.editor.client; import com.google.gwt.user.client.ui.Button; /** * A button for the control panel. Will be styled accordingly. * * @author Patrick Brosi * */ public class ControlPanelButton extends Button { public ControlPanelButton(String desc) { super(); this.addStyleName("controllpanel-button"); super.getElement().setAttribute("title", desc); this.setWidth("39px"); this.setHeight("39px"); } public ControlPanelButton(String desc, String styleClass) { this(desc); this.addStyleName("controllbutton-" + styleClass); } }
patrickbr/ferryleaks
src/com/algebraweb/editor/client/ControlPanelButton.java
Java
gpl-2.0
573
<?php /** * Intreface DAO * * @author: http://phpdao.com * @date: 2013-11-06 23:13 */ interface AccesoDAO{ /** * Get Domain object by primry key * * @param String $id primary key * @Return Acceso */ public function load($id); /** * Get all records from table */ public function queryAll(); /** * Get all records from table ordered by field * @Param $orderColumn column name */ public function queryAllOrderBy($orderColumn); /** * Delete record from table * @param acceso primary key */ public function delete($usuario); /** * Insert record to table * * @param Acceso acceso */ public function insert($acceso); /** * Update record in table * * @param Acceso acceso */ public function update($acceso); /** * Delete all rows */ public function clean(); public function queryByContrasenia($value); public function queryByRol($value); public function deleteByContrasenia($value); public function deleteByRol($value); } ?>
Digznav/DMG
files/old-projects/MIP/MIPhtml/FTU/class/dao/AccesoDAO.class.php
PHP
gpl-2.0
1,080
#python imports import sys import os import time import datetime import subprocess import json import requests from termcolor import colored #third-party imports #No third-party imports #programmer generated imports from logger import logger from fileio import fileio ''' ***BEGIN DESCRIPTION*** Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database. ***END DESCRIPTION*** ''' def POE(POE): if (POE.logging == True): LOG = logger() newlogentry = '' reputation_dump = '' reputation_output_data = '' malwarebazaar = '' if (POE.logging == True): newlogentry = 'Module: malware_bazaar_search' LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry) if (POE.SHA256 == ''): print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold'])) newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256' LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry) return -1 global json query_status = '' first_seen = '' last_seen = '' signature = '' sig_count = 0 output = POE.logdir + 'MalwareBazaarSearch.json' FI = fileio() print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold'])) malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL data = { #Our header params 'query': 'get_info', 'hash': POE.SHA256, } response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON if (POE.debug == True): print (response_dump) try: FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore")) print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold'])) if ((POE.logging == True) and (POE.nolinksummary == False)): newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>' LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) except: print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold'])) if (POE.logging == True): newlogentry = 'Unable to write Malware Bazaar data to file' LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry) POE.csv_line += 'N/A,' return -1 try: #Open the file we just downloaded print ('[-] Reading Malware Bazaar file: ' + output.strip()) with open(output.strip(), 'rb') as read_file: data = json.load(read_file, cls=None) read_file.close() # Check what kind of results we have query_status = data["query_status"] print ('[*] query_status: ' + query_status) if (query_status == 'ok'): with open(output.strip(), 'r') as read_file: for string in read_file: if (POE.debug == True): print ('[DEBUG] string: ' + string.strip()) if ('first_seen' in string): first_seen = string.strip() if ('last_seen' in string): last_seen = string.strip() if (('signature' in string) and (sig_count == 0)): signature = string.strip() sig_count += 1 print ('[*] Sample ' + first_seen.replace(',','')) print ('[*] Sample ' + last_seen.replace(',','')) print ('[*] Sample ' + signature.replace(',','')) if (POE.logging == True): newlogentry = 'Sample ' + first_seen.replace(',','') LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) newlogentry = 'Sample ' + last_seen.replace(',','') LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) newlogentry = 'Sample ' + signature.replace(',','') LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) #Can't find anything on this one... elif (query_status == 'hash_not_found'): print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold'])) if (POE.logging == True): newlogentry = 'No results available for host...' LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) #Can't find anything on this one... elif (query_status == 'no_results'): print (colored('[-] No results available for host...', 'yellow', attrs=['bold'])) if (POE.logging == True): newlogentry = 'No results available for host...' LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) #Something weird happened... else: print (colored('[x] An error has occurred...', 'red', attrs=['bold'])) if (POE.logging == True): newlogentry = 'An error has occurred...' LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) except Exception as e: print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold'])) read_file.close() return -1 #Clean up before returning read_file.close() return 0
slaughterjames/static
modules/malware_bazaar_search.py
Python
gpl-2.0
5,588
// QueenMaxima, a chess playing program. // Copyright (C) 1996-2013 Erik van het Hof and Hermen Reitsma // // 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 <string.h> #include <stdio.h> #include "hashcodes.h" #include "legality.h" #include "fast.h" #include "attack.h" bool _fast_moveokw (TFastNode* node, int move) // returns "move would be generated" { int ssq = SOURCESQ (move); int piece = PIECE (move); if ((!piece) || node -> matrix [ssq] != piece) { return false; } int tsq = TARGETSQ (move); if (! (move & _LL(4294934528))) { //a normal noncapture if (node->matrix[tsq]) { return false; } if (piece==PAWN) { return !node->matrix [ssq+8]; } return t.pieceattacks [piece] [ssq] [tsq] && (piece == KNIGHT || piece == KING || nooccs(node,ssq,tsq)); } else if (!SPECIAL(move)) { //a normal capture if (node->matrix [tsq] != CAPTURED (move) + KING) { return false; } return t.pieceattacks [piece][ssq][tsq] && (piece == PAWN || piece==KNIGHT || piece==KING || nooccs(node,ssq,tsq)); } else switch (SPECIALCASE (move)) { case _SHORT_CASTLE: return _SCW (node) && node -> matrix [g1] == 0 && node -> matrix [f1] == 0; case _LONG_CASTLE: return _LCW (node) && node -> matrix [b1] == 0 && node -> matrix [c1] == 0 && node -> matrix [d1] == 0; case _EN_PASSANT: return _EPSQ (node) == tsq && node -> matrix [ssq] == PAWN; default: // promotion if (_CAPTURE (move)) { return node -> matrix [ssq] == PAWN && node -> matrix [tsq] == CAPTURED (move)+KING; } else { return node -> matrix [ssq] == PAWN && node -> matrix [tsq] == 0; } } BOOST_ASSERT (false); return false; } bool _fast_moveokb(TFastNode* node, int move) { // returns "move would be generated" int ssq = SOURCESQ (move), piece = PIECE(move); if (!piece || node -> matrix [ssq] != piece+KING) { return false; } int tsq = TARGETSQ(move); if (! (move & _LL(4294934528))) { //not a special move or a capture if (node->matrix[tsq]) { return false; } if (piece==PAWN) { return !node->matrix[ssq-8]; } return (t.pieceattacks [piece] [tsq] [ssq] && (piece == KNIGHT || piece == KING || nooccs (node, ssq, tsq))); } else if (!SPECIAL (move)) { //a normal capture if (node->matrix [tsq] != CAPTURED (move)) { return false; } return t.pieceattacks [piece][tsq][ssq] && (piece == PAWN || piece==KNIGHT || piece==KING || nooccs (node, ssq, tsq)); } else switch (SPECIALCASE (move)) { case _SHORT_CASTLE: return _SCB (node) && (node -> matrix [g8] == 0) && (node -> matrix [f8] == 0); case _LONG_CASTLE: return _LCB (node) && (node -> matrix [b8] == 0) && (node -> matrix [c8] == 0) && (node -> matrix [d8] == 0); case _EN_PASSANT: return (_EPSQ (node) == tsq) && (node -> matrix [ssq] == BPAWN); default: // promotion if (_CAPTURE (move)) { return (node -> matrix [ssq] == BPAWN) && (node -> matrix [tsq] == CAPTURED (move)); } else { return (node -> matrix [ssq] == BPAWN) && (node -> matrix [tsq] == 0); } } BOOST_ASSERT (false); return false; } bool inspect_move_legality_b (TFastNode* node, int move) { bool result; int flags = node -> flags, fifty = node -> fifty; if (move == ENCODESCB) { return ! attacked_by_PNBRQK (node, e8) && ! attacked_by_PNBRQK (node, f8) && ! attacked_by_PNBRQK (node, g8); } if (move == ENCODELCB) { return ! attacked_by_PNBRQK (node, e8) && ! attacked_by_PNBRQK (node, d8) && ! attacked_by_PNBRQK (node, c8); } _fast_dobmove (node, move); result = ! attacked_by_PNBRQK (node, node -> bkpos); _fast_undobmove (node, move, flags, fifty); return result; } bool inspect_move_legality_w (TFastNode* node, int move) { bool result; int flags = node -> flags, fifty = node -> fifty; if (move == ENCODESCW) { return ! attacked_by_pnbrqk (node, e1) && ! attacked_by_pnbrqk (node, f1) && ! attacked_by_pnbrqk (node, g1); } if (move == ENCODELCW) { return ! attacked_by_pnbrqk (node, e1) && ! attacked_by_pnbrqk (node, d1) && ! attacked_by_pnbrqk (node, c1); } _fast_dowmove (node, move); result = ! attacked_by_pnbrqk (node, node -> wkpos); _fast_undowmove (node, move, flags, fifty); return result; } bool legal_move (TFastNode* node, int move) { if (node -> flags & _WTM) { return legal_move_w(node, move); } else { return legal_move_b(node, move); } } bool legal_move_w (TFastNode* node, int move) // returns "white move is legal in node" { int sq = SOURCESQ (move), offset_ssq_wk, offset_ssq_tsq, piece = PIECE (move); if (piece < KING) { // voor promoties, en_passant en normale zetten geldt: offset_ssq_wk = t.direction [sq] [node->wkpos]; if (! offset_ssq_wk) { return true; // niet op een lijn met de koning. vaak knalt ie er hier meteen weer uit. } offset_ssq_tsq = t.direction [sq] [TARGETSQ (move)]; if (offset_ssq_wk == offset_ssq_tsq || offset_ssq_wk == - offset_ssq_tsq) { return true; // stuk blijft op dezelfde lijn } if (! SPECIAL (move) || SPECIALCASE (move) != _EN_PASSANT || (offset_ssq_wk != 1 && offset_ssq_wk != -1)) { // uitzonderingen met en_passant komen alleen voor als koning en pion op hor. lijn staan (toch?) // omdat er bij enpassant slaan twee stukken van de horizontale lijn verdwijnen. sq += offset_ssq_wk; while (sq != node -> wkpos) { if (node -> matrix [sq]) { return true; // niet gepind want er staat een stuk (w/z) tussen } sq += offset_ssq_wk; } sq = t.sqonline [node -> wkpos] [SOURCESQ (move)]; while (sq != node -> wkpos) { BOOST_ASSERT (sq >= 0 && sq <= 63); piece = node -> matrix [sq]; if (piece) { return piece < BBISHOP || ! t.pieceattacks [piece - KING] [sq] [node->wkpos]; } sq = t.sqonline [node -> wkpos] [sq]; } return true; } // en passant en koning, pion en geslagen pion op 1 horizontale lijn int csq = TARGETSQ (move) - 8; sq += offset_ssq_wk; while (sq != node->wkpos) { if (node -> matrix [sq] && (sq != csq)) { return true; // niet gepind want er staat een stuk (w/z) tussen } sq += offset_ssq_wk; } sq = t.sqonline [node -> wkpos] [SOURCESQ (move)]; while (sq != node -> wkpos) { BOOST_ASSERT (sq >= 0 && sq <= 63); piece = node -> matrix [sq]; if (piece && (sq != csq)) { return piece < BROOK || ! t.pieceattacks [piece - KING] [sq] [node -> wkpos]; } sq = t.sqonline [node -> wkpos] [sq]; } return true; } // de koning zet if (attacked_by_pnbrqk (node, TARGETSQ (move))) { return false; } if (! SPECIAL (move)) { return true; } if (attacked_by_pnbrqk (node, e1)) { return false; } if (move == ENCODESCW) { return ! attacked_by_pnbrqk (node, f1); } return ! attacked_by_pnbrqk (node, d1); } bool legal_move_b (TFastNode* node, int move) // returns "black move is legal in node" { int sq = SOURCESQ (move), offset_ssq_bk, offset_ssq_tsq, piece = PIECE (move); if (piece < KING) { // voor promoties, en_passant en normale zetten geldt: offset_ssq_bk = t.direction [sq] [node->bkpos]; if (! offset_ssq_bk) { return true; // niet op een lijn met de koning. vaak knalt ie er hier meteen weer uit. } offset_ssq_tsq = t.direction [sq] [TARGETSQ (move)]; if (offset_ssq_bk == offset_ssq_tsq || offset_ssq_bk == - offset_ssq_tsq) { return true; // stuk blijft op dezelfde lijn } sq += offset_ssq_bk; if (! SPECIAL (move) || SPECIALCASE (move) != _EN_PASSANT || (offset_ssq_bk != 1 && offset_ssq_bk != -1)) { // uitzonderingen met en_passant komen alleen voor als koning en pion op hor. lijn staan (toch?) // omdat er bij enpassant slaan twee stukken van de horizontale lijn verdwijnen. while (sq != node -> bkpos) { if (node -> matrix [sq]) { return true; // niet gepind want er staat een stuk (w/z) tussen } sq += offset_ssq_bk; } sq = t.sqonline [node -> bkpos] [SOURCESQ (move)]; while (sq != node -> bkpos) { BOOST_ASSERT (sq >= 0 && sq <= 63); piece = node -> matrix [sq]; if (piece) { return piece > QUEEN || piece < BISHOP || ! t.pieceattacks [piece] [sq] [node->bkpos]; } sq = t.sqonline [node -> bkpos] [sq]; } return true; } // en passant en koning, pion en geslagen pion op 1 horizontale lijn int csq = TARGETSQ (move) + 8; while (sq != node -> bkpos) { if (node -> matrix [sq] && sq != csq) { return true; // niet gepind want er staat een stuk (w/z) tussen } sq += offset_ssq_bk; } sq = t.sqonline [node -> bkpos] [ SOURCESQ (move)]; while (sq != node -> bkpos) { BOOST_ASSERT (sq >= 0 && sq <= 63); piece = node -> matrix [sq]; if (piece && sq != csq) { return piece > QUEEN || piece < ROOK || ! t.pieceattacks [piece] [sq] [node -> bkpos]; } sq = t.sqonline [node -> bkpos] [sq]; } return true; } // de koning zet if (attacked_by_PNBRQK (node, TARGETSQ (move))) { return false; } if (! SPECIAL (move)) { return true; } if (attacked_by_PNBRQK (node, e8)) { return false; } if (move == ENCODESCB) { return ! attacked_by_PNBRQK (node, f8); } return ! attacked_by_PNBRQK (node, d8); } int _fast_inspectnode (TFastNode* node) { _int64 hashcode = 0, pawncode = 0; int i; if ((bool)((node -> hashcode & 1) > 0) != (bool)((node -> flags & _WTM) >0)) { return 500; } if (node->wpawns > 8 || node->wpawns < 0) { return 1; } if (node->wknights + node->wpawns > 10 || node->wknights < 0) { return 2; } if (node->wbishops + node->wpawns > 10 || node->wbishops < 0) { return 3; } if (node->wrooks + node->wpawns > 10 || node->wrooks < 0) { return 4; } if (node->wqueens + node->wpawns > 10 || node->wqueens < 0) { return 5; } if (node->wkpos < 0 || node->wkpos > 63) { return 6; } if (node->bpawns > 8 || node->bpawns < 0) { return 11; } if (node->bknights + node->bpawns > 10 || node->bknights < 0) { return 12; } if (node->bbishops + node->bpawns > 10 || node->bbishops < 0) { return 13; } if (node->brooks + node->bpawns > 10 || node->brooks < 0) { return 14; } if (node->bqueens + node->bpawns > 10 || node->bqueens < 0) { return 15; } if (node->bkpos < 0 || node->bkpos > 63) { return 16; } int sq; char matrix[64]; memset (matrix, 0, sizeof (matrix)); for (i = 0; i < node->wpawns; i++) { sq = node->wpawnlist [i]; hashcode ^= hashnumbers [PAWN - 1] [sq]; pawncode ^= hashnumbers [PAWN - 1] [sq]; if (node->index [sq] != i) { std::cout << boost::format("node->index[%d] = %d ; i = %d\n") % sq % node->index[sq] % i; return 21; } matrix [sq] = PAWN; if (node->matrix [sq] != PAWN) { return 41; } } for (i = 0; i < node->wknights; i++) { sq = node->wknightlist [i]; hashcode ^= hashnumbers [KNIGHT - 1] [sq]; if (node->index [sq] != i) { return 22; } matrix [sq] = KNIGHT; if (node->matrix [sq] != KNIGHT) { return 42; } } for (i = 0; i < node->wbishops; i++) { sq = node->wbishoplist [i]; hashcode ^= hashnumbers [BISHOP - 1] [sq]; if (node->index [sq] != i) { return 23; } matrix [sq] = BISHOP; if (node->matrix [sq] != BISHOP) { return 43; } } for (i = 0; i < node->wrooks; i++) { sq = node->wrooklist [i]; hashcode ^= hashnumbers [ROOK - 1] [sq]; if (node->index [sq] != i) { return 24; } matrix [sq] = ROOK; if (node->matrix [sq] != ROOK) { return 44; } } for (i = 0; i < node->wqueens; i++) { sq = node->wqueenlist [i]; hashcode ^= hashnumbers [QUEEN - 1] [sq]; if (node->index [sq] != i) { return 25; } matrix [sq] = QUEEN; if (node->matrix [sq] != QUEEN) { return 45; } } matrix [node->wkpos] = KING; hashcode ^= hashnumbers [KING - 1] [node -> wkpos]; if (node->matrix [node->wkpos] != KING) { return 46; } for (i = 0; i < node->bpawns; i++) { sq = node->bpawnlist [i]; hashcode ^= hashnumbers [BPAWN - 1] [sq]; pawncode ^= hashnumbers [BPAWN - 1] [sq]; if (node->index [sq] != i) { return 31; } matrix [sq] = BPAWN; if (node->matrix [sq] != BPAWN) { return 51; } } for (i = 0; i < node->bknights; i++) { sq = node->bknightlist [i]; hashcode ^= hashnumbers [BKNIGHT - 1] [sq]; if (node->index [sq] != i) { return 32; } matrix [sq] = BKNIGHT; if (node->matrix [sq] != BKNIGHT) { return 52; } } for (i = 0; i < node->bbishops; i++) { sq = node->bbishoplist [i]; hashcode ^= hashnumbers [BBISHOP - 1] [sq]; if (node->index [sq] != i) { return 33; } matrix [sq] = BBISHOP; if (node->matrix [sq] != BBISHOP) { return 53; } } for (i = 0; i < node->brooks; i++) { sq = node->brooklist [i]; hashcode ^= hashnumbers [BROOK - 1] [sq]; if (node->index [sq] != i) { return 34; } matrix [sq] = BROOK; if (node->matrix [sq] != BROOK) { return 54; } } for (i = 0; i < node->bqueens; i++) { sq = node->bqueenlist [i]; hashcode ^= hashnumbers [BQUEEN - 1] [sq]; if (node->index [sq] != i) { return 35; } matrix [sq] = BQUEEN; if (node->matrix [sq] != BQUEEN) { return 55; } } matrix [node->bkpos] = BKING; hashcode ^= hashnumbers [BKING - 1] [node -> bkpos]; if (node->matrix [node->bkpos] != BKING) { return 56; } if (memcmp (matrix, node->matrix, sizeof (matrix))) { return 100; } if (_SCW(node)) { hashcode ^= _LL(0x47bc71a493da706e); } if (_SCB(node)) { hashcode ^= _LL(0x6fed622e98f98b7e); } if (_LCW(node)) { hashcode ^= _LL(0x6338be439fd357dc); } if (_LCB(node)) { hashcode ^= _LL(0xce107ca2947d2d58); } if (_EPSQ(node)) { hashcode ^= ephash [_EPSQ (node)]; } if (node-> flags & _WTM) { hashcode |= 1; } else { hashcode &= _LL(0xFFFFFFFFFFFFFFFE); } if (hashcode != node -> hashcode) { std::cout << boost::format("hashcode = %Ld, node -> hashcode = %Ld\n") % hashcode % node -> hashcode; return 200; } if (pawncode != node -> pawncode) { std::cout << boost::format("pawncode = %Ld, node -> pawncode = %Ld\n") % pawncode % node -> pawncode; return 201; } // if (_result_value < -CHESS_INF || _result_value > CHESS_INF) { // return 300; // } return 0; }
hof/queenmaxima
src/legality.cpp
C++
gpl-2.0
14,849
<?php /* * Comments cell type. * Displays form and coments * */ if( !function_exists('register_comments_cell_init') ) { function register_comments_cell_init() { if ( function_exists('register_dd_layout_cell_type') ) { register_dd_layout_cell_type ( 'comments-cell', array ( 'name' => __('Comments', 'ddl-layouts'), 'description' => __('Display the comments section. This cell is typically used in layouts for blog posts and pages that need comments enable.', 'ddl-layouts'), 'category' => __('Site elements', 'ddl-layouts'), 'cell-image-url' => DDL_ICONS_SVG_REL_PATH.'layouts-comments-cell.svg', 'button-text' => __('Assign comments cell', 'ddl-layouts'), 'dialog-title-create' => __('Create a new comments cell', 'ddl-layouts'), 'dialog-title-edit' => __('Edit comments cell', 'ddl-layouts'), 'dialog-template-callback' => 'comments_cell_dialog_template_callback', 'cell-content-callback' => 'comments_cell_content_callback', 'cell-template-callback' => 'comments_cell_template_callback', 'has_settings' => true, 'cell-class' => '', 'preview-image-url' => DDL_ICONS_PNG_REL_PATH . 'comments_expand-image.png', 'allow-multiple' => false, 'register-scripts' => array( array( 'ddl-comments-cell-script', WPDDL_GUI_RELPATH . 'editor/js/ddl-comments-cell-script.js', array( 'jquery' ), WPDDL_VERSION, true ), ), 'translatable_fields' => array( 'title_one_comment' => array('title' => 'One comment text', 'type' => 'LINE'), 'title_multi_comments' => array('title' => 'Multiple comments text', 'type' => 'LINE'), 'ddl_prev_link_text' => array('title' => 'Older Comments text', 'type' => 'LINE'), 'ddl_next_link_text' => array('title' => 'Newer Comments text', 'type' => 'LINE'), 'comments_closed_text' => array('title' => 'Comments are closed text', 'type' => 'LINE'), 'reply_text' => array('title' => 'Reply text', 'type' => 'LINE'), 'password_text' => array('title' => 'Password protected post text', 'type' => 'LINE') ) ) ); add_action( 'wp_ajax_ddl_load_comments_page_content', 'ddl_load_comments_page_content' ); add_action( 'wp_ajax_nopriv_ddl_load_comments_page_content', 'ddl_load_comments_page_content' ); } } add_action( 'init', 'register_comments_cell_init' ); function comments_cell_dialog_template_callback() { ob_start(); ?> <h3 class="ddl-section-title"> <?php _e('Comments list', 'ddl-layouts'); ?> </h3> <div class="ddl-form"> <p> <label for="<?php the_ddl_name_attr('avatar_size'); ?>"><?php _e( 'Avatar size', 'ddl-layouts' ) ?>:</label> <input type="number" value="24" placeholder="<?php _e( '32', 'ddl-layouts' ) ?>" name="<?php the_ddl_name_attr('avatar_size'); ?>" id="<?php the_ddl_name_attr('avatar_size'); ?>" class="ddl-narrow-width" onkeypress='return event.charCode >= 48 && event.charCode <= 57'> </p> </div> <h3 class="ddl-section-title"> <?php _e( 'Title for comments list', 'ddl-layouts' ) ?> </h3> <div class="ddl-form"> <p> <label for="<?php the_ddl_name_attr('title_one_comment'); ?>"><?php _e( 'For one comment', 'ddl-layouts' ) ?>:</label> <input type="text" name="<?php the_ddl_name_attr('title_one_comment'); ?>" id="<?php the_ddl_name_attr('title_one_comment'); ?>" value="<?php _e( 'One thought on %TITLE%', 'ddl-layouts' ) ?>"> <div id="title_one_comment_message"></div> </p> <p> <label for="<?php the_ddl_name_attr('title_multi_comments'); ?>"><?php _e( 'For two or more', 'ddl-layouts' ) ?>:</label> <input type="text" name="<?php the_ddl_name_attr('title_multi_comments'); ?>" id="<?php the_ddl_name_attr('title_multi_comments'); ?>" value="<?php _e( '%COUNT% thoughts on %TITLE%', 'ddl-layouts' ) ?>"> <div id="title_multi_comments_message"></div> <span class="desc"><?php _e( 'Use the %TITLE% placeholder to display the post title and the %COUNT% placeholder to display the number of comments.', 'ddl-layouts' ) ?></span> </p> </div> <h3 class="ddl-section-title"> <?php _e( 'Navigation and miscellaneous texts', 'ddl-layouts' ) ?> </h3> <div class="ddl-form"> <p> <label for="<?php the_ddl_name_attr('ddl_prev_link_text'); ?>"><?php _e( 'Previous link text', 'ddl-layouts' ) ?>:</label> <input type="text" name="<?php the_ddl_name_attr('ddl_prev_link_text'); ?>" id="<?php the_ddl_name_attr('ddl_prev_link_text'); ?>" value="<?php _e( '<< Older Comments', 'ddl-layouts' ) ?>"> </p> <p> <label for="<?php the_ddl_name_attr('ddl_next_link_text'); ?>"><?php _e( 'Next link text', 'ddl-layouts' ) ?>:</label> <input type="text" name="<?php the_ddl_name_attr('ddl_next_link_text'); ?>" id="<?php the_ddl_name_attr('ddl_next_link_text'); ?>" value="<?php _e( 'Newer Comments >>', 'ddl-layouts' ) ?>"> </p> <p> <label for="<?php the_ddl_name_attr('comments_closed_text'); ?>"><?php _e( 'Comments closed text', 'ddl-layouts' ) ?>:</label> <input type="text" name="<?php the_ddl_name_attr('comments_closed_text'); ?>" id="<?php the_ddl_name_attr('comments_closed_text'); ?>" value="<?php _e( 'Comments are closed', 'ddl-layouts' ) ?>"> <div id="comments_closed_text_message"></div> </p> <p> <label for="<?php the_ddl_name_attr('reply_text'); ?>"><?php _e( 'Reply text', 'ddl-layouts' ) ?>:</label> <input type="text" name="<?php the_ddl_name_attr('reply_text'); ?>" id="<?php the_ddl_name_attr('reply_text'); ?>" value="<?php _e( 'Reply', 'ddl-layouts' ) ?>"> <div id="reply_text_message"></div> </p> <p> <label for="<?php the_ddl_name_attr('password_text'); ?>"><?php _e( 'Password protected text', 'ddl-layouts' ) ?>:</label> <input type="text" name="<?php the_ddl_name_attr('password_text'); ?>" id="<?php the_ddl_name_attr('password_text'); ?>" value="<?php _e( 'This post is password protected. Enter the password to view any comments.', 'ddl-layouts' ) ?>"> <div id="password_text_message"></div> </p> </div> <div class="ddl-form"> <div class="ddl-form-item"> <br /> <?php ddl_add_help_link_to_dialog(WPDLL_COMMENTS_CELL, __('Learn about the Comments cell', 'ddl-layouts')); ?> </div> </div> <?php global $current_user; get_currentuserinfo(); ?> <?php return ob_get_clean(); } // Callback function for displaying the cell in the editor. function comments_cell_template_callback() { ob_start(); ?> <div class="cell-content"> <p class="cell-name">{{ name }} &ndash; <?php _e('Comment Cell', 'ddl-layouts'); ?></p> <div class="cell-preview"> <div class="ddl-comments-preview"> <img src="<?php echo WPDDL_RES_RELPATH . '/images/cell-icons/comments.svg'; ?>" height="130px"> </div> </div> </div> <?php return ob_get_clean(); } //Hook for previous page link, add post id and prev page to link function ddl_add_previous_comments_link_data(){ global $post; if ( !isset($post->ID)){ return; } $page = get_query_var('cpage'); if ( intval($page) <= 1 ){ return; } $prevpage = intval($page) - 1; return ' data-page="'.$prevpage.'" data-postid="'.$post->ID.'" '; } //Hook for next page link, add post id and next page to link function ddl_add_next_comments_link_data(){ global $post; if ( !isset($post->ID)){ return; } $page = get_query_var('cpage'); $nextpage = intval($page) + 1; return ' data-page="'.$nextpage.'" data-postid="'.$post->ID.'" '; } //Load page content, Ajax pagination. Most of code same, so we can do one function for this function ddl_load_comments_page_content(){ $nonce = $_POST["wpnonce"]; if (! wp_verify_nonce( $nonce, 'ddl_comments_listing_page' ) ) { echo 'Error'; } else { global $wpddlayout, $wp_query, $withcomments, $wpdb, $id, $post, $comment, $user_login, $user_ID, $user_identity, $overridden_cpage; if ( !isset($_POST['page']) && !isset($_POST['postid']) ){ echo 'Error'; } $load_page = $_POST['page']; // Current page to load $post_id = $_POST['postid']; $post = get_post($post_id); // Get post setup_postdata( $post ); // load global $post $comments = ddl_load_comments_array(); set_query_var('cpage' ,$load_page); //Set query page $overridden_cpage = true; $wp_query->query = array( 'page_id' => $post->ID, 'cpage' => $load_page); set_query_var( 'post_id', $post->ID); set_query_var( 'p', $post->ID); $wp_query->is_singular = 1; $layout_id = $_POST['layout_name']; $cell_id = $_POST['cell_id']; get_the_ddlayout($layout_id); global $wpddlayout; $wpddlayout->set_up_cell_fields_by_id( $cell_id, $layout_id ); $post = get_post($post_id); // Get post setup_postdata( $post ); // load global $post } $comments_list = ddl_render_comments_list( $comments, $post, $load_page); echo $comments_list; die(); } // Callback function for display the cell in the front end. function comments_cell_content_callback() { global $wpddlayout, $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity, $overridden_cpage; if ( !(is_single() || is_page() || $withcomments) || empty($post) ) return; $wpddlayout->enqueue_scripts('ddl-comment-cell-front-end'); $wpddlayout->localize_script('ddl-comment-cell-front-end', 'DDL_Comments_cell', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'security' => wp_create_nonce( 'ddl_comments_listing_page' ), 'layout_name' => $wpddlayout->get_rendered_layout_id(), 'cell_id' => get_ddl_field('unique_id') )); $comments = ddl_load_comments_array(); $overridden_cpage = false; if ( '' == get_query_var('cpage') && get_option('page_comments') ) { set_query_var( 'cpage', 'newest' == get_option('default_comments_page') ? get_comment_pages_count() : 1 ); $overridden_cpage = true; } $load_page = ''; if ( isset($_GET['cpage']) ){ $load_page = $_GET['cpage']; } $comments_list = ddl_render_comments_list( $comments, $post, $load_page); return $comments_list; } //Get comments array for current post function ddl_load_comments_array(){ global $wpddlayout, $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity, $overridden_cpage; $commenter = wp_get_current_commenter(); $comment_author = $commenter['comment_author']; $comment_author_email = $commenter['comment_author_email']; $comment_author_url = esc_url($commenter['comment_author_url']); if ( $user_ID) { $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND (comment_approved = '1' OR ( user_id = %d AND comment_approved = '0' ) ) ORDER BY comment_date_gmt", $post->ID, $user_ID)); } else if ( empty($comment_author) ) { $comments = get_comments( array('post_id' => $post->ID, 'status' => 'approve', 'order' => 'ASC') ); } else { $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND ( comment_approved = '1' OR ( comment_author = %s AND comment_author_email = %s AND comment_approved = '0' ) ) ORDER BY comment_date_gmt", $post->ID, wp_specialchars_decode($comment_author,ENT_QUOTES), $comment_author_email)); } $wp_query->comments = apply_filters( 'comments_array', $comments, $post->ID ); $comments = &$wp_query->comments; $wp_query->comment_count = count($wp_query->comments); update_comment_cache($wp_query->comments); return $comments; } //Generate comments listing function ddl_render_comments_list($comments, $post, $load_page=''){ ob_start(); ?> <div id="comments"> <?php if ( post_password_required($post) ) : ?> <p class="nopassword"><?php the_ddl_field('password_text'); ?></p> </div><!-- #comments --> <?php return ob_get_clean(); endif; ?> <?php if ( comments_open() ): $num_comments = get_comments_number(); ?> <?php if ( $num_comments > 0 ): ?> <h2 id="comments-title"> <?php $one_comment_text = str_replace( array('%TITLE%', '%COUNT%'), array('%2$s','%1$s'), get_ddl_field('title_one_comment')); $two_comments_text = str_replace( array('%TITLE%', '%COUNT%'), array('%2$s','%1$s'), get_ddl_field('title_multi_comments')); printf( _n( $one_comment_text, $two_comments_text, $num_comments ), number_format_i18n( $num_comments ), '<span>' . $post->post_title . '</span>' ); ?> </h2> <?php if ( get_comment_pages_count($comments) > 1 && get_option( 'page_comments' ) ):?> <?php add_filter('previous_comments_link_attributes','ddl_add_previous_comments_link_data'); add_filter('next_comments_link_attributes','ddl_add_next_comments_link_data'); ?> <nav id="comment-nav-above"> <div class="nav-previous js-ddl-previous-link"><?php previous_comments_link( get_ddl_field('ddl_prev_link_text') ); ?></div> <div class="nav-next js-ddl-next-link"><?php next_comments_link( get_ddl_field('ddl_next_link_text') ); ?></div> </nav> <?php endif; // check for comment navigation ?> <?php $comments_defaults = array(); //Set comments style $comments_defaults['style'] = apply_filters('ddl_comment_cell_style', 'ul'); //Avatar Size if ( get_ddl_field('avatar_size') != '' ){ $comments_defaults['avatar_size'] = get_ddl_field('avatar_size'); } //Reply text if ( get_ddl_field('reply_text') != '' ){ $comments_defaults['reply_text'] = get_ddl_field('reply_text'); } if ( get_comment_pages_count($comments) > 1 && get_option( 'page_comments' ) ): $comments_defaults['per_page'] = get_option('comments_per_page'); if ( empty($load_page) ){ if ('newest' == get_option('default_comments_page')){ $comments_defaults['page'] = get_comment_pages_count($comments); }else{ $comments_defaults['page'] = 1; } }else{ //Current page $comments_defaults['page'] = $load_page; } endif; $before_comments_list = '<ul class="commentlist">'; $after_comments_list = '</ul>'; if ( $comments_defaults['style'] == 'ol' ){ $before_comments_list = '<ol class="commentlist">'; $after_comments_list = '</ol>'; } if ( $comments_defaults['style'] == 'div' ){ $before_comments_list = '<div class="commentlist">'; $after_comments_list = '</div>'; } echo '<div id="comments-listing">'; echo $before_comments_list; //Generate and print comments listing wp_list_comments( $comments_defaults, $comments ); echo $after_comments_list; echo '</div>'; ?> <?php endif;?> <?php // Generate comment form comment_form(); ?> <?php else:?> <p class="nocomments"><?php the_ddl_field('comments_closed_text'); ?></p> <?php endif;?> </div> <?php return ob_get_clean(); } }
juliusmiranda/wordpress
wp-content/plugins/layouts/classes/cell_types/wpddl.cell_comments.class.php
PHP
gpl-2.0
15,614
<? class CategoryID extends Handler { protected $REST_vars; protected $DBs; protected $User; // RUN // public function run() { switch ( $this->REST_vars["method"] ) { case "get": $this->get(); break; case "delete": case "put": case "post": default: throw new Error($GLOBALS["HTTP_STATUS"]["Bad Request"], get_class($this) . " Error: Request method not supported."); } } // * // // GET // protected function get() { // Get category with given categoryID $select = " SELECT `id`, `name` FROM `Categories` WHERE `id` = ? "; $binds = ["i", $this->REST_vars["categoryID"]]; $res = $this->DBs->select($select, $binds); if ( is_null($res) ) { throw new Error($GLOBALS["HTTP_STATUS"]["Internal Error"], get_class($this) . " Error: Failed to retrieve request."); } $JSON = []; while ($row = $res->fetch_assoc()) { $obj = []; $obj["id"] = $row['id']; $obj["name"] = $row['name']; $JSON[] = $obj; } //// $this->send( $JSON, $GLOBALS["HTTP_STATUS"]["OK"] ); } // * // } ?>
jetwhiz/jackelo
jackelow.gjye.com/api/category/category-id.php
PHP
gpl-2.0
1,147
<?php /** * Controllo se il file viene richiamato direttamente senza * essere incluso dalla procedura standard del plugin. * * @package SZGoogle */ if (!defined('SZ_PLUGIN_GOOGLE') or !SZ_PLUGIN_GOOGLE) die(); /** * Definizione variabile HTML per la preparazione della stringa * che contiene la documentazione di questa funzionalità */ $HTML = <<<EOD <h2>Documentation</h2> <p>With this feature you can place on its website a widget that displays the recommendations related to the pages of your website based on social iterations. This feature will be displayed only on the mobile version of the web site and ignored on different devices. To enable this option, you must select the specific field that you find the admin panel but you also need to perform operations on google+ page connected to your site. <a target="_blank" href="https://developers.google.com/+/web/recommendations/?hl=it">Content recommendations for mobile websites</a>.</p> <h2>Configuration</h2> <p>In the settings section of the Google+ page you can control the behavior of the widget that relates to the advice and the display mode. So do not try to change these settings in the options but use the plugin configuration page directly on google plus.</p> <p><b>The following options are available from the settings page:</b></p> <ul> <li>Turn on or off recommendations.</li> <li>Choose pages or paths which should not show recommendations.</li> <li>Choose pages or paths to prevent from displaying in the recommendations bar.</li> </ul> <p><b>Choose when to show the recommendations bar:</b></p> <ul> <li>When the user scrolls up.</li> <li>When the user scrolls past an element with a specified ID.</li> <li>When the user scrolls past an element that matches a DOM query selector.</li> </ul> <h2>Warnings</h2> <p>The plugin <b>SZ-Google</b> has been developed with a technique of loading individual modules to optimize overall performance, so before you use a shortcode, a widget, or a PHP function you should check that the module general and the specific option appears enabled via the field dedicated option that you find in the admin panel.</p> EOD; /** * Richiamo della funzione per la creazione della pagina di * documentazione standard in base al contenuto della variabile HTML */ $this->moduleCommonFormHelp(__('google+ recommendations','szgoogleadmin'),NULL,NULL,false,$HTML,basename(__FILE__));
mathewhtc/cats
wp-content/plugins/sz-google/admin/help/en/sz-google-help-plus-recommendations.php
PHP
gpl-2.0
2,411
# BurnMan - a lower mantle toolkit # Copyright (C) 2012-2014, Myhill, R., Heister, T., Unterborn, C., Rose, I. and Cottaar, S. # Released under GPL v2 or later. # This is a standalone program that converts a tabulated version of the Stixrude and Lithgow-Bertelloni data format into the standard burnman format (printed to stdout) import sys def read_dataset(datafile): f=open(datafile,'r') ds=[] for line in f: ds.append(line.decode('utf-8').split()) return ds ds=read_dataset('HHPH2013_endmembers.dat') print '# BurnMan - a lower mantle toolkit' print '# Copyright (C) 2012, 2013, Heister, T., Unterborn, C., Rose, I. and Cottaar, S.' print '# Released under GPL v2 or later.' print '' print '"""' print 'HHPH_2013' print 'Minerals from Holland et al 2013 and references therein' print 'The values in this document are all in S.I. units,' print 'unlike those in the original paper' print 'File autogenerated using HHPHdata_to_burnman.py' print '"""' print '' print 'from burnman.mineral import Mineral' print 'from burnman.solidsolution import SolidSolution' print 'from burnman.solutionmodel import *' print 'from burnman.processchemistry import read_masses, dictionarize_formula, formula_mass' print '' print 'atomic_masses=read_masses()' print '' print '"""' print 'ENDMEMBERS' print '"""' print '' param_scales = [ -1., -1., #not nubmers, so we won't scale 1.e3, 1.e3, #kJ -> J 1.0, # J/K/mol 1.e-5, # kJ/kbar/mol -> m^3/mol 1.e3, 1.e-2, 1.e3, 1.e3, # kJ -> J and table conversion for b 1.e-5, # table conversion 1.e8, # kbar -> Pa 1.0, # no scale for K'0 1.e-8] #GPa -> Pa # no scale for eta_s formula='0' for idx, m in enumerate(ds): if idx == 0: param_names=m else: print 'class', m[0].lower(), '(Mineral):' print ' def __init__(self):' print ''.join([' formula=\'',m[1],'\'']) print ' formula = dictionarize_formula(formula)' print ' self.params = {' print ''.join([' \'name\': \'', m[0], '\',']) print ' \'formula\': formula,' print ' \'equation_of_state\': \'hp_tmt\',' for pid, param in enumerate(m): if pid > 1 and pid != 3 and pid<6: print ' \''+param_names[pid]+'\':', float(param)*param_scales[pid], ',' print ' \'Cp\':', [round(float(m[i])*param_scales[i],10) for i in [6, 7, 8, 9]], ',' for pid, param in enumerate(m): if pid > 9: print ' \''+param_names[pid]+'\':', float(param)*param_scales[pid], ',' print ' \'n\': sum(formula.values()),' print ' \'molar_mass\': formula_mass(formula, atomic_masses)}' print '' print ' self.uncertainties = {' print ' \''+param_names[3]+'\':', float(m[3])*param_scales[3], '}' print ' Mineral.__init__(self)' print ''
QuLogic/burnman
burnman/data/input_raw_endmember_datasets/HHPH2013data_to_burnman.py
Python
gpl-2.0
3,130
const fs = require('fs'); const util = require('../../util'); // test equality function equal(a, b, options) { if (a === b) { return options.fn(this); } return options.inverse(this); } // great than function gt(a, b, options) { if (a >= b) { return options.fn(this); } return options.inverse(this); } // between function between(a, b, c, options) { if (a >= b && a <= c) { return options.fn(this); } return options.inverse(this); } // less than function lt(a, b, options) { if (a < b) { return options.fn(this); } return options.inverse(this); } function ignoreNan(val, symbol) { const isNumber = (val >= 0 || val < 0); return isNumber ? `${util.roundDecimal(val, 2)} ${symbol}` : ''; } // test inequality function inequal(a, b, options) { if (a !== b) { return options.fn(this); } return options.inverse(this); } // test File Exit function fileExist(a, b, options) { try { fs.statSync(`${a}${b}`); return options.fn(this); } catch (err) { return options.inverse(this); } } exports.equal = equal; exports.gt = gt; exports.lt = lt; exports.between = between; exports.ignoreNan = ignoreNan; exports.inequal = inequal; exports.fileExist = fileExist;
IMA-WorldHealth/bhima
server/lib/template/helpers/logic.js
JavaScript
gpl-2.0
1,228
<?php /** * @file * Definition of Drupal\views_ui\ViewUI. */ namespace Drupal\views_ui; use Drupal\views\ViewExecutable; use Drupal\Core\Database\Database; use Drupal\Core\TypedData\ContextAwareInterface; use Drupal\views\Plugin\views\query\Sql; use Drupal\views\Plugin\Core\Entity\View; use Drupal\views\ViewStorageInterface; /** * Stores UI related temporary settings. */ class ViewUI implements ViewStorageInterface { /** * Indicates if a view is currently being edited. * * @var bool */ public $editing = FALSE; /** * Stores an array of errors for any displays. * * @var array */ public $display_errors; /** * Stores an array of displays that have been changed. * * @var array */ public $changed_display; /** * How long the view takes to build. * * @var int */ public $build_time; /** * How long the view takes to render. * * @var int */ public $render_time; /** * How long the view takes to execute. * * @var int */ public $execute_time; /** * If this view is locked for editing. * * @var bool */ public $locked; /** * If this view has been changed. * * @var bool */ public $changed; /** * Stores options temporarily while editing. * * @var array */ public $temporary_options; /** * Stores a stack of UI forms to display. * * @var array */ public $stack; /** * Is the view runned in a context of the preview in the admin interface. * * @var bool */ public $live_preview; public $displayID; public $renderPreview = FALSE; /** * The View storage object. * * @var \Drupal\views\Plugin\Core\Entity\View */ protected $storage; /** * The View executable object. * * @var \Drupal\views\ViewExecutable */ protected $executable; /** * Constructs a View UI object. * * @param \Drupal\views\ViewStorageInterface $storage * The View storage object to wrap. */ public function __construct(ViewStorageInterface $storage) { $this->entityType = 'view'; $this->storage = $storage; $this->executable = $storage->get('executable'); } /** * Overrides \Drupal\Core\Config\Entity\ConfigEntityBase::get(). */ public function get($property_name, $langcode = NULL) { if (property_exists($this->storage, $property_name)) { return $this->storage->get($property_name, $langcode); } return isset($this->{$property_name}) ? $this->{$property_name} : NULL; } /** * Overrides \Drupal\Core\Config\Entity\ConfigEntityBase::set(). */ public function set($property_name, $value) { if (property_exists($this->storage, $property_name)) { $this->storage->set($property_name, $value); } else { $this->{$property_name} = $value; } } public static function getDefaultAJAXMessage() { return '<div class="message">' . t("Click on an item to edit that item's details.") . '</div>'; } /** * Basic submit handler applicable to all 'standard' forms. * * This submit handler determines whether the user wants the submitted changes * to apply to the default display or to the current display, and dispatches * control appropriately. */ public function standardSubmit($form, &$form_state) { // Determine whether the values the user entered are intended to apply to // the current display or the default display. list($was_defaulted, $is_defaulted, $revert) = $this->getOverrideValues($form, $form_state); // Based on the user's choice in the display dropdown, determine which display // these changes apply to. if ($revert) { // If it's revert just change the override and return. $display = &$this->executable->displayHandlers->get($form_state['display_id']); $display->optionsOverride($form, $form_state); // Don't execute the normal submit handling but still store the changed view into cache. views_ui_cache_set($this); return; } elseif ($was_defaulted === $is_defaulted) { // We're not changing which display these form values apply to. // Run the regular submit handler for this form. } elseif ($was_defaulted && !$is_defaulted) { // We were using the default display's values, but we're now overriding // the default display and saving values specific to this display. $display = &$this->executable->displayHandlers->get($form_state['display_id']); // optionsOverride toggles the override of this section. $display->optionsOverride($form, $form_state); $display->submitOptionsForm($form, $form_state); } elseif (!$was_defaulted && $is_defaulted) { // We used to have an override for this display, but the user now wants // to go back to the default display. // Overwrite the default display with the current form values, and make // the current display use the new default values. $display = &$this->executable->displayHandlers->get($form_state['display_id']); // optionsOverride toggles the override of this section. $display->optionsOverride($form, $form_state); $display->submitOptionsForm($form, $form_state); } $submit_handler = $form['#form_id'] . '_submit'; if (function_exists($submit_handler)) { $submit_handler($form, $form_state); } } /** * Submit handler for cancel button */ public function standardCancel($form, &$form_state) { if (!empty($this->changed) && isset($this->form_cache)) { unset($this->form_cache); views_ui_cache_set($this); } $form_state['redirect'] = 'admin/structure/views/view/' . $this->id() . '/edit'; } /** * Provide a standard set of Apply/Cancel/OK buttons for the forms. Also provide * a hidden op operator because the forms plugin doesn't seem to properly * provide which button was clicked. * * TODO: Is the hidden op operator still here somewhere, or is that part of the * docblock outdated? */ public function getStandardButtons(&$form, &$form_state, $form_id, $name = NULL, $third = NULL, $submit = NULL) { $form['buttons'] = array( '#prefix' => '<div class="clearfix"><div class="form-buttons">', '#suffix' => '</div></div>', ); if (empty($name)) { $name = t('Apply'); if (!empty($this->stack) && count($this->stack) > 1) { $name = t('Apply and continue'); } $names = array(t('Apply'), t('Apply and continue')); } // Forms that are purely informational set an ok_button flag, so we know not // to create an "Apply" button for them. if (empty($form_state['ok_button'])) { $form['buttons']['submit'] = array( '#type' => 'submit', '#value' => $name, // The regular submit handler ($form_id . '_submit') does not apply if // we're updating the default display. It does apply if we're updating // the current display. Since we have no way of knowing at this point // which display the user wants to update, views_ui_standard_submit will // take care of running the regular submit handler as appropriate. '#submit' => array(array($this, 'standardSubmit')), '#button_type' => 'primary', ); // Form API button click detection requires the button's #value to be the // same between the form build of the initial page request, and the initial // form build of the request processing the form submission. Ideally, the // button's #value shouldn't change until the form rebuild step. However, // views_ui_ajax_form() implements a different multistep form workflow than // the Form API does, and adjusts $view->stack prior to form processing, so // we compensate by extending button click detection code to support any of // the possible button labels. if (isset($names)) { $form['buttons']['submit']['#values'] = $names; $form['buttons']['submit']['#process'] = array_merge(array('views_ui_form_button_was_clicked'), element_info_property($form['buttons']['submit']['#type'], '#process', array())); } // If a validation handler exists for the form, assign it to this button. if (function_exists($form_id . '_validate')) { $form['buttons']['submit']['#validate'][] = $form_id . '_validate'; } } // Create a "Cancel" button. For purely informational forms, label it "OK". $cancel_submit = function_exists($form_id . '_cancel') ? $form_id . '_cancel' : array($this, 'standardCancel'); $form['buttons']['cancel'] = array( '#type' => 'submit', '#value' => empty($form_state['ok_button']) ? t('Cancel') : t('Ok'), '#submit' => array($cancel_submit), '#validate' => array(), ); // Some forms specify a third button, with a name and submit handler. if ($third) { if (empty($submit)) { $submit = 'third'; } $third_submit = function_exists($form_id . '_' . $submit) ? $form_id . '_' . $submit : array($this, 'standardCancel'); $form['buttons'][$submit] = array( '#type' => 'submit', '#value' => $third, '#validate' => array(), '#submit' => array($third_submit), ); } // Compatibility, to be removed later: // TODO: When is "later"? // We used to set these items on the form, but now we want them on the $form_state: if (isset($form['#title'])) { $form_state['title'] = $form['#title']; } if (isset($form['#url'])) { $form_state['url'] = $form['#url']; } if (isset($form['#section'])) { $form_state['#section'] = $form['#section']; } // Finally, we never want these cached -- our object cache does that for us. $form['#no_cache'] = TRUE; // If this isn't an ajaxy form, then we want to set the title. if (!empty($form['#title'])) { drupal_set_title($form['#title']); } } /** * Return the was_defaulted, is_defaulted and revert state of a form. */ public function getOverrideValues($form, $form_state) { // Make sure the dropdown exists in the first place. if (isset($form_state['values']['override']['dropdown'])) { // #default_value is used to determine whether it was the default value or not. // So the available options are: $display, 'default' and 'default_revert', not 'defaults'. $was_defaulted = ($form['override']['dropdown']['#default_value'] === 'defaults'); $is_defaulted = ($form_state['values']['override']['dropdown'] === 'default'); $revert = ($form_state['values']['override']['dropdown'] === 'default_revert'); if ($was_defaulted !== $is_defaulted && isset($form['#section'])) { // We're changing which display these values apply to. // Update the #section so it knows what to mark changed. $form['#section'] = str_replace('default-', $form_state['display_id'] . '-', $form['#section']); } } else { // The user didn't get the dropdown for overriding the default display. $was_defaulted = FALSE; $is_defaulted = FALSE; $revert = FALSE; } return array($was_defaulted, $is_defaulted, $revert); } /** * Submit handler to break_lock a view. */ public function submitBreakLock(&$form, &$form_state) { drupal_container()->get('user.tempstore')->get('views')->delete($this->id()); $form_state['redirect'] = 'admin/structure/views/view/' . $this->id() . '/edit'; drupal_set_message(t('The lock has been broken and you may now edit this view.')); } /** * Form constructor callback to reorder displays on a view */ public function buildDisplaysReorderForm($form, &$form_state) { $display_id = $form_state['display_id']; $form['view'] = array('#type' => 'value', '#value' => $this); $form['#tree'] = TRUE; $count = count($this->get('display')); $displays = $this->get('display'); uasort($displays, array('static', 'sortPosition')); $this->set('display', $displays); foreach ($displays as $display) { $form[$display['id']] = array( 'title' => array('#markup' => $display['display_title']), 'weight' => array( '#type' => 'weight', '#value' => $display['position'], '#delta' => $count, '#title' => t('Weight for @display', array('@display' => $display['display_title'])), '#title_display' => 'invisible', ), '#tree' => TRUE, '#display' => $display, 'removed' => array( '#type' => 'checkbox', '#id' => 'display-removed-' . $display['id'], '#attributes' => array('class' => array('views-remove-checkbox')), '#default_value' => isset($display['deleted']), ), ); if (isset($display['deleted']) && $display['deleted']) { $form[$display['id']]['deleted'] = array('#type' => 'value', '#value' => TRUE); } if ($display['id'] === 'default') { unset($form[$display['id']]['weight']); unset($form[$display['id']]['removed']); } } $form['#title'] = t('Displays Reorder'); $form['#section'] = 'reorder'; // Add javascript settings that will be added via $.extend for tabledragging $form['#js']['tableDrag']['reorder-displays']['weight'][0] = array( 'target' => 'weight', 'source' => NULL, 'relationship' => 'sibling', 'action' => 'order', 'hidden' => TRUE, 'limit' => 0, ); $form['#action'] = url('admin/structure/views/nojs/reorder-displays/' . $this->id() . '/' . $display_id); $this->getStandardButtons($form, $form_state, 'views_ui_reorder_displays_form'); $form['buttons']['submit']['#submit'] = array(array($this, 'submitDisplaysReorderForm')); return $form; } /** * Submit handler for rearranging display form */ public function submitDisplaysReorderForm($form, &$form_state) { foreach ($form_state['input'] as $display => $info) { // add each value that is a field with a weight to our list, but only if // it has had its 'removed' checkbox checked. if (is_array($info) && isset($info['weight']) && empty($info['removed'])) { $order[$display] = $info['weight']; } } // Sort the order array asort($order); // Fixing up positions $position = 1; foreach (array_keys($order) as $display) { $order[$display] = $position++; } // Setting up position and removing deleted displays $displays = $this->get('display'); foreach ($displays as $display_id => $display) { // Don't touch the default !!! if ($display_id === 'default') { $displays[$display_id]['position'] = 0; continue; } if (isset($order[$display_id])) { $displays[$display_id]['position'] = $order[$display_id]; } else { $displays[$display_id]['deleted'] = TRUE; } } // Sorting back the display array as the position is not enough uasort($displays, array('static', 'sortPosition')); $this->set('display', $displays); // Store in cache views_ui_cache_set($this); $form_state['redirect'] = array('admin/structure/views/view/' . $this->id() . '/edit', array('fragment' => 'views-tab-default')); } /** * Add another form to the stack; clicking 'apply' will go to this form * rather than closing the ajax popup. */ public function addFormToStack($key, $display_id, $args, $top = FALSE, $rebuild_keys = FALSE) { // Reset the cache of IDs. Drupal rather aggressively prevents ID // duplication but this causes it to remember IDs that are no longer even // being used. $seen_ids_init = &drupal_static('drupal_html_id:init'); $seen_ids_init = array(); if (empty($this->stack)) { $this->stack = array(); } $stack = array($this->buildIdentifier($key, $display_id, $args), $key, $display_id, $args); // If we're being asked to add this form to the bottom of the stack, no // special logic is required. Our work is equally easy if we were asked to add // to the top of the stack, but there's nothing in it yet. if (!$top || empty($this->stack)) { $this->stack[] = $stack; } // If we're adding to the top of an existing stack, we have to maintain the // existing integer keys, so they can be used for the "2 of 3" progress // indicator (which will now read "2 of 4"). else { $keys = array_keys($this->stack); $first = current($keys); $last = end($keys); for ($i = $last; $i >= $first; $i--) { if (!isset($this->stack[$i])) { continue; } // Move form number $i to the next position in the stack. $this->stack[$i + 1] = $this->stack[$i]; unset($this->stack[$i]); } // Now that the previously $first slot is free, move the new form into it. $this->stack[$first] = $stack; ksort($this->stack); // Start the keys from 0 again, if requested. if ($rebuild_keys) { $this->stack = array_values($this->stack); } } } /** * Submit handler for adding new item(s) to a view. */ public function submitItemAdd($form, &$form_state) { $type = $form_state['type']; $types = ViewExecutable::viewsHandlerTypes(); $section = $types[$type]['plural']; // Handle the override select. list($was_defaulted, $is_defaulted) = $this->getOverrideValues($form, $form_state); if ($was_defaulted && !$is_defaulted) { // We were using the default display's values, but we're now overriding // the default display and saving values specific to this display. $display = &$this->executable->displayHandlers->get($form_state['display_id']); // setOverride toggles the override of this section. $display->setOverride($section); } elseif (!$was_defaulted && $is_defaulted) { // We used to have an override for this display, but the user now wants // to go back to the default display. // Overwrite the default display with the current form values, and make // the current display use the new default values. $display = &$this->executable->displayHandlers->get($form_state['display_id']); // optionsOverride toggles the override of this section. $display->setOverride($section); } if (!empty($form_state['values']['name']) && is_array($form_state['values']['name'])) { // Loop through each of the items that were checked and add them to the view. foreach (array_keys(array_filter($form_state['values']['name'])) as $field) { list($table, $field) = explode('.', $field, 2); if ($cut = strpos($field, '$')) { $field = substr($field, 0, $cut); } $id = $this->executable->addItem($form_state['display_id'], $type, $table, $field); // check to see if we have group by settings $key = $type; // Footer,header and empty text have a different internal handler type(area). if (isset($types[$type]['type'])) { $key = $types[$type]['type']; } $handler = views_get_handler($table, $field, $key); if ($this->executable->displayHandlers->get('default')->useGroupBy() && $handler->usesGroupBy()) { $this->addFormToStack('config-item-group', $form_state['display_id'], array($type, $id)); } // check to see if this type has settings, if so add the settings form first if ($handler && $handler->hasExtraOptions()) { $this->addFormToStack('config-item-extra', $form_state['display_id'], array($type, $id)); } // Then add the form to the stack $this->addFormToStack('config-item', $form_state['display_id'], array($type, $id)); } } if (isset($this->form_cache)) { unset($this->form_cache); } // Store in cache views_ui_cache_set($this); } public function renderPreview($display_id, $args = array()) { // Save the current path so it can be restored before returning from this function. $old_q = current_path(); // Determine where the query and performance statistics should be output. $config = config('views.settings'); $show_query = $config->get('ui.show.sql_query.enabled'); $show_info = $config->get('ui.show.preview_information'); $show_location = $config->get('ui.show.sql_query.where'); $show_stats = $config->get('ui.show.performance_statistics'); if ($show_stats) { $show_stats = $config->get('ui.show.sql_query.where'); } $combined = $show_query && $show_stats; $rows = array('query' => array(), 'statistics' => array()); $output = ''; $errors = $this->executable->validate(); if ($errors === TRUE) { $this->ajax = TRUE; $this->executable->live_preview = TRUE; $this->views_ui_context = TRUE; // AJAX happens via $_POST but everything expects exposed data to // be in GET. Copy stuff but remove ajax-framework specific keys. // If we're clicking on links in a preview, though, we could actually // still have some in $_GET, so we use $_REQUEST to ensure we get it all. $exposed_input = drupal_container()->get('request')->request->all(); foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', 'ajax_html_ids', 'ajax_page_state', 'form_id', 'form_build_id', 'form_token') as $key) { if (isset($exposed_input[$key])) { unset($exposed_input[$key]); } } $this->executable->setExposedInput($exposed_input); if (!$this->executable->setDisplay($display_id)) { return t('Invalid display id @display', array('@display' => $display_id)); } $this->executable->setArguments($args); // Store the current view URL for later use: if ($this->executable->display_handler->getOption('path')) { $path = $this->executable->getUrl(); } // Make view links come back to preview. $this->override_path = 'admin/structure/views/nojs/preview/' . $this->id() . '/' . $display_id; // Also override the current path so we get the pager. $original_path = current_path(); $q = _current_path($this->override_path); if ($args) { $q .= '/' . implode('/', $args); _current_path($q); } // Suppress contextual links of entities within the result set during a // Preview. // @todo We'll want to add contextual links specific to editing the View, so // the suppression may need to be moved deeper into the Preview pipeline. views_ui_contextual_links_suppress_push(); $preview = $this->executable->preview($display_id, $args); views_ui_contextual_links_suppress_pop(); // Reset variables. unset($this->override_path); _current_path($original_path); // Prepare the query information and statistics to show either above or // below the view preview. if ($show_info || $show_query || $show_stats) { // Get information from the preview for display. if (!empty($this->executable->build_info['query'])) { if ($show_query) { $query = $this->executable->build_info['query']; // Only the sql default class has a method getArguments. $quoted = array(); if ($this->executable->query instanceof Sql) { $quoted = $query->getArguments(); $connection = Database::getConnection(); foreach ($quoted as $key => $val) { if (is_array($val)) { $quoted[$key] = implode(', ', array_map(array($connection, 'quote'), $val)); } else { $quoted[$key] = $connection->quote($val); } } } $rows['query'][] = array('<strong>' . t('Query') . '</strong>', '<pre>' . check_plain(strtr($query, $quoted)) . '</pre>'); if (!empty($this->executable->additional_queries)) { $queries = '<strong>' . t('These queries were run during view rendering:') . '</strong>'; foreach ($this->executable->additional_queries as $query) { if ($queries) { $queries .= "\n"; } $queries .= t('[@time ms]', array('@time' => intval($query[1] * 100000) / 100)) . ' ' . $query[0]; } $rows['query'][] = array('<strong>' . t('Other queries') . '</strong>', '<pre>' . $queries . '</pre>'); } } if ($show_info) { $rows['query'][] = array('<strong>' . t('Title') . '</strong>', filter_xss_admin($this->executable->getTitle())); if (isset($path)) { $path = l($path, $path); } else { $path = t('This display has no path.'); } $rows['query'][] = array('<strong>' . t('Path') . '</strong>', $path); } if ($show_stats) { $rows['statistics'][] = array('<strong>' . t('Query build time') . '</strong>', t('@time ms', array('@time' => intval($this->executable->build_time * 100000) / 100))); $rows['statistics'][] = array('<strong>' . t('Query execute time') . '</strong>', t('@time ms', array('@time' => intval($this->executable->execute_time * 100000) / 100))); $rows['statistics'][] = array('<strong>' . t('View render time') . '</strong>', t('@time ms', array('@time' => intval($this->executable->render_time * 100000) / 100))); } drupal_alter('views_preview_info', $rows, $this); } else { // No query was run. Display that information in place of either the // query or the performance statistics, whichever comes first. if ($combined || ($show_location === 'above')) { $rows['query'] = array(array('<strong>' . t('Query') . '</strong>', t('No query was run'))); } else { $rows['statistics'] = array(array('<strong>' . t('Query') . '</strong>', t('No query was run'))); } } } } else { foreach ($errors as $error) { drupal_set_message($error, 'error'); } $preview = t('Unable to preview due to validation errors.'); } // Assemble the preview, the query info, and the query statistics in the // requested order. if ($show_location === 'above') { if ($combined) { $output .= '<div class="views-query-info">' . theme('table', array('rows' => array_merge($rows['query'], $rows['statistics']))) . '</div>'; } else { $output .= '<div class="views-query-info">' . theme('table', array('rows' => $rows['query'])) . '</div>'; } } elseif ($show_stats === 'above') { $output .= '<div class="views-query-info">' . theme('table', array('rows' => $rows['statistics'])) . '</div>'; } $output .= $preview; if ($show_location === 'below') { if ($combined) { $output .= '<div class="views-query-info">' . theme('table', array('rows' => array_merge($rows['query'], $rows['statistics']))) . '</div>'; } else { $output .= '<div class="views-query-info">' . theme('table', array('rows' => $rows['query'])) . '</div>'; } } elseif ($show_stats === 'below') { $output .= '<div class="views-query-info">' . theme('table', array('rows' => $rows['statistics'])) . '</div>'; } _current_path($old_q); return $output; } /** * Get the user's current progress through the form stack. * * @return * FALSE if the user is not currently in a multiple-form stack. Otherwise, * an associative array with the following keys: * - current: The number of the current form on the stack. * - total: The total number of forms originally on the stack. */ public function getFormProgress() { $progress = FALSE; if (!empty($this->stack)) { $stack = $this->stack; // The forms on the stack have integer keys that don't change as the forms // are completed, so we can see which ones are still left. $keys = array_keys($this->stack); // Add 1 to the array keys for the benefit of humans, who start counting // from 1 and not 0. $current = reset($keys) + 1; $total = end($keys) + 1; if ($total > 1) { $progress = array(); $progress['current'] = $current; $progress['total'] = $total; } } return $progress; } /** * Build a form identifier that we can use to see if one form * is the same as another. Since the arguments differ slightly * we do a lot of spiffy concatenation here. */ public function buildIdentifier($key, $display_id, $args) { $form = views_ui_ajax_forms($key); // Automatically remove the single-form cache if it exists and // does not match the key. $identifier = implode('-', array($key, $this->id(), $display_id)); foreach ($form['args'] as $id) { $arg = (!empty($args)) ? array_shift($args) : NULL; $identifier .= '-' . $arg; } return $identifier; } /** * Display position sorting function */ public static function sortPosition($display1, $display2) { if ($display1['position'] != $display2['position']) { return $display1['position'] < $display2['position'] ? -1 : 1; } return 0; } /** * Build up a $form_state object suitable for use with drupal_build_form * based on known information about a form. */ public function buildFormState($js, $key, $display_id, $args) { $form = views_ui_ajax_forms($key); // Build up form state $form_state = array( 'form_key' => $key, 'form_id' => $form['form_id'], 'view' => &$this, 'ajax' => $js, 'display_id' => $display_id, 'no_redirect' => TRUE, ); // If an method was specified, use that for the callback. if (isset($form['callback'])) { $form_state['build_info']['args'] = array(); $form_state['build_info']['callback'] = array($this, $form['callback']); } foreach ($form['args'] as $id) { $form_state[$id] = (!empty($args)) ? array_shift($args) : NULL; } return $form_state; } /** * Passes through all unknown calls onto the storage object. */ public function __call($method, $args) { return call_user_func_array(array($this->storage, $method), $args); } /** * Implements \IteratorAggregate::getIterator(). */ public function getIterator() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::id(). */ public function id() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::uuid(). */ public function uuid() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::isNew(). */ public function isNew() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::entityType(). */ public function entityType() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::bundle(). */ public function bundle() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::isDefaultRevision(). */ public function isDefaultRevision($new_value = NULL) { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::getRevisionId(). */ public function getRevisionId() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::entityInfo(). */ public function entityInfo() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::createDuplicate(). */ public function createDuplicate() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::delete(). */ public function delete() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::save(). */ public function save() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::uri(). */ public function uri() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::label(). */ public function label($langcode = NULL) { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::isNewRevision(). */ public function isNewRevision() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::setNewRevision(). */ public function setNewRevision($value = TRUE) { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::enforceIsNew(). */ public function enforceIsNew($value = TRUE) { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Entity\EntityInterface::getExportProperties(). */ public function getExportProperties() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\TranslatableInterface::getTranslation(). */ public function getTranslation($langcode, $strict = TRUE) { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\TranslatableInterface::getTranslationLanguages(). */ public function getTranslationLanguages($include_default = TRUE) { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\TranslatableInterface::language)(). */ public function language() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\AccessibleInterface::access(). */ public function access($operation = 'view', \Drupal\user\Plugin\Core\Entity\User $account = NULL) { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\ComplexDataInterface::isEmpty)(). */ public function isEmpty() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\ComplexDataInterface::getPropertyValues(). */ public function getPropertyValues() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\ComplexDataInterface::getPropertyDefinitions(). */ public function getPropertyDefinitions() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\ComplexDataInterface::getPropertyDefinition(). */ public function getPropertyDefinition($name) { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\ComplexDataInterface::setPropertyValues(). */ public function setPropertyValues($values) { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\ComplexDataInterface::getProperties(). */ public function getProperties($include_computed = FALSE) { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\views\ViewStorageInterface::enable(). */ public function enable() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\views\ViewStorageInterface::disable(). */ public function disable() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\views\ViewStorageInterface::isEnabled(). */ public function isEnabled() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Config\Entity\ConfigEntityInterface::getOriginalID(). */ public function getOriginalID() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\Config\Entity\ConfigEntityInterface::setOriginalID(). */ public function setOriginalID($id) { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements Drupal\Core\Entity\EntityInterface::getBCEntity(). */ public function getBCEntity() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements Drupal\Core\Entity\EntityInterface::getOriginalEntity(). */ public function getOriginalEntity() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\ContextAwareInterface::getName(). */ public function getName() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\ContextAwareInterface::getRoot(). */ public function getRoot() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\ContextAwareInterface::getPropertyPath(). */ public function getPropertyPath() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\ContextAwareInterface::getParent(). */ public function getParent() { return $this->__call(__FUNCTION__, func_get_args()); } /** * Implements \Drupal\Core\TypedData\ContextAwareInterface::setContext(). */ public function setContext($name = NULL, ContextAwareInterface $parent = NULL) { return $this->__call(__FUNCTION__, func_get_args()); } }
adirkuhn/expressoDrupal
core/modules/views/views_ui/lib/Drupal/views_ui/ViewUI.php
PHP
gpl-2.0
38,054
<?php /** * @version 2.3, Creation Date : March-24-2011 * @name impressionclicks.php * @location /components/com_contushdvideosahre/views/impressionclicks/tmpl/impressionclicks.php * @package Joomla 1.6 * @subpackage contushdvideoshare * @author Contus Support - http://www.contussupport.com * @copyright Copyright (C) 2011 Contus Support * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html * @link http://www.hdvideoshare.net */ /* * Description : front page video search page layout */ ?>
dherrerav/Azteca-Sonora
components/com_contushdvideoshare/views/impressionclicks/tmpl/impressionclicks.php
PHP
gpl-2.0
553
<?php /** * TOP API: taobao.shop.remainshowcase.get request * * @author auto create * @since 1.0, 2012-03-21 12:35:10 */ class ShopRemainshowcaseGetRequest { private $apiParas = array(); public function getApiMethodName() { return "taobao.shop.remainshowcase.get"; } public function getApiParas() { return $this->apiParas; } public function check() { } }
gxk9933/guoxk-blog
html/test_taobaoke/sdk/top/request/ShopRemainshowcaseGetRequest.php
PHP
gpl-2.0
386
/* * Timeval.cc -- time arithmetic * * (c) 2003 Dr. Andreas Mueller, Beratung und Entwicklung * * $Id: Timeval.cc,v 1.7 2009/01/10 19:00:25 afm Exp $ */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /* HAVE_CONFIG_H */ #include <Timeval.h> #ifdef HAVE_MATH_H #include <math.h> #endif /* HAVE_MATH_H */ #ifdef HAVE_UNISTD_H #include <unistd.h> #endif /* HAVE_UNISTD_H */ #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif /* HAVE_SYS_TYPES_H */ #include <mdebug.h> namespace meteo { Timeval::Timeval(void) { t.tv_sec = t.tv_usec = 0; } Timeval::Timeval(struct timeval tv) { t.tv_sec = tv.tv_sec; t.tv_usec = tv.tv_usec; } Timeval::Timeval(double r) { t.tv_sec = (int)r; t.tv_usec = (int)(1000000. * (r - t.tv_sec)); } Timeval::Timeval(int l) { t.tv_sec = l; t.tv_usec = 0; } void Timeval::now(void) { gettimeofday(&t, NULL); } time_t Timeval::getTimekey(void) const { time_t result = t.tv_sec; result -= (result % 60); return result; } void Timeval::wait(void) { struct timeval local; local = t; if (0 != select(0, NULL, NULL, NULL, &local)) { mdebug(LOG_DEBUG, MDEBUG_LOG, MDEBUG_ERRNO, "select problem in drain"); } } double Timeval::getValue(void) const { return t.tv_sec + t.tv_usec/1000000.; } Timeval& Timeval::operator+=(double b) { t.tv_sec += (int)b; t.tv_usec += (int)(1000000 * (b - (int)b)); if (t.tv_usec >= 1000000) { t.tv_usec -= 1000000; t.tv_sec++; } return *this; } Timeval& Timeval::operator+=(int b) { t.tv_sec += b; return *this; } Timeval operator+(const Timeval& a, const Timeval& b) { struct timeval tv; tv.tv_sec = a.t.tv_sec + b.t.tv_sec; tv.tv_usec = a.t.tv_usec + b.t.tv_usec; if (tv.tv_usec >= 1000000) { tv.tv_sec++; tv.tv_usec -= 1000000; } return Timeval(tv); } Timeval operator+(const Timeval& a, const double b) { return Timeval(a.getValue() + b); } Timeval operator+(const Timeval& a, const int b) { struct timeval tv; tv.tv_sec = a.t.tv_sec + b; tv.tv_usec = a.t.tv_usec; return Timeval(tv); } Timeval operator-(const Timeval& a, const Timeval& b) { return Timeval(a.getValue() - b.getValue()); } } /* namespace meteo */
martinluther/meteo
lib/Timeval.cc
C++
gpl-2.0
2,129
using Rocket.API; using Rocket.API.Extensions; using Rocket.Core.Logging; using Rocket.Unturned.Chat; using Rocket.Unturned.Commands; using Rocket.Unturned.Player; using System; using System.Collections.Generic; using UnityEngine; namespace coolpuppy24.rpevents { public class ArrestFinishCommand : IRocketCommand { public static Main Instance; public List<string> Aliases { get { return new List<string>() { }; } } public AllowedCaller AllowedCaller { get { return AllowedCaller.Player; } } public string Help { get { return "Finishes arrest on a player"; } } public string Name { get { return "arrestfinish"; } } public List<string> Permissions { get { return new List<string>() { "rpevents.arrest" }; } } public string Syntax { get { return "<playername>"; } } public void Execute(IRocketPlayer caller, string[] command) { UnturnedPlayer player = command.GetUnturnedPlayerParameter(0); if (player == null) UnturnedChat.Say(caller, Main.Instance.Translate("player_not_found")); if (caller is ConsolePlayer) { Rocket.Core.Logging.Logger.Log("This command cannot be called from the console!"); return; } else { UnturnedChat.Say("[RPEvents]: " + Main.Instance.Translate("command_arrestfinish", caller.DisplayName), UnturnedChat.GetColorFromName(Main.Instance.Configuration.Instance.FinishColor, Color.red)); return; } } } }
Coolpuppy24/RPEvents
Commands/ArrestFinishCommand.cs
C#
gpl-2.0
1,996
package com.omnicrola.panoptes.ui.autocomplete; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.Test; import com.omnicrola.panoptes.control.DataController; import com.omnicrola.panoptes.control.IControlObserver; import com.omnicrola.panoptes.control.TimeblockSet; import com.omnicrola.panoptes.data.IReadTimeblock; import com.omnicrola.panoptes.data.TimeData; import com.omnicrola.testing.util.EnhancedTestCase; public class CardNumberProviderTest extends EnhancedTestCase { private DataController mockController; private String expectedNumber1; private String expectedNumber2; private String expectedNumber3; @Test public void testImplementsInterfaces() throws Exception { assertImplementsInterface(IOptionProvider.class, CardNumberProvider.class); assertImplementsInterface(IControlObserver.class, CardNumberProvider.class); } @Test public void testConstructorParams() throws Exception { DataController mockController = useMock(DataController.class); startReplay(); CardNumberProvider cardNumberProvider = new CardNumberProvider(mockController); assertConstructionParamSame("dataController", mockController, cardNumberProvider); } @Test public void testDataChanged_UpdatesOptionList() throws Exception { setupMockTimeblockSet(); startReplay(); CardNumberProvider cardNumberProvider = new CardNumberProvider(this.mockController); assertEquals(0, cardNumberProvider.getOptionsList().size()); cardNumberProvider.dataChanged(); List<Object> optionsList = cardNumberProvider.getOptionsList(); assertEquals(3, optionsList.size()); assertTrue(optionsList.contains(this.expectedNumber1)); assertTrue(optionsList.contains(this.expectedNumber2)); assertTrue(optionsList.contains(this.expectedNumber3)); } @Test public void testTimeblockSetChanged_UpdatesOptionList() throws Exception { TimeblockSet mockTimeblockSet = useMock(TimeblockSet.class); setupMockTimeblockSet(); startReplay(); CardNumberProvider cardNumberProvider = new CardNumberProvider(this.mockController); assertEquals(0, cardNumberProvider.getOptionsList().size()); cardNumberProvider.timeblockSetChanged(mockTimeblockSet); List<Object> optionsList = cardNumberProvider.getOptionsList(); assertEquals(3, optionsList.size()); assertTrue(optionsList.contains(this.expectedNumber1)); assertTrue(optionsList.contains(this.expectedNumber2)); assertTrue(optionsList.contains(this.expectedNumber3)); } public void setupMockTimeblockSet() { TimeblockSet mockTimeblockSet = useMock(TimeblockSet.class); this.expectedNumber1 = "cardnumber"; this.expectedNumber2 = "a different number"; this.expectedNumber3 = "duplicate"; IReadTimeblock mockTimeblock1 = createMockBlockWithCardNumber(this.expectedNumber1); IReadTimeblock mockTimeblock2 = createMockBlockWithCardNumber(this.expectedNumber2); IReadTimeblock mockTimeblock3 = createMockBlockWithCardNumber(this.expectedNumber3); IReadTimeblock mockTimeblock4 = createMockBlockWithCardNumber(this.expectedNumber3); List<IReadTimeblock> timblocks = Arrays.asList(mockTimeblock1, mockTimeblock2, mockTimeblock3, mockTimeblock4); expect(mockTimeblockSet.getBlockSet()).andReturn(timblocks); this.mockController = useMock(DataController.class); expect(this.mockController.getAllTimeblocks()).andReturn(mockTimeblockSet); } private IReadTimeblock createMockBlockWithCardNumber(String expectedNumber) { IReadTimeblock mockTimeblock = useMock(IReadTimeblock.class); TimeData mockData = useMock(TimeData.class); expect(mockTimeblock.getTimeData()).andReturn(mockData); expect(mockData.getCard()).andReturn(expectedNumber); return mockTimeblock; } }
Omnicrola/Panoptes
Panoptes.Test/src/com/omnicrola/panoptes/ui/autocomplete/CardNumberProviderTest.java
Java
gpl-2.0
3,813
<?php namespace ApacheSolrForTypo3\Solr\IndexQueue; /*************************************************************** * Copyright notice * * (c) 2010-2015 Ingo Renner <ingo@typo3.org> * All rights reserved * * This script is part of the TYPO3 project. The TYPO3 project 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. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * A copy is found in the textfile GPL.txt and important notices to the license * from the author is found in LICENSE.txt distributed with these scripts. * * * This script 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 copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ /** * IndexQueuePageIndexerDocumentsModifier interface, allows to modify documents * before adding them to the Solr index in the index queue page indexer. * * @author Ingo Renner <ingo@typo3.org> */ interface PageIndexerDocumentsModifier { /** * Modifies the given documents * * @param Item $item The currently being indexed item. * @param int $language The language uid of the documents * @param array $documents An array of documents to be indexed * @return array An array of modified documents */ public function modifyDocuments(Item $item, $language, array $documents); }
arnoschoon/ext-solr
Classes/IndexQueue/PageIndexerDocumentsModifier.php
PHP
gpl-2.0
1,793
<?php $xml = simplexml_load_file("http://animacionugm.blogspot.com/feeds/posts/default"); $json = json_encode($xml); echo "<pre>"; echo $json; echo "</pre>"; ?>
acalvoa/EOLLICE
xml.php
PHP
gpl-2.0
165
<?php /** * @package syscart * libraries/platform/language.php * * @autor majeed mohammadian */ defined('syscart') or die('access denied...!'); class platformLanguage { private $language = 'persian'; private $code = 'fa-IR'; private $direction = 'rtl'; private $id = null; public function set($language = 'persian', $code = 'fa-IR', $direction = 'rtl') { $this->language = $language; $this->code = $code; $this->direction = $direction; } public function getLanguage() { return $this->language; } public function getCode() { return $this->code; } public function getID() { if(!isset( $this->id )) { global $sysDbo; $sql = "SELECT id FROM #__language WHERE code = :code"; $sql = platformQuery::refactor($sql); $query = $sysDbo->prepare($sql); $query->bindParam(':code', $this->code, PDO::PARAM_INT); $query->execute(); $result = $query->fetch(\PDO::FETCH_ASSOC); $this->id = $result['id']; } return $this->id; } public function getDirection() { return $this->direction; } public function generate($data = '') { global $sysDbo, $sysLang; $regex = "/\\{\\{t:(\\S+)\\}\\}/"; preg_match_all($regex, $data, $matches); $languageGroups = []; foreach( $matches[1] as $textLang ) { $partLang = explode('.', $textLang); if( !in_array($partLang[0], $languageGroups, true) ) { array_push($languageGroups, "'".$partLang[0]."'"); } } if($languageGroups) { $sql = "SELECT groups, meta, value FROM #__language_code WHERE languageId = :langID AND groups IN (".implode(',', $languageGroups).") AND state = '1'"; $sql = platformQuery::refactor($sql); $query = $sysDbo->prepare($sql); $query->bindValue(':langID', $sysLang->getID(), PDO::PARAM_INT); $query->execute(); $result = $query->fetchAll(\PDO::FETCH_ASSOC); $langKey = $langValue = []; foreach( $result as $langData ) { $langKey[] = '{{t:'.$langData[ 'groups' ].'.'.$langData[ 'meta' ].'}}'; $langValue[] = $langData[ 'value' ]; } return str_replace($langKey, $langValue, $data); } else { return $data; } } }
syscart/syscart
libraries/platform/language.php
PHP
gpl-2.0
2,177
<?php /** * TOP API: taobao.wlb.inventory.detail.get request * * @author auto create * @since 1.0, 2012-11-01 12:40:06 */ class WlbInventoryDetailGetRequest { /** * 库存类型列表,值包括: VENDIBLE--可销售库存 FREEZE--冻结库存 ONWAY--在途库存 DEFECT--残次品库存 ENGINE_DAMAGE--机损 BOX_DAMAGE--箱损 EXPIRATION--过保 **/ private $inventoryTypeList; /** * 商品ID **/ private $itemId; /** * 仓库编码 **/ private $storeCode; private $apiParas = array(); public function setInventoryTypeList($inventoryTypeList) { $this->inventoryTypeList = $inventoryTypeList; $this->apiParas["inventory_type_list"] = $inventoryTypeList; } public function getInventoryTypeList() { return $this->inventoryTypeList; } public function setItemId($itemId) { $this->itemId = $itemId; $this->apiParas["item_id"] = $itemId; } public function getItemId() { return $this->itemId; } public function setStoreCode($storeCode) { $this->storeCode = $storeCode; $this->apiParas["store_code"] = $storeCode; } public function getStoreCode() { return $this->storeCode; } public function getApiMethodName() { return "taobao.wlb.inventory.detail.get"; } public function getApiParas() { return $this->apiParas; } public function check() { RequestCheckUtil::checkMaxListSize($this->inventoryTypeList,20,"inventoryTypeList"); RequestCheckUtil::checkNotNull($this->itemId,"itemId"); } public function putOtherTextParam($key, $value) { $this->apiParas[$key] = $value; $this->$key = $value; } }
Jeepal/iLogin
API/taobao/top/request/WlbInventoryDetailGetRequest.php
PHP
gpl-2.0
1,597
<?php if(!class_exists('WP_List_Table')){ require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); } class EasySocialMetricsLiteResultTable extends WP_List_Table { public $total_results = array(); public $top_content = array(); /** ************************************************************************ * REQUIRED. Set up a constructor that references the parent constructor. We * use the parent reference to set some default configs. ***************************************************************************/ function __construct(){ global $status, $page; //Set parent defaults parent::__construct( array( 'singular' => 'post', //singular name of the listed records 'plural' => 'posts', //plural name of the listed records 'ajax' => false //does this table support ajax? ) ); $this->services = array( 'facebook' => 'Facebook', 'twitter' => 'Twitter', 'googleplus' => 'Google Plus', 'linkedin' => 'LinkedIn', 'pinterest' => 'Pinterest', 'diggs' => 'Digg.com', 'delicious' => 'Delicious', 'facebook_comments' => 'Facebook Comments', 'stumbleupon'=> 'Stumble Upon' ); } /** ************************************************************************ * Recommended. This method is called when the parent class can't find a method * specifically build for a given column. Generally, it's recommended to include * one method for each column you want to render, keeping your package class * neat and organized. For example, if the class needs to process a column * named 'title', it would first see if a method named $this->column_title() * exists - if it does, that method will be used. If it doesn't, this one will * be used. Generally, you should try to use custom column methods as much as * possible. * * Since we have defined a column_title() method later on, this method doesn't * need to concern itself with any column with a name of 'title'. Instead, it * needs to handle everything else. * * For more detailed insight into how columns are handled, take a look at * WP_List_Table::single_row_columns() * * @param array $item A singular item (one full row's worth of data) * @param array $column_name The name/slug of the column to be processed * @return string Text or HTML to be placed inside the column <td> **************************************************************************/ function column_default($item, $column_name){ switch($column_name){ case 'total': return number_format(intval($item['esml_socialcount_total'])); case 'comment_count': return number_format(intval($item[$column_name])); case 'facebook': case 'twitter': case 'googleplus': case 'pinterest': case 'linkedin': case 'stumbleupon': case 'facebook_comments': return number_format(intval($item['esml_socialcount_'.$column_name])); default: return print_r($item,true); //Show the whole array for troubleshooting purposes } } /** ************************************************************************ * Recommended. This is a custom column method and is responsible for what * is rendered in any column with a name/slug of 'title'. Every time the class * needs to render a column, it first looks for a method named * column_{$column_title} - if it exists, that method is run. If it doesn't * exist, column_default() is called instead. * * This example also illustrates how to implement rollover actions. Actions * should be an associative array formatted as 'slug'=>'link html' - and you * will need to generate the URLs yourself. You could even ensure the links * * * @see WP_List_Table::::single_row_columns() * @param array $item A singular item (one full row's worth of data) * @return string Text to be placed inside the column <td> (movie title only) **************************************************************************/ function column_post_title($item){ //Build row actions $actions = array( 'edit' => sprintf('<a href="post.php?post=%s&action=edit">Edit Post</a>',$item['ID'],'edit',$item['ID']), 'update' => '<a href="'.add_query_arg( 'esml_sync_now', $item['ID']).'">Update Stats</a>', 'info' => sprintf('Updated %s',EasySocialMetricsLite::timeago($item['esml_socialcount_LAST_UPDATED'])) ); //Return the title contents return sprintf('%1$s <span style="color:silver">(id:%2$s)</span>%3$s', /*$1%s*/ $item['post_title'], /*$2%s*/ $item['ID'], /*$3%s*/ $this->row_actions($actions) ); } /** ************************************************************************ * REQUIRED! This method dictates the table's columns and titles. This should * return an array where the key is the column slug (and class) and the value * is the column's title text. If you need a checkbox for bulk actions, refer * to the $columns array below. * * The 'cb' column is treated differently than the rest. If including a checkbox * column in your table you must create a column_cb() method. If you don't need * bulk actions or checkboxes, simply leave the 'cb' entry out of your array. * * @see WP_List_Table::::single_row_columns() * @return array An associative array containing column information: 'slugs'=>'Visible Titles' **************************************************************************/ function get_columns(){ $columns = array( 'post_title' => 'Title', 'total' => 'Total', 'facebook' => 'Facebook', 'twitter' => 'Twitter', 'googleplus' => 'Google+', 'linkedin' => 'LinkedIn', 'pinterest' => 'Pinterest', 'stumbleupon' => 'StumbleUpon', 'comment_count' => 'Post Comments', 'facebook_comments' => 'Facebook Comments' ); return $columns; } /** ************************************************************************ * Optional. If you want one or more columns to be sortable (ASC/DESC toggle), * you will need to register it here. This should return an array where the * key is the column that needs to be sortable, and the value is db column to * sort by. Often, the key and value will be the same, but this is not always * the case (as the value is a column name from the database, not the list table). * * This method merely defines which columns should be sortable and makes them * clickable - it does not handle the actual sorting. You still need to detect * the ORDERBY and ORDER querystring variables within prepare_items() and sort * your data accordingly (usually by modifying your query). * * @return array An associative array containing all the columns that should be sortable: 'slugs'=>array('data_values',bool) **************************************************************************/ function get_sortable_columns() { $sortable_columns = array( 'post_title' => array('post_title',false), //true means it's already sorted 'total' => array('total',false), 'facebook' => array('facebook',false), 'twitter' => array('twitter',false), 'googleplus' => array('googleplus',false), 'linkedin' => array('linkedin',false), 'pinterest' => array('pinterest',false), 'stumbleupon' => array('stumbleupon',false), 'comment_count' => array('comment_count',false), 'facebook_comments' => array('facebook_comments',false) ); return $sortable_columns; } /** ************************************************************************ * Optional. If you need to include bulk actions in your list table, this is * the place to define them. Bulk actions are an associative array in the format * 'slug'=>'Visible Title' * * If this method returns an empty value, no bulk action will be rendered. If * you specify any bulk actions, the bulk actions box will be rendered with * the table automatically on display(). * * Also note that list tables are not automatically wrapped in <form> elements, * so you will need to create those manually in order for bulk actions to function. * * @return array An associative array containing all the bulk actions: 'slugs'=>'Visible Titles' **************************************************************************/ function get_bulk_actions() { $actions = array( //'delete' => 'Delete' ); return $actions; } /** ************************************************************************ * Optional. You can handle your bulk actions anywhere or anyhow you prefer. * For this example package, we will handle it in the class to keep things * clean and organized. * * @see $this->prepare_items() **************************************************************************/ function process_bulk_action() { //Detect when a bulk action is being triggered... if( 'delete'===$this->current_action() ) { wp_die('Items deleted (or they would be if we had items to delete)!'); } } /** ************************************************************************ * REQUIRED! This is where you prepare your data for display. This method will * usually be used to query the database, sort and filter the data, and generally * get it ready to be displayed. At a minimum, we should set $this->items and * $this->set_pagination_args(), although the following properties and methods * are frequently interacted with here... * * @global WPDB $wpdb * @uses $this->_column_headers * @uses $this->items * @uses $this->get_columns() * @uses $this->get_sortable_columns() * @uses $this->get_pagenum() * @uses $this->set_pagination_args() **************************************************************************/ function prepare_items() { global $wpdb; //This is used only if making any database queries /** * First, lets decide how many records per page to show */ $per_page = 20; /** * REQUIRED. Now we need to define our column headers. This includes a complete * array of columns to be displayed (slugs & titles), a list of columns * to keep hidden, and a list of columns that are sortable. Each of these * can be defined in another method (as we've done here) before being * used to build the value for our _column_headers property. */ $columns = $this->get_columns(); $hidden = array(); $sortable = $this->get_sortable_columns(); /** * REQUIRED. Finally, we build an array to be used by the class for column * headers. The $this->_column_headers property takes an array which contains * 3 other arrays. One for all columns, one for hidden columns, and one * for sortable columns. */ $this->_column_headers = array($columns, $hidden, $sortable); /** * Optional. You can handle your bulk actions however you see fit. In this * case, we'll handle them within our package just to keep things clean. */ $this->process_bulk_action(); /** * Instead of querying a database, we're going to fetch the example data * property we created for use in this plugin. This makes this example * package slightly different than one you might build on your own. In * this example, we'll be using array manipulation to sort and paginate * our data. In a real-world implementation, you will probably want to * use sort and pagination data to build a custom query instead, as you'll * be able to use your precisely-queried data immediately. */ $data = $this->generate_data(); //print_r($data); /** * This checks for sorting input and sorts the data in our array accordingly. * * In a real-world situation involving a database, you would probably want * to handle sorting by passing the 'orderby' and 'order' values directly * to a custom query. The returned data will be pre-sorted, and this array * sorting technique would be unnecessary. */ function usort_reorder($a,$b){ $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'total'; //If no sort, default to title $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'desc'; //If no order, default to asc if ($orderby == 'total') { $orderby = 'esml_socialcount_total'; } switch ($orderby) { case 'facebook': case 'twitter': case 'googleplus': case 'pinterest': case 'linkedin': case 'stumbleupon': case 'facebook_comments': $orderby = 'esml_socialcount_'.$orderby; } if ($orderby == "post_title") { $result = strcmp($a[$orderby], $b[$orderby]); } //Determine sort order else { if (intval($a[$orderby]) < intval($b[$orderby])) { $result = -1; } else if (intval($a[$orderby]) > intval($b[$orderby])) { $result = 1; } else { $result = 0; } } return ($order==='asc') ? $result : -$result; //Send final sort direction to usort } usort($data, 'usort_reorder'); /*********************************************************************** * --------------------------------------------------------------------- * vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv * * In a real-world situation, this is where you would place your query. * * For information on making queries in WordPress, see this Codex entry: * http://codex.wordpress.org/Class_Reference/wpdb * * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * --------------------------------------------------------------------- **********************************************************************/ /** * REQUIRED for pagination. Let's figure out what page the user is currently * looking at. We'll need this later, so you should always include it in * your own package classes. */ $current_page = $this->get_pagenum(); /** * REQUIRED for pagination. Let's check how many items are in our data array. * In real-world use, this would be the total number of items in your database, * without filtering. We'll need this later, so you should always include it * in your own package classes. */ $total_items = count($data); /** * The WP_List_Table class does not handle pagination for us, so we need * to ensure that the data is trimmed to only the current page. We can use * array_slice() to */ $data = array_slice($data,(($current_page-1)*$per_page),$per_page); /** * REQUIRED. Now we can add our *sorted* data to the items property, where * it can be used by the rest of the class. */ $this->items = $data; /** * REQUIRED. We also have to register our pagination options & calculations. */ $this->set_pagination_args( array( 'total_items' => $total_items, //WE have to calculate the total number of items 'per_page' => $per_page, //WE have to determine how many items to show on a page 'total_pages' => ceil($total_items/$per_page) //WE have to calculate the total number of pages ) ); } function generate_data() { global $wpdb; //This is used only if making any database queries $per_page = 10; $this->process_bulk_action(); // Get custom post types to display in our report. $post_types = $this->get_post_types(); //print "post types = "; $limit = 30; add_filter( 'posts_where', array($this, 'date_range_filter') ); $querydata = new WP_Query(array( 'posts_per_page'=> -1, 'post_status' => 'publish', 'post_type' => $post_types )); remove_filter( 'posts_where', array($this, 'date_range_filter') ); $data=array(); // foreach ($querydata as $querydatum ) { if ( $querydata->have_posts() ) : while ( $querydata->have_posts() ) : $querydata->the_post(); global $post; $item['ID'] = $post->ID; $item['post_title'] = $post->post_title; $item['post_date'] = $post->post_date; $item['comment_count'] = $post->comment_count; $item['esml_socialcount_total'] = (get_post_meta($post->ID, "esml_socialcount_TOTAL", true)) ? get_post_meta($post->ID, "esml_socialcount_TOTAL", true) : 0; $item['esml_socialcount_LAST_UPDATED'] = get_post_meta($post->ID, "esml_socialcount_LAST_UPDATED", true); $item['permalink'] = get_permalink($post->ID); if (!isset($this->total_results['esml_socialcount_total'])) { $this->total_results['esml_socialcount_total'] = 0; } $this->total_results['esml_socialcount_total'] = $this->total_results['esml_socialcount_total'] + $item['esml_socialcount_total']; foreach ($this->services as $slug => $name) { $item['esml_socialcount_'.$slug] = get_post_meta($post->ID, "esml_socialcount_$slug", true); if (!isset($this->total_results['esml_socialcount_'.$slug])) { $this->total_results['esml_socialcount_'.$slug] = 0; } $this->total_results['esml_socialcount_'.$slug] = $this->total_results['esml_socialcount_'.$slug] + $item['esml_socialcount_'.$slug]; if (!isset($this->top_content['esml_socialcount_'.$slug ])) { $blank = array("title" => "", "permalink" => "", "value" => "0"); $this->top_content['esml_socialcount_'.$slug ] = $blank; } if ($item['esml_socialcount_'.$slug] > $this->top_content['esml_socialcount_'.$slug ]["value"]) { $this->top_content['esml_socialcount_'.$slug ]["value"] = $item['esml_socialcount_'.$slug]; $this->top_content['esml_socialcount_'.$slug ]["title"] = $item['post_title'] = $post->post_title; $this->top_content['esml_socialcount_'.$slug ]["permalink"] = $item['permalink']; } } array_push($data, $item); endwhile; endif; return $data; } public function get_post_types() { $types_to_track = array(); $pts = get_post_types ( array ('public' => true, 'show_ui' => true, '_builtin' => true ) ); $cpts = get_post_types ( array ('public' => true, 'show_ui' => true, '_builtin' => false ) ); $options = $this->options; if (is_array($options)) { if (!isset($options['esml_monitor_types'])) { $options['esml_monitor_types'] = array(); } } if (is_array ( $options ) && isset ( $options ['esml_monitor_types'] ) && is_array ( $options ['esml_monitor_types'] )) { global $wp_post_types; // classical post type listing foreach ( $pts as $pt ) { $selected = in_array ( $pt, $options ['esml_monitor_types'] ) ? '1' : '0'; if ($selected == '1') { $types_to_track[] = $pt; } } // custom post types listing if (is_array ( $cpts ) && ! empty ( $cpts )) { foreach ( $cpts as $cpt ) { $selected = in_array ( $cpt, $options ['esml_monitor_types'] ) ? '1' : '0'; if ($selected == '1') { $types_to_track[] = $cpt; } $selected = in_array ( $cpt, $options ['esml_monitor_types'] ) ? 'checked="checked"' : ''; } } } return $types_to_track; } function extra_tablenav( $which ) { if ( $which == "top" ){ //The code that goes before the table is here $range = (isset($_GET['range'])) ? $_GET['range'] : 0; ?> <label for="range">Show only:</label> <select name="range"> <option value="1"<?php if ($range == 1) echo 'selected="selected"'; ?>>Items published within 1 Month</option> <option value="3"<?php if ($range == 3) echo 'selected="selected"'; ?>>Items published within 3 Months</option> <option value="6"<?php if ($range == 6) echo 'selected="selected"'; ?>>Items published within 6 Months</option> <option value="12"<?php if ($range == 12) echo 'selected="selected"'; ?>>Items published within 12 Months</option> <option value="0"<?php if ($range == 0) echo 'selected="selected"'; ?>>Items published anytime</option> </select> <?php do_action( 'esml_dashboard_query_options' ); // Allows developers to add additional sort options ?> <input type="submit" name="filter" id="submit_filter" class="button" value="Filter"> <a href="<?php echo admin_url('admin.php?page=easy-social-metrics-lite&esml_sync_all=true'); ?>" class="button">Update all posts</a> <?php } if ( $which == "bottom" ){ //The code that goes after the table is there } } function date_range_filter( $where = '' ) { $range = (isset($_GET['range'])) ? $_GET['range'] : '0'; if ($range <= 0) return $where; $range_bottom = " AND post_date >= '".date("Y-m-d", strtotime('-'.$range.' month') ); $range_top = "' AND post_date <= '".date("Y-m-d")."'"; $where .= $range_bottom . $range_top; return $where; } public function output_total_results() { echo '<table border="0" cellpadding="3" cellspacing="0" width="100%">'; echo '<col width="30%"/>'; echo '<col width="30%"/>'; echo '<col width="40%"/>'; echo '<tr>'; echo '<td><strong>Total Social Shares:</strong></td>'; echo '<td align="right"><strong>'.number_format($this->total_results['esml_socialcount_total']).'</strong></td>'; echo '<td>&nbsp;</td>'; echo '</tr>'; $total = $this->total_results['esml_socialcount_total']; $parse_list = array("facebook" => "Facebook", "twitter" => "Twitter", "googleplus" => "Google+", "pinterest" => "Pinterest", "linkedin" => "LinkedIn", "stumbleupon" => "StumbleUpon"); foreach ($parse_list as $singleValueCode => $singleValue) { $single_value = $this->total_results['esml_socialcount_'.$singleValueCode]; if ($total != 0) { $display_percent = number_format($single_value * 100 / $total, 2); $percent = number_format($single_value * 100 / $total); } else { $display_percent = "0.00"; $percent = "0"; } if (intval($percent) == 0 && intval($single_value) != 0) { $percent = 1; } echo '<tr>'; echo '<td>'.$singleValue.' <span style="background-color: #2980b9; padding: 2px 5px; color: #fff; font-size: 10px; border-radius: 3px;">'.$display_percent.' %</span></td>'; echo '<td align="right"><strong>'.number_format($single_value).'</strong></td>'; echo '<td><div style="background-color: #2980b9; display: block; height: 24px; width:'.$percent.'%;">&nbsp;</div></td>'; echo '</tr>'; } echo '</table>'; } public function output_total_content() { echo '<table border="0" cellpadding="5" cellspacing="0" width="100%">'; echo '<col width="20%"/>'; echo '<col width="20%"/>'; echo '<col width="60%"/>'; $parse_list = array("facebook" => "Facebook", "twitter" => "Twitter", "googleplus" => "Google+", "pinterest" => "Pinterest", "linkedin" => "LinkedIn", "stumbleupon" => "StumbleUpon"); foreach ($parse_list as $singleValueCode => $singleValue) { $single_value = $this->top_content['esml_socialcount_'.$singleValueCode]['value']; $title = $this->top_content['esml_socialcount_'.$singleValueCode]['title']; $permalink = $this->top_content['esml_socialcount_'.$singleValueCode]['permalink']; echo '<tr>'; echo '<td>'.$singleValue.'</td>'; echo '<td align="right"><strong>'.number_format($single_value).'</strong></td>'; echo '<td><a href="'.$permalink.'" target="_blank">'.$title.'</a></td>'; echo '</tr>'; } echo '</table>'; } } function esml_render_dashboard_view($options){ //Create an instance of our package class... $testListTable = new EasySocialMetricsLiteResultTable(); $testListTable->options = $options; //Fetch, prepare, sort, and filter our data... $testListTable->prepare_items(); ?> <style type="text/css"> .column-post_title { width: 30%; } .column-total { font-weight: bold; } </style> <div class="wrap"> <h2>Easy Social Metrics Lite Dashboard</h2> <div style="clear:both;"></div> <div class="welcome-panel"> <div class="welcome-panel-content"> <div class="welcome-panel-column-container"> <div class="welcome-panel-column" style="width: 49%;"> <h4>Social Networks Presentation</h4> <?php $testListTable->output_total_results(); ?> </div> <div class="welcome-panel-column" style="width: 49%;"> <h4>Top Shared Content by Social Network</h4> <?php $testListTable->output_total_content();?> </div> </div> </div> </div> <?php EasySocialMetricsUpdater::printQueueLength(); ?> <form id="easy-social-metrics-lite" method="get" action="admin.php?page=easy-social-metrics-lite"> <!-- For plugins, we also need to ensure that the form posts back to our current page --> <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>" /> <input type="hidden" name="orderby" value="<?php echo (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'total'; ?>" /> <input type="hidden" name="order" value="<?php echo (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'DESC'; ?>" /> <?php $testListTable->display() ?> </form> </div> <?php }
rvfeed/rfeed
wp-content/plugins/easy-social-share-buttons/lib/modules/easy-social-metrics-lite/esml-render-results.php
PHP
gpl-2.0
27,672
<form> <i class="glyphicon glyphicon-search"></i> <input type="text" name="q"> <button type="submit" class="hidden">{{ trans('labels.search') }}</button> </form>
manishkiozen/Cms
resources/views/widgets/toolbar/search.blade.php
PHP
gpl-2.0
173
<?php /** * @file * Contains Drupal\views\Plugin\views\display\DisplayPluginBase. */ namespace Drupal\views\Plugin\views\display; use Drupal\views\Plugin\views\area\AreaPluginBase; use Drupal\views\ViewExecutable; use \Drupal\views\Plugin\views\PluginBase; use Drupal\views\Views; /** * @defgroup views_display_plugins Views display plugins * @{ * Display plugins control how Views interact with the rest of Drupal. * * They can handle creating Views from a Drupal page hook; they can * handle creating Views from a Drupal block hook. They can also * handle creating Views from an external module source. */ /** * The default display plugin handler. Display plugins handle options and * basic mechanisms for different output methods. */ abstract class DisplayPluginBase extends PluginBase { /** * The top object of a view. * * @var Drupal\views\ViewExecutable */ var $view = NULL; var $handlers = array(); /** * An array of instantiated plugins used in this display. * * @var array */ protected $plugins = array(); /** * Stores all available display extenders. */ var $extender = array(); /** * Overrides Drupal\views\Plugin\Plugin::$usesOptions. */ protected $usesOptions = TRUE; /** * Stores the rendered output of the display. * * @see View::render * @var string */ public $output = NULL; /** * Whether the display allows the use of AJAX or not. * * @var bool */ protected $usesAJAX = TRUE; /** * Whether the display allows the use of a pager or not. * * @var bool */ protected $usesPager = TRUE; /** * Whether the display allows the use of a 'more' link or not. * * @var bool */ protected $usesMore = TRUE; /** * Whether the display allows attachments. * * @var bool * TRUE if the display can use attachments, or FALSE otherwise. */ protected $usesAttachments = FALSE; /** * Whether the display allows area plugins. * * @var bool */ protected $usesAreas = TRUE; public function initDisplay(ViewExecutable $view, array &$display, array &$options = NULL) { $this->setOptionDefaults($this->options, $this->defineOptions()); $this->view = $view; $this->display = &$display; // Load extenders as soon as possible. $this->extender = array(); $extenders = views_get_enabled_display_extenders(); if (!empty($extenders)) { $manager = Views::pluginManager('display_extender'); foreach ($extenders as $extender) { $plugin = $manager->createInstance($extender); if ($plugin) { $plugin->init($this->view, $this); $this->extender[$extender] = $plugin; } } } // Track changes that the user should know about. $changed = FALSE; // Make some modifications: if (!isset($options) && isset($display['display_options'])) { $options = $display['display_options']; } if ($this->isDefaultDisplay() && isset($options['defaults'])) { unset($options['defaults']); } // Cache for unpackOptions, but not if we are in the ui. static $unpack_options = array(); if (empty($view->editing)) { $cid = 'unpackOptions:' . hash('sha256', serialize(array($this->options, $options))); if (empty($unpack_options[$cid])) { $cache = views_cache_get($cid, TRUE); if (!empty($cache->data)) { $this->options = $cache->data; } else { $this->unpackOptions($this->options, $options); views_cache_set($cid, $this->options, TRUE); } $unpack_options[$cid] = $this->options; } else { $this->options = $unpack_options[$cid]; } } else { $this->unpackOptions($this->options, $options); } // Convert the field_language and field_language_add_to_query settings. $field_language = $this->getOption('field_language'); $field_language_add_to_query = $this->getOption('field_language_add_to_query'); if (isset($field_langcode)) { $this->setOption('field_langcode', $field_language); $this->setOption('field_langcode_add_to_query', $field_language_add_to_query); $changed = TRUE; } // Mark the view as changed so the user has a chance to save it. if ($changed) { $this->view->changed = TRUE; } } public function destroy() { parent::destroy(); foreach ($this->handlers as $type => $handlers) { foreach ($handlers as $id => $handler) { if (is_object($handler)) { $this->handlers[$type][$id]->destroy(); } } } if (isset($this->default_display)) { unset($this->default_display); } foreach ($this->extender as $extender) { $extender->destroy(); } } /** * Determine if this display is the 'default' display which contains * fallback settings */ public function isDefaultDisplay() { return FALSE; } /** * Determine if this display uses exposed filters, so the view * will know whether or not to build them. */ public function usesExposed() { if (!isset($this->has_exposed)) { foreach ($this->handlers as $type => $value) { foreach ($this->view->$type as $id => $handler) { if ($handler->canExpose() && $handler->isExposed()) { // one is all we need; if we find it, return true. $this->has_exposed = TRUE; return TRUE; } } } $pager = $this->getPlugin('pager'); if (isset($pager) && $pager->uses_exposed()) { $this->has_exposed = TRUE; return TRUE; } $this->has_exposed = FALSE; } return $this->has_exposed; } /** * Determine if this display should display the exposed * filters widgets, so the view will know whether or not * to render them. * * Regardless of what this function * returns, exposed filters will not be used nor * displayed unless usesExposed() returns TRUE. */ public function displaysExposed() { return TRUE; } /** * Whether the display allows the use of AJAX or not. * * @return bool */ public function usesAJAX() { return $this->usesAJAX; } /** * Whether the display is actually using AJAX or not. * * @return bool */ public function ajaxEnabled() { if ($this->usesAJAX()) { return $this->getOption('use_ajax'); } return FALSE; } /** * Whether the display is enabled. * * @return bool * Returns TRUE if the display is marked as enabled, else FALSE. */ public function isEnabled() { return (bool) $this->getOption('enabled'); } /** * Whether the display allows the use of a pager or not. * * @return bool */ public function usesPager() { return $this->usesPager; } /** * Whether the display is using a pager or not. * * @return bool */ public function isPagerEnabled() { if ($this->usesPager()) { $pager = $this->getPlugin('pager'); if ($pager) { return $pager->use_pager(); } } return FALSE; } /** * Whether the display allows the use of a 'more' link or not. * * @return bool */ public function usesMore() { return $this->usesMore; } /** * Whether the display is using the 'more' link or not. * * @return bool */ public function isMoreEnabled() { if ($this->usesMore()) { return $this->getOption('use_more'); } return FALSE; } /** * Does the display have groupby enabled? */ public function useGroupBy() { return $this->getOption('group_by'); } /** * Should the enabled display more link be shown when no more items? */ public function useMoreAlways() { if ($this->usesMore()) { return $this->getOption('useMoreAlways'); } return FALSE; } /** * Does the display have custom link text? */ public function useMoreText() { if ($this->usesMore()) { return $this->getOption('useMoreText'); } return FALSE; } /** * Determines whether this display can use attachments. * * @return bool */ public function acceptAttachments() { // To be able to accept attachments this display have to be able to use // attachments but at the same time, you cannot attach a display to itself. if (!$this->usesAttachments() || ($this->definition['id'] == $this->view->current_display)) { return FALSE; } if (!empty($this->view->argument) && $this->getOption('hide_attachment_summary')) { foreach ($this->view->argument as $argument_id => $argument) { if ($argument->needsStylePlugin() && empty($argument->argument_validated)) { return FALSE; } } } return TRUE; } /** * Returns whether the display can use attachments. * * @return bool */ public function usesAttachments() { return $this->usesAttachments; } /** * Returns whether the display can use areas. * * @return bool * TRUE if the display can use areas, or FALSE otherwise. */ public function usesAreas() { return $this->usesAreas; } /** * Allow displays to attach to other views. */ public function attachTo(ViewExecutable $view, $display_id) { } /** * Static member function to list which sections are defaultable * and what items each section contains. */ public function defaultableSections($section = NULL) { $sections = array( 'access' => array('access'), 'cache' => array('cache'), 'title' => array('title'), 'css_class' => array('css_class'), 'use_ajax' => array('use_ajax'), 'hide_attachment_summary' => array('hide_attachment_summary'), 'show_admin_links' => array('show_admin_links'), 'group_by' => array('group_by'), 'query' => array('query'), 'use_more' => array('use_more', 'use_more_always', 'use_more_text'), 'use_more_always' => array('use_more', 'use_more_always', 'use_more_text'), 'use_more_text' => array('use_more', 'use_more_always', 'use_more_text'), 'link_display' => array('link_display', 'link_url'), // Force these to cascade properly. 'style' => array('style', 'row'), 'row' => array('style', 'row'), 'pager' => array('pager', 'pager_options'), 'pager_options' => array('pager', 'pager_options'), 'exposed_form' => array('exposed_form', 'exposed_form_options'), 'exposed_form_options' => array('exposed_form', 'exposed_form_options'), // These guys are special 'header' => array('header'), 'footer' => array('footer'), 'empty' => array('empty'), 'relationships' => array('relationships'), 'fields' => array('fields'), 'sorts' => array('sorts'), 'arguments' => array('arguments'), 'filters' => array('filters', 'filter_groups'), 'filter_groups' => array('filters', 'filter_groups'), ); // If the display cannot use a pager, then we cannot default it. if (!$this->usesPager()) { unset($sections['pager']); unset($sections['items_per_page']); } foreach ($this->extender as $extender) { $extender->defaultableSections($sections, $section); } if ($section) { if (!empty($sections[$section])) { return $sections[$section]; } } else { return $sections; } } protected function defineOptions() { $options = array( 'defaults' => array( 'default' => array( 'access' => TRUE, 'cache' => TRUE, 'query' => TRUE, 'title' => TRUE, 'css_class' => TRUE, 'display_description' => FALSE, 'use_ajax' => TRUE, 'hide_attachment_summary' => TRUE, 'show_admin_links' => TRUE, 'pager' => TRUE, 'use_more' => TRUE, 'use_more_always' => TRUE, 'use_more_text' => TRUE, 'exposed_form' => TRUE, 'link_display' => TRUE, 'link_url' => '', 'group_by' => TRUE, 'style' => TRUE, 'row' => TRUE, 'header' => TRUE, 'footer' => TRUE, 'empty' => TRUE, 'relationships' => TRUE, 'fields' => TRUE, 'sorts' => TRUE, 'arguments' => TRUE, 'filters' => TRUE, 'filter_groups' => TRUE, ), ), 'title' => array( 'default' => '', 'translatable' => TRUE, ), 'enabled' => array( 'default' => TRUE, 'translatable' => FALSE, 'bool' => TRUE, ), 'display_comment' => array( 'default' => '', ), 'css_class' => array( 'default' => '', 'translatable' => FALSE, ), 'display_description' => array( 'default' => '', 'translatable' => TRUE, ), 'use_ajax' => array( 'default' => FALSE, 'bool' => TRUE, ), 'hide_attachment_summary' => array( 'default' => FALSE, 'bool' => TRUE, ), 'show_admin_links' => array( 'default' => TRUE, 'bool' => TRUE, ), 'use_more' => array( 'default' => FALSE, 'bool' => TRUE, ), 'use_more_always' => array( 'default' => FALSE, 'bool' => TRUE, ), 'use_more_text' => array( 'default' => 'more', 'translatable' => TRUE, ), 'link_display' => array( 'default' => '', ), 'link_url' => array( 'default' => '', ), 'group_by' => array( 'default' => FALSE, 'bool' => TRUE, ), 'field_langcode' => array( 'default' => '***CURRENT_LANGUAGE***', ), 'field_langcode_add_to_query' => array( 'default' => TRUE, 'bool' => TRUE, ), // These types are all plugins that can have individual settings // and therefore need special handling. 'access' => array( 'contains' => array( 'type' => array('default' => 'none'), 'options' => array('default' => array()), ), ), 'cache' => array( 'contains' => array( 'type' => array('default' => 'none'), 'options' => array('default' => array()), ), ), 'query' => array( 'contains' => array( 'type' => array('default' => 'views_query'), 'options' => array('default' => array()), ), ), 'exposed_form' => array( 'contains' => array( 'type' => array('default' => 'basic'), 'options' => array('default' => array()), ), ), 'pager' => array( 'contains' => array( 'type' => array('default' => 'mini'), 'options' => array('default' => array()), ), ), 'style' => array( 'contains' => array( 'type' => array('default' => 'default'), 'options' => array('default' => array()), ), ), 'row' => array( 'contains' => array( 'type' => array('default' => 'fields'), 'options' => array('default' => array()), ), ), 'exposed_block' => array( 'default' => FALSE, ), 'header' => array( 'default' => array(), ), 'footer' => array( 'default' => array(), ), 'empty' => array( 'default' => array(), ), // We want these to export last. // These are the 5 handler types. 'relationships' => array( 'default' => array(), ), 'fields' => array( 'default' => array(), ), 'sorts' => array( 'default' => array(), ), 'arguments' => array( 'default' => array(), ), 'filter_groups' => array( 'contains' => array( 'operator' => array('default' => 'AND'), 'groups' => array('default' => array(1 => 'AND')), ), ), 'filters' => array( 'default' => array(), ), ); if (!$this->usesPager()) { $options['defaults']['default']['use_pager'] = FALSE; $options['defaults']['default']['items_per_page'] = FALSE; $options['defaults']['default']['offset'] = FALSE; $options['defaults']['default']['pager'] = FALSE; $options['pager']['contains']['type']['default'] = 'some'; } if ($this->isDefaultDisplay()) { unset($options['defaults']); } foreach ($this->extender as $extender) { $extender->defineOptionsAlter($options); } return $options; } /** * Check to see if the display has a 'path' field. * * This is a pure function and not just a setting on the definition * because some displays (such as a panel pane) may have a path based * upon configuration. * * By default, displays do not have a path. */ public function hasPath() { return FALSE; } /** * Check to see if the display has some need to link to another display. * * For the most part, displays without a path will use a link display. However, * sometimes displays that have a path might also need to link to another display. * This is true for feeds. */ public function usesLinkDisplay() { return !$this->hasPath(); } /** * Check to see if the display can put the exposed formin a block. * * By default, displays that do not have a path cannot disconnect * the exposed form and put it in a block, because the form has no * place to go and Views really wants the forms to go to a specific * page. */ public function usesExposedFormInBlock() { return $this->hasPath(); } /** * Find out all displays which are attached to this display. * * The method is just using the pure storage object to avoid loading of the * sub displays which would kill lazy loading. */ public function getAttachedDisplays() { $current_display_id = $this->display['id']; $attached_displays = array(); // Go through all displays and search displays which link to this one. foreach ($this->view->storage->get('display') as $display_id => $display) { if (isset($display['display_options']['displays'])) { $displays = $display['display_options']['displays']; if (isset($displays[$current_display_id])) { $attached_displays[] = $display_id; } } } return $attached_displays; } /** * Check to see which display to use when creating links within * a view using this display. */ public function getLinkDisplay() { $display_id = $this->getOption('link_display'); // If unknown, pick the first one. if (empty($display_id) || !$this->view->displayHandlers->has($display_id)) { foreach ($this->view->displayHandlers as $display_id => $display) { if (!empty($display) && $display->hasPath()) { return $display_id; } } } else { return $display_id; } // fall-through returns NULL } /** * Return the base path to use for this display. * * This can be overridden for displays that do strange things * with the path. */ public function getPath() { if ($this->hasPath()) { return $this->getOption('path'); } $display_id = $this->getLinkDisplay(); if ($display_id && $this->view->displayHandlers->has($display_id) && is_object($this->view->displayHandlers->get($display_id))) { return $this->view->displayHandlers->get($display_id)->getPath(); } } public function getUrl() { return $this->view->getUrl(); } /** * Check to see if the display needs a breadcrumb * * By default, displays do not need breadcrumbs */ public function usesBreadcrumb() { return FALSE; } /** * Determine if a given option is set to use the default display or the * current display * * @return * TRUE for the default display */ public function isDefaulted($option) { return !$this->isDefaultDisplay() && !empty($this->default_display) && !empty($this->options['defaults'][$option]); } /** * Intelligently get an option either from this display or from the * default display, if directed to do so. */ public function getOption($option) { if ($this->isDefaulted($option)) { return $this->default_display->getOption($option); } if (array_key_exists($option, $this->options)) { return $this->options[$option]; } } /** * Determine if the display's style uses fields. * * @return bool */ public function usesFields() { return $this->getPlugin('style')->usesFields(); } /** * Get the instance of a plugin, for example style or row. * * @param string $type * The type of the plugin. * * @return \Drupal\views\Plugin\views\PluginBase */ public function getPlugin($type) { // Look up the plugin name to use for this instance. $options = $this->getOption($type); $name = $options['type']; // Query plugins allow specifying a specific query class per base table. if ($type == 'query') { $views_data = Views::viewsData()->get($this->view->storage->get('base_table')); $name = isset($views_data['table']['base']['query_id']) ? $views_data['table']['base']['query_id'] : 'views_query'; } // Plugin instances are stored on the display for re-use. if (!isset($this->plugins[$type][$name])) { $plugin = Views::pluginManager($type)->createInstance($name); // Initialize the plugin. $plugin->init($this->view, $this, $options['options']); $this->plugins[$type][$name] = $plugin; } return $this->plugins[$type][$name]; } /** * Get the handler object for a single handler. */ public function &getHandler($type, $id) { if (!isset($this->handlers[$type])) { $this->getHandlers($type); } if (isset($this->handlers[$type][$id])) { return $this->handlers[$type][$id]; } // So we can return a reference. $null = NULL; return $null; } /** * Get a full array of handlers for $type. This caches them. */ public function getHandlers($type) { if (!isset($this->handlers[$type])) { $this->handlers[$type] = array(); $types = ViewExecutable::viewsHandlerTypes(); $plural = $types[$type]['plural']; foreach ($this->getOption($plural) as $id => $info) { // If this is during form submission and there are temporary options // which can only appear if the view is in the edit cache, use those // options instead. This is used for AJAX multi-step stuff. if (isset($_POST['form_id']) && isset($this->view->temporary_options[$type][$id])) { $info = $this->view->temporary_options[$type][$id]; } if ($info['id'] != $id) { $info['id'] = $id; } // If aggregation is on, the group type might override the actual // handler that is in use. This piece of code checks that and, // if necessary, sets the override handler. $override = NULL; if ($this->useGroupBy() && !empty($info['group_type'])) { if (empty($this->view->query)) { $this->view->initQuery(); } $aggregate = $this->view->query->get_aggregation_info(); if (!empty($aggregate[$info['group_type']]['handler'][$type])) { $override = $aggregate[$info['group_type']]['handler'][$type]; } } if (!empty($types[$type]['type'])) { $handler_type = $types[$type]['type']; } else { $handler_type = $type; } if ($handler = views_get_handler($info, $handler_type, $override)) { // Special override for area types so they know where they come from. if ($handler instanceof AreaPluginBase) { $handler->areaType = $type; } $handler->init($this->view, $this, $info); $this->handlers[$type][$id] = &$handler; } // Prevent reference problems. unset($handler); } } return $this->handlers[$type]; } /** * Retrieves a list of fields for the current display. * * This also takes into account any associated relationships, if they exist. * * @param bool $groupable_only * (optional) TRUE to only return an array of field labels from handlers * that support the use_string_group_by method, defaults to FALSE. * * @return array * An array of applicable field options, keyed by ID. */ public function getFieldLabels($groupable_only = FALSE) { $options = array(); foreach ($this->getHandlers('relationship') as $relationship => $handler) { $relationships[$relationship] = $handler->adminLabel(); } foreach ($this->getHandlers('field') as $id => $handler) { if ($groupable_only && !$handler->use_string_group_by()) { // Continue to next handler if it's not groupable. continue; } if ($label = $handler->label()) { $options[$id] = $label; } else { $options[$id] = $handler->adminLabel(); } if (!empty($handler->options['relationship']) && !empty($relationships[$handler->options['relationship']])) { $options[$id] = '(' . $relationships[$handler->options['relationship']] . ') ' . $options[$id]; } } return $options; } /** * Intelligently set an option either from this display or from the * default display, if directed to do so. */ public function setOption($option, $value) { if ($this->isDefaulted($option)) { return $this->default_display->setOption($option, $value); } // Set this in two places: On the handler where we'll notice it // but also on the display object so it gets saved. This should // only be a temporary fix. $this->display['display_options'][$option] = $value; return $this->options[$option] = $value; } /** * Set an option and force it to be an override. */ public function overrideOption($option, $value) { $this->setOverride($option, FALSE); $this->setOption($option, $value); } /** * Because forms may be split up into sections, this provides * an easy URL to exactly the right section. Don't override this. */ public function optionLink($text, $section, $class = '', $title = '') { if (!empty($class)) { $text = '<span>' . $text . '</span>'; } if (!trim($text)) { $text = t('Broken field'); } if (empty($title)) { $title = $text; } return l($text, 'admin/structure/views/nojs/display/' . $this->view->storage->id() . '/' . $this->display['id'] . '/' . $section, array('attributes' => array('class' => 'views-ajax-link ' . $class, 'title' => $title, 'id' => drupal_html_id('views-' . $this->display['id'] . '-' . $section)), 'html' => TRUE)); } /** * Returns to tokens for arguments. * * This function is similar to views_handler_field::get_render_tokens() * but without fields tokens. */ public function getArgumentsTokens() { $tokens = array(); if (!empty($this->view->build_info['substitutions'])) { $tokens = $this->view->build_info['substitutions']; } $count = 0; foreach ($this->view->display_handler->getHandlers('argument') as $arg => $handler) { $token = '%' . ++$count; if (!isset($tokens[$token])) { $tokens[$token] = ''; } // Use strip tags as there should never be HTML in the path. // However, we need to preserve special characters like " that // were removed by check_plain(). $tokens['!' . $count] = isset($this->view->args[$count - 1]) ? strip_tags(decode_entities($this->view->args[$count - 1])) : ''; } return $tokens; } /** * Provide the default summary for options in the views UI. * * This output is returned as an array. */ public function optionsSummary(&$categories, &$options) { $categories = array( 'title' => array( 'title' => t('Title'), 'column' => 'first', ), 'format' => array( 'title' => t('Format'), 'column' => 'first', ), 'filters' => array( 'title' => t('Filters'), 'column' => 'first', ), 'fields' => array( 'title' => t('Fields'), 'column' => 'first', ), 'pager' => array( 'title' => t('Pager'), 'column' => 'second', ), 'exposed' => array( 'title' => t('Exposed form'), 'column' => 'third', 'build' => array( '#weight' => 1, ), ), 'access' => array( 'title' => '', 'column' => 'second', 'build' => array( '#weight' => -5, ), ), 'other' => array( 'title' => t('Other'), 'column' => 'third', 'build' => array( '#weight' => 2, ), ), ); if ($this->display['id'] != 'default') { $options['display_id'] = array( 'category' => 'other', 'title' => t('Machine Name'), 'value' => !empty($this->display['new_id']) ? check_plain($this->display['new_id']) : check_plain($this->display['id']), 'desc' => t('Change the machine name of this display.'), ); } $display_comment = check_plain(drupal_substr($this->getOption('display_comment'), 0, 10)); $options['display_comment'] = array( 'category' => 'other', 'title' => t('Administrative comment'), 'value' => !empty($display_comment) ? $display_comment : t('None'), 'desc' => t('Comment or document this display.'), ); $title = strip_tags($this->getOption('title')); if (!$title) { $title = t('None'); } $options['title'] = array( 'category' => 'title', 'title' => t('Title'), 'value' => $title, 'desc' => t('Change the title that this display will use.'), ); $style_plugin_instance = $this->getPlugin('style'); $style_summary = empty($style_plugin_instance->definition['title']) ? t('Missing style plugin') : $style_plugin_instance->summaryTitle(); $style_title = empty($style_plugin_instance->definition['title']) ? t('Missing style plugin') : $style_plugin_instance->pluginTitle(); $style = ''; $options['style'] = array( 'category' => 'format', 'title' => t('Format'), 'value' => $style_title, 'setting' => $style_summary, 'desc' => t('Change the way content is formatted.'), ); // This adds a 'Settings' link to the style_options setting if the style has options. if ($style_plugin_instance->usesOptions()) { $options['style']['links']['style_options'] = t('Change settings for this format'); } if ($style_plugin_instance->usesRowPlugin()) { $row_plugin_instance = $this->getPlugin('row'); $row_summary = empty($row_plugin_instance->definition['title']) ? t('Missing style plugin') : $row_plugin_instance->summaryTitle(); $row_title = empty($row_plugin_instance->definition['title']) ? t('Missing style plugin') : $row_plugin_instance->pluginTitle(); $options['row'] = array( 'category' => 'format', 'title' => t('Show'), 'value' => $row_title, 'setting' => $row_summary, 'desc' => t('Change the way each row in the view is styled.'), ); // This adds a 'Settings' link to the row_options setting if the row style has options. if ($row_plugin_instance->usesOptions()) { $options['row']['links']['row_options'] = t('Change settings for this style'); } } if ($this->usesAJAX()) { $options['use_ajax'] = array( 'category' => 'other', 'title' => t('Use AJAX'), 'value' => $this->getOption('use_ajax') ? t('Yes') : t('No'), 'desc' => t('Change whether or not this display will use AJAX.'), ); } if ($this->usesAttachments()) { $options['hide_attachment_summary'] = array( 'category' => 'other', 'title' => t('Hide attachments in summary'), 'value' => $this->getOption('hide_attachment_summary') ? t('Yes') : t('No'), 'desc' => t('Change whether or not to display attachments when displaying a contextual filter summary.'), ); } if (!isset($this->definition['contextual links locations']) || !empty($this->definition['contextual links locations'])) { $options['show_admin_links'] = array( 'category' => 'other', 'title' => t('Contextual links'), 'value' => $this->getOption('show_admin_links') ? t('Shown') : t('Hidden'), 'desc' => t('Change whether or not to display contextual links for this view.'), ); } $pager_plugin = $this->getPlugin('pager'); if (!$pager_plugin) { // default to the no pager plugin. $pager_plugin = Views::pluginManager('pager')->createInstance('none'); } $pager_str = $pager_plugin->summaryTitle(); $options['pager'] = array( 'category' => 'pager', 'title' => t('Use pager'), 'value' => $pager_plugin->pluginTitle(), 'setting' => $pager_str, 'desc' => t("Change this display's pager setting."), ); // If pagers aren't allowed, change the text of the item: if (!$this->usesPager()) { $options['pager']['title'] = t('Items to display'); } if ($pager_plugin->usesOptions()) { $options['pager']['links']['pager_options'] = t('Change settings for this pager type.'); } if ($this->usesMore()) { $options['use_more'] = array( 'category' => 'pager', 'title' => t('More link'), 'value' => $this->getOption('use_more') ? t('Yes') : t('No'), 'desc' => t('Specify whether this display will provide a "more" link.'), ); } $this->view->initQuery(); if ($this->view->query->get_aggregation_info()) { $options['group_by'] = array( 'category' => 'other', 'title' => t('Use aggregation'), 'value' => $this->getOption('group_by') ? t('Yes') : t('No'), 'desc' => t('Allow grouping and aggregation (calculation) of fields.'), ); } $options['query'] = array( 'category' => 'other', 'title' => t('Query settings'), 'value' => t('Settings'), 'desc' => t('Allow to set some advanced settings for the query plugin'), ); $languages = array( '***CURRENT_LANGUAGE***' => t("Current user's language"), '***DEFAULT_LANGUAGE***' => t("Default site language"), LANGUAGE_NOT_SPECIFIED => t('Language neutral'), ); if (\Drupal::moduleHandler()->moduleExists('language')) { $languages = array_merge($languages, language_list()); } $options['field_langcode'] = array( 'category' => 'other', 'title' => t('Field Language'), 'value' => $languages[$this->getOption('field_langcode')], 'desc' => t('All fields which support translations will be displayed in the selected language.'), ); $access_plugin = $this->getPlugin('access'); if (!$access_plugin) { // default to the no access control plugin. $access_plugin = Views::pluginManager('access')->createInstance('none'); } $access_str = $access_plugin->summaryTitle(); $options['access'] = array( 'category' => 'access', 'title' => t('Access'), 'value' => $access_plugin->pluginTitle(), 'setting' => $access_str, 'desc' => t('Specify access control type for this display.'), ); if ($access_plugin->usesOptions()) { $options['access']['links']['access_options'] = t('Change settings for this access type.'); } $cache_plugin = $this->getPlugin('cache'); if (!$cache_plugin) { // default to the no cache control plugin. $cache_plugin = Views::pluginManager('cache')->createInstance('none'); } $cache_str = $cache_plugin->summaryTitle(); $options['cache'] = array( 'category' => 'other', 'title' => t('Caching'), 'value' => $cache_plugin->pluginTitle(), 'setting' => $cache_str, 'desc' => t('Specify caching type for this display.'), ); if ($cache_plugin->usesOptions()) { $options['cache']['links']['cache_options'] = t('Change settings for this caching type.'); } if ($access_plugin->usesOptions()) { $options['access']['links']['access_options'] = t('Change settings for this access type.'); } if ($this->usesLinkDisplay()) { $display_id = $this->getLinkDisplay(); $displays = $this->view->storage->get('display'); $link_display = empty($displays[$display_id]) ? t('None') : check_plain($displays[$display_id]['display_title']); $link_display = $this->getOption('link_display') == 'custom_url' ? t('Custom URL') : $link_display; $options['link_display'] = array( 'category' => 'other', 'title' => t('Link display'), 'value' => $link_display, 'desc' => t('Specify which display or custom url this display will link to.'), ); } if ($this->usesExposedFormInBlock()) { $options['exposed_block'] = array( 'category' => 'exposed', 'title' => t('Exposed form in block'), 'value' => $this->getOption('exposed_block') ? t('Yes') : t('No'), 'desc' => t('Allow the exposed form to appear in a block instead of the view.'), ); } $exposed_form_plugin = $this->getPlugin('exposed_form'); if (!$exposed_form_plugin) { // default to the no cache control plugin. $exposed_form_plugin = Views::pluginManager('exposed_form')->createInstance('basic'); } $exposed_form_str = $exposed_form_plugin->summaryTitle(); $options['exposed_form'] = array( 'category' => 'exposed', 'title' => t('Exposed form style'), 'value' => $exposed_form_plugin->pluginTitle(), 'setting' => $exposed_form_str, 'desc' => t('Select the kind of exposed filter to use.'), ); if ($exposed_form_plugin->usesOptions()) { $options['exposed_form']['links']['exposed_form_options'] = t('Exposed form settings for this exposed form style.'); } $css_class = check_plain(trim($this->getOption('css_class'))); if (!$css_class) { $css_class = t('None'); } $options['css_class'] = array( 'category' => 'other', 'title' => t('CSS class'), 'value' => $css_class, 'desc' => t('Change the CSS class name(s) that will be added to this display.'), ); $options['analyze-theme'] = array( 'category' => 'other', 'title' => t('Output'), 'value' => t('Templates'), 'desc' => t('Get information on how to theme this display'), ); foreach ($this->extender as $extender) { $extender->optionsSummary($categories, $options); } } /** * Provide the default form for setting options. */ public function buildOptionsForm(&$form, &$form_state) { parent::buildOptionsForm($form, $form_state); if ($this->defaultableSections($form_state['section'])) { views_ui_standard_display_dropdown($form, $form_state, $form_state['section']); } $form['#title'] = check_plain($this->display['display_title']) . ': '; // Set the 'section' to hilite on the form. // If it's the item we're looking at is pulling from the default display, // reflect that. Don't use is_defaulted since we want it to show up even // on the default display. if (!empty($this->options['defaults'][$form_state['section']])) { $form['#section'] = 'default-' . $form_state['section']; } else { $form['#section'] = $this->display['id'] . '-' . $form_state['section']; } switch ($form_state['section']) { case 'display_id': $form['#title'] .= t('The machine name of this display'); $form['display_id'] = array( '#type' => 'textfield', '#title' => t('Machine name of the display'), '#default_value' => !empty($this->display['new_id']) ? $this->display['new_id'] : $this->display['id'], '#required' => TRUE, '#size' => 64, ); break; case 'display_title': $form['#title'] .= t('The name and the description of this display'); $form['display_title'] = array( '#title' => t('Administrative name'), '#type' => 'textfield', '#default_value' => $this->display['display_title'], ); $form['display_description'] = array( '#title' => t('Administrative description'), '#type' => 'textfield', '#default_value' => $this->getOption('display_description'), ); break; case 'display_comment': $form['#title'] .= t('Administrative comment'); $form['display_comment'] = array( '#type' => 'textarea', '#title' => t('Administrative comment'), '#description' => t('This description will only be seen within the administrative interface and can be used to document this display.'), '#default_value' => $this->getOption('display_comment'), ); break; case 'title': $form['#title'] .= t('The title of this view'); $form['title'] = array( '#type' => 'textfield', '#description' => t('This title will be displayed with the view, wherever titles are normally displayed; i.e, as the page title, block title, etc.'), '#default_value' => $this->getOption('title'), ); break; case 'css_class': $form['#title'] .= t('CSS class'); $form['css_class'] = array( '#type' => 'textfield', '#title' => t('CSS class name(s)'), '#description' => t('Multiples classes should be separated by spaces.'), '#default_value' => $this->getOption('css_class'), ); break; case 'use_ajax': $form['#title'] .= t('Use AJAX when available to load this view'); $form['use_ajax'] = array( '#description' => t('When viewing a view, things like paging, table sorting, and exposed filters will not trigger a page refresh.'), '#type' => 'checkbox', '#title' => t('Use AJAX'), '#default_value' => $this->getOption('use_ajax') ? 1 : 0, ); break; case 'hide_attachment_summary': $form['#title'] .= t('Hide attachments when displaying a contextual filter summary'); $form['hide_attachment_summary'] = array( '#type' => 'checkbox', '#title' => t('Hide attachments in summary'), '#default_value' => $this->getOption('hide_attachment_summary') ? 1 : 0, ); break; case 'show_admin_links': $form['#title'] .= t('Show contextual links on this view.'); $form['show_admin_links'] = array( '#type' => 'checkbox', '#title' => t('Show contextual links'), '#default_value' => $this->getOption('show_admin_links'), ); break; case 'use_more': $form['#title'] .= t('Add a more link to the bottom of the display.'); $form['use_more'] = array( '#type' => 'checkbox', '#title' => t('Create more link'), '#description' => t("This will add a more link to the bottom of this view, which will link to the page view. If you have more than one page view, the link will point to the display specified in 'Link display' section under advanced. You can override the url at the link display setting."), '#default_value' => $this->getOption('use_more'), ); $form['use_more_always'] = array( '#type' => 'checkbox', '#title' => t("Display 'more' link only if there is more content"), '#description' => t("Leave this unchecked to display the 'more' link even if there are no more items to display."), '#default_value' => !$this->getOption('use_more_always'), '#states' => array( 'visible' => array( ':input[name="use_more"]' => array('checked' => TRUE), ), ), ); $form['use_more_text'] = array( '#type' => 'textfield', '#title' => t('More link text'), '#description' => t("The text to display for the more link."), '#default_value' => $this->getOption('useMoreText'), '#states' => array( 'visible' => array( ':input[name="use_more"]' => array('checked' => TRUE), ), ), ); break; case 'group_by': $form['#title'] .= t('Allow grouping and aggregation (calculation) of fields.'); $form['group_by'] = array( '#type' => 'checkbox', '#title' => t('Aggregate'), '#description' => t('If enabled, some fields may become unavailable. All fields that are selected for grouping will be collapsed to one record per distinct value. Other fields which are selected for aggregation will have the function run on them. For example, you can group nodes on title and count the number of nids in order to get a list of duplicate titles.'), '#default_value' => $this->getOption('group_by'), ); break; case 'access': $form['#title'] .= t('Access restrictions'); $form['access'] = array( '#prefix' => '<div class="clearfix">', '#suffix' => '</div>', '#tree' => TRUE, ); $access = $this->getOption('access'); $form['access']['type'] = array( '#type' => 'radios', '#options' => views_fetch_plugin_names('access', $this->getType(), array($this->view->storage->get('base_table'))), '#default_value' => $access['type'], ); $access_plugin = $this->getPlugin('access'); if ($access_plugin->usesOptions()) { $form['markup'] = array( '#prefix' => '<div class="form-item description">', '#markup' => t('You may also adjust the !settings for the currently selected access restriction.', array('!settings' => $this->optionLink(t('settings'), 'access_options'))), '#suffix' => '</div>', ); } break; case 'access_options': $plugin = $this->getPlugin('access'); $form['#title'] .= t('Access options'); if ($plugin) { $form['access_options'] = array( '#tree' => TRUE, ); $plugin->buildOptionsForm($form['access_options'], $form_state); } break; case 'cache': $form['#title'] .= t('Caching'); $form['cache'] = array( '#prefix' => '<div class="clearfix">', '#suffix' => '</div>', '#tree' => TRUE, ); $cache = $this->getOption('cache'); $form['cache']['type'] = array( '#type' => 'radios', '#options' => views_fetch_plugin_names('cache', $this->getType(), array($this->view->storage->get('base_table'))), '#default_value' => $cache['type'], ); $cache_plugin = $this->getPlugin('cache'); if ($cache_plugin->usesOptions()) { $form['markup'] = array( '#prefix' => '<div class="form-item description">', '#suffix' => '</div>', '#markup' => t('You may also adjust the !settings for the currently selected cache mechanism.', array('!settings' => $this->optionLink(t('settings'), 'cache_options'))), ); } break; case 'cache_options': $plugin = $this->getPlugin('cache'); $form['#title'] .= t('Caching options'); if ($plugin) { $form['cache_options'] = array( '#tree' => TRUE, ); $plugin->buildOptionsForm($form['cache_options'], $form_state); } break; case 'query': $query_options = $this->getOption('query'); $plugin_name = $query_options['type']; $form['#title'] .= t('Query options'); $this->view->initQuery(); if ($this->view->query) { $form['query'] = array( '#tree' => TRUE, 'type' => array( '#type' => 'value', '#value' => $plugin_name, ), 'options' => array( '#tree' => TRUE, ), ); $this->view->query->buildOptionsForm($form['query']['options'], $form_state); } break; case 'field_language': $form['#title'] .= t('Field Language'); $entities = entity_get_info(); $entity_tables = array(); $has_translation_handlers = FALSE; foreach ($entities as $type => $entity_info) { $entity_tables[] = $entity_info['base_table']; if (!empty($entity_info['translation'])) { $has_translation_handlers = TRUE; } } // Doesn't make sense to show a field setting here if we aren't querying // an entity base table. Also, we make sure that there's at least one // entity type with a translation handler attached. if (in_array($this->view->storage->get('base_table'), $entity_tables) && $has_translation_handlers) { $languages = array( '***CURRENT_LANGUAGE***' => t("Current user's language"), '***DEFAULT_LANGUAGE***' => t("Default site language"), LANGUAGE_NOT_SPECIFIED => t('Language neutral'), ); $languages = array_merge($languages, views_language_list()); $form['field_langcode'] = array( '#type' => 'select', '#title' => t('Field Language'), '#description' => t('All fields which support translations will be displayed in the selected language.'), '#options' => $languages, '#default_value' => $this->getOption('field_langcode'), ); $form['field_langcode_add_to_query'] = array( '#type' => 'checkbox', '#title' => t('When needed, add the field language condition to the query'), '#default_value' => $this->getOption('field_langcode_add_to_query'), ); } else { $form['field_language']['#markup'] = t("You don't have translatable entity types."); } break; case 'style': $form['#title'] .= t('How should this view be styled'); $style_plugin = $this->getPlugin('style'); $form['style'] = array( '#type' => 'radios', '#options' => views_fetch_plugin_names('style', $this->getType(), array($this->view->storage->get('base_table'))), '#default_value' => $style_plugin->definition['id'], '#description' => t('If the style you choose has settings, be sure to click the settings button that will appear next to it in the View summary.'), ); if ($style_plugin->usesOptions()) { $form['markup'] = array( '#prefix' => '<div class="form-item description">', '#suffix' => '</div>', '#markup' => t('You may also adjust the !settings for the currently selected style.', array('!settings' => $this->optionLink(t('settings'), 'style_options'))), ); } break; case 'style_options': $form['#title'] .= t('Style options'); $style = TRUE; $style_plugin = $this->getOption('style'); $name = $style_plugin['type']; case 'row_options': if (!isset($name)) { $row_plugin = $this->getOption('row'); $name = $row_plugin['type']; } // if row, $style will be empty. if (empty($style)) { $form['#title'] .= t('Row style options'); } $plugin = $this->getPlugin(empty($style) ? 'row' : 'style', $name); if ($plugin) { $form[$form_state['section']] = array( '#tree' => TRUE, ); $plugin->buildOptionsForm($form[$form_state['section']], $form_state); } break; case 'row': $form['#title'] .= t('How should each row in this view be styled'); $row_plugin_instance = $this->getPlugin('row'); $form['row'] = array( '#type' => 'radios', '#options' => views_fetch_plugin_names('row', $this->getType(), array($this->view->storage->get('base_table'))), '#default_value' => $row_plugin_instance->definition['id'], ); if ($row_plugin_instance->usesOptions()) { $form['markup'] = array( '#prefix' => '<div class="form-item description">', '#suffix' => '</div>', '#markup' => t('You may also adjust the !settings for the currently selected row style.', array('!settings' => $this->optionLink(t('settings'), 'row_options'))), ); } break; case 'link_display': $form['#title'] .= t('Which display to use for path'); foreach ($this->view->storage->get('display') as $display_id => $display) { if ($this->view->displayHandlers->get($display_id)->hasPath()) { $options[$display_id] = $display['display_title']; } } $options['custom_url'] = t('Custom URL'); if (count($options)) { $form['link_display'] = array( '#type' => 'radios', '#options' => $options, '#description' => t("Which display to use to get this display's path for things like summary links, rss feed links, more links, etc."), '#default_value' => $this->getOption('link_display'), ); } $options = array(); $count = 0; // This lets us prepare the key as we want it printed. foreach ($this->view->display_handler->getHandlers('argument') as $arg => $handler) { $options[t('Arguments')]['%' . ++$count] = t('@argument title', array('@argument' => $handler->adminLabel())); $options[t('Arguments')]['!' . $count] = t('@argument input', array('@argument' => $handler->adminLabel())); } // Default text. // We have some options, so make a list. $output = ''; if (!empty($options)) { $output = t('<p>The following tokens are available for this link.</p>'); foreach (array_keys($options) as $type) { if (!empty($options[$type])) { $items = array(); foreach ($options[$type] as $key => $value) { $items[] = $key . ' == ' . $value; } $output .= theme('item_list', array( 'items' => $items, 'type' => $type )); } } } $form['link_url'] = array( '#type' => 'textfield', '#title' => t('Custom URL'), '#default_value' => $this->getOption('link_url'), '#description' => t('A Drupal path or external URL the more link will point to. Note that this will override the link display setting above.') . $output, '#states' => array( 'visible' => array( ':input[name="link_display"]' => array('value' => 'custom_url'), ), ), ); break; case 'analyze-theme': $form['#title'] .= t('Theming information'); if ($theme = drupal_container()->get('request')->request->get('theme')) { $this->theme = $theme; } elseif (empty($this->theme)) { $this->theme = config('system.theme')->get('default'); } if (isset($GLOBALS['theme']) && $GLOBALS['theme'] == $this->theme) { $this->theme_registry = theme_get_registry(); $theme_engine = $GLOBALS['theme_engine']; } else { $themes = list_themes(); $theme = $themes[$this->theme]; // Find all our ancestor themes and put them in an array. $base_theme = array(); $ancestor = $this->theme; while ($ancestor && isset($themes[$ancestor]->base_theme)) { $ancestor = $themes[$ancestor]->base_theme; $base_theme[] = $themes[$ancestor]; } // The base themes should be initialized in the right order. $base_theme = array_reverse($base_theme); // This code is copied directly from _drupal_theme_initialize() $theme_engine = NULL; // Initialize the theme. if (isset($theme->engine)) { // Include the engine. include_once DRUPAL_ROOT . '/' . $theme->owner; $theme_engine = $theme->engine; if (function_exists($theme_engine . '_init')) { foreach ($base_theme as $base) { call_user_func($theme_engine . '_init', $base); } call_user_func($theme_engine . '_init', $theme); } } else { // include non-engine theme files foreach ($base_theme as $base) { // Include the theme file or the engine. if (!empty($base->owner)) { include_once DRUPAL_ROOT . '/' . $base->owner; } } // and our theme gets one too. if (!empty($theme->owner)) { include_once DRUPAL_ROOT . '/' . $theme->owner; } } $this->theme_registry = _theme_load_registry($theme, $base_theme, $theme_engine); } // If there's a theme engine involved, we also need to know its extension // so we can give the proper filename. $this->theme_extension = '.tpl.php'; if (isset($theme_engine)) { $extension_function = $theme_engine . '_extension'; if (function_exists($extension_function)) { $this->theme_extension = $extension_function(); } } $funcs = array(); // Get theme functions for the display. Note that some displays may // not have themes. The 'feed' display, for example, completely // delegates to the style. if (!empty($this->definition['theme'])) { $funcs[] = $this->optionLink(t('Display output'), 'analyze-theme-display') . ': ' . $this->formatThemes($this->themeFunctions()); } $plugin = $this->getPlugin('style'); if ($plugin) { $funcs[] = $this->optionLink(t('Style output'), 'analyze-theme-style') . ': ' . $this->formatThemes($plugin->themeFunctions()); if ($plugin->usesRowPlugin()) { $row_plugin = $this->getPlugin('row'); if ($row_plugin) { $funcs[] = $this->optionLink(t('Row style output'), 'analyze-theme-row') . ': ' . $this->formatThemes($row_plugin->themeFunctions()); } } if ($plugin->usesFields()) { foreach ($this->getHandlers('field') as $id => $handler) { $funcs[] = $this->optionLink(t('Field @field (ID: @id)', array('@field' => $handler->adminLabel(), '@id' => $id)), 'analyze-theme-field') . ': ' . $this->formatThemes($handler->themeFunctions()); } } } $form['important'] = array( '#markup' => '<div class="form-item description"><p>' . t('This section lists all possible templates for the display plugin and for the style plugins, ordered roughly from the least specific to the most specific. The active template for each plugin -- which is the most specific template found on the system -- is highlighted in bold.') . '</p></div>', ); if (isset($this->view->display_handler->new_id)) { $form['important']['new_id'] = array( '#prefix' => '<div class="description">', '#suffix' => '</div>', '#value' => t("<strong>Important!</strong> You have changed the display's machine name. Anything that attached to this display specifically, such as theming, may stop working until it is updated. To see theme suggestions for it, you need to save the view."), ); } foreach (list_themes() as $key => $theme) { if (!empty($theme->info['hidden'])) { continue; } $options[$key] = $theme->info['name']; } $form['box'] = array( '#prefix' => '<div class="container-inline">', '#suffix' => '</div>', ); $form['box']['theme'] = array( '#type' => 'select', '#options' => $options, '#default_value' => $this->theme, ); $form['box']['change'] = array( '#type' => 'submit', '#value' => t('Change theme'), '#submit' => array(array($this, 'changeThemeForm')), ); $form['analysis'] = array( '#markup' => '<div class="form-item">' . theme('item_list', array('items' => $funcs)) . '</div>', ); $form['rescan_button'] = array( '#prefix' => '<div class="form-item">', '#suffix' => '</div>', ); $form['rescan_button']['button'] = array( '#type' => 'submit', '#value' => t('Rescan template files'), '#submit' => array(array($this, 'rescanThemes')), ); $form['rescan_button']['markup'] = array( '#markup' => '<div class="description">' . t("<strong>Important!</strong> When adding, removing, or renaming template files, it is necessary to make Drupal aware of the changes by making it rescan the files on your system. By clicking this button you clear Drupal's theme registry and thereby trigger this rescanning process. The highlighted templates above will then reflect the new state of your system.") . '</div>', ); $form_state['ok_button'] = TRUE; break; case 'analyze-theme-display': $form['#title'] .= t('Theming information (display)'); $output = '<p>' . t('Back to !info.', array('!info' => $this->optionLink(t('theming information'), 'analyze-theme'))) . '</p>'; if (empty($this->definition['theme'])) { $output .= t('This display has no theming information'); } else { $output .= '<p>' . t('This is the default theme template used for this display.') . '</p>'; $output .= '<pre>' . check_plain(file_get_contents('./' . $this->definition['theme_path'] . '/' . strtr($this->definition['theme'], '_', '-') . '.tpl.php')) . '</pre>'; } $form['analysis'] = array( '#markup' => '<div class="form-item">' . $output . '</div>', ); $form_state['ok_button'] = TRUE; break; case 'analyze-theme-style': $form['#title'] .= t('Theming information (style)'); $output = '<p>' . t('Back to !info.', array('!info' => $this->optionLink(t('theming information'), 'analyze-theme'))) . '</p>'; $plugin = $this->getPlugin('style'); if (empty($plugin->definition['theme'])) { $output .= t('This display has no style theming information'); } else { $output .= '<p>' . t('This is the default theme template used for this style.') . '</p>'; $output .= '<pre>' . check_plain(file_get_contents('./' . $plugin->definition['theme_path'] . '/' . strtr($plugin->definition['theme'], '_', '-') . '.tpl.php')) . '</pre>'; } $form['analysis'] = array( '#markup' => '<div class="form-item">' . $output . '</div>', ); $form_state['ok_button'] = TRUE; break; case 'analyze-theme-row': $form['#title'] .= t('Theming information (row style)'); $output = '<p>' . t('Back to !info.', array('!info' => $this->optionLink(t('theming information'), 'analyze-theme'))) . '</p>'; $plugin = $this->getPlugin('row'); if (empty($plugin->definition['theme'])) { $output .= t('This display has no row style theming information'); } else { $output .= '<p>' . t('This is the default theme template used for this row style.') . '</p>'; $output .= '<pre>' . check_plain(file_get_contents('./' . $plugin->definition['theme_path'] . '/' . strtr($plugin->definition['theme'], '_', '-') . '.tpl.php')) . '</pre>'; } $form['analysis'] = array( '#markup' => '<div class="form-item">' . $output . '</div>', ); $form_state['ok_button'] = TRUE; break; case 'analyze-theme-field': $form['#title'] .= t('Theming information (row style)'); $output = '<p>' . t('Back to !info.', array('!info' => $this->optionLink(t('theming information'), 'analyze-theme'))) . '</p>'; $output .= '<p>' . t('This is the default theme template used for this row style.') . '</p>'; // Field templates aren't registered the normal way...and they're always // this one, anyhow. $output .= '<pre>' . check_plain(file_get_contents(drupal_get_path('module', 'views') . '/templates/views-view-field.tpl.php')) . '</pre>'; $form['analysis'] = array( '#markup' => '<div class="form-item">' . $output . '</div>', ); $form_state['ok_button'] = TRUE; break; case 'exposed_block': $form['#title'] .= t('Put the exposed form in a block'); $form['description'] = array( '#markup' => '<div class="description form-item">' . t('If set, any exposed widgets will not appear with this view. Instead, a block will be made available to the Drupal block administration system, and the exposed form will appear there. Note that this block must be enabled manually, Views will not enable it for you.') . '</div>', ); $form['exposed_block'] = array( '#type' => 'radios', '#options' => array(1 => t('Yes'), 0 => t('No')), '#default_value' => $this->getOption('exposed_block') ? 1 : 0, ); break; case 'exposed_form': $form['#title'] .= t('Exposed Form'); $form['exposed_form'] = array( '#prefix' => '<div class="clearfix">', '#suffix' => '</div>', '#tree' => TRUE, ); $exposed_form = $this->getOption('exposed_form'); $form['exposed_form']['type'] = array( '#type' => 'radios', '#options' => views_fetch_plugin_names('exposed_form', $this->getType(), array($this->view->storage->get('base_table'))), '#default_value' => $exposed_form['type'], ); $exposed_form_plugin = $this->getPlugin('exposed_form'); if ($exposed_form_plugin->usesOptions()) { $form['markup'] = array( '#prefix' => '<div class="form-item description">', '#suffix' => '</div>', '#markup' => t('You may also adjust the !settings for the currently selected style.', array('!settings' => $this->optionLink(t('settings'), 'exposed_form_options'))), ); } break; case 'exposed_form_options': $plugin = $this->getPlugin('exposed_form'); $form['#title'] .= t('Exposed form options'); if ($plugin) { $form['exposed_form_options'] = array( '#tree' => TRUE, ); $plugin->buildOptionsForm($form['exposed_form_options'], $form_state); } break; case 'pager': $form['#title'] .= t('Select which pager, if any, to use for this view'); $form['pager'] = array( '#prefix' => '<div class="clearfix">', '#suffix' => '</div>', '#tree' => TRUE, ); $pager = $this->getOption('pager'); $form['pager']['type'] = array( '#type' => 'radios', '#options' => views_fetch_plugin_names('pager', !$this->usesPager() ? 'basic' : NULL, array($this->view->storage->get('base_table'))), '#default_value' => $pager['type'], ); $pager_plugin = $this->getPlugin('pager'); if ($pager_plugin->usesOptions()) { $form['markup'] = array( '#prefix' => '<div class="form-item description">', '#suffix' => '</div>', '#markup' => t('You may also adjust the !settings for the currently selected pager.', array('!settings' => $this->optionLink(t('settings'), 'pager_options'))), ); } break; case 'pager_options': $plugin = $this->getPlugin('pager'); $form['#title'] .= t('Pager options'); if ($plugin) { $form['pager_options'] = array( '#tree' => TRUE, ); $plugin->buildOptionsForm($form['pager_options'], $form_state); } break; } foreach ($this->extender as $extender) { $extender->buildOptionsForm($form, $form_state); } } /** * Submit hook to clear Drupal's theme registry (thereby triggering * a templates rescan). */ public function rescanThemes($form, &$form_state) { drupal_theme_rebuild(); // The 'Theme: Information' page is about to be shown again. That page // analyzes the output of theme_get_registry(). However, this latter // function uses an internal cache (which was initialized before we // called drupal_theme_rebuild()) so it won't reflect the // current state of our theme registry. The only way to clear that cache // is to re-initialize the theme system: unset($GLOBALS['theme']); drupal_theme_initialize(); $form_state['rerender'] = TRUE; $form_state['rebuild'] = TRUE; } /** * Displays the Change Theme form. */ public function changeThemeForm($form, &$form_state) { // This is just a temporary variable. $form_state['view']->theme = $form_state['values']['theme']; $form_state['view']->cacheSet(); $form_state['rerender'] = TRUE; $form_state['rebuild'] = TRUE; } /** * Format a list of theme templates for output by the theme info helper. */ protected function formatThemes($themes) { $registry = $this->theme_registry; $extension = $this->theme_extension; $output = ''; $picked = FALSE; foreach ($themes as $theme) { $template = strtr($theme, '_', '-') . $extension; if (!$picked && !empty($registry[$theme])) { $template_path = isset($registry[$theme]['path']) ? $registry[$theme]['path'] . '/' : './'; if (file_exists($template_path . $template)) { $hint = t('File found in folder @template-path', array('@template-path' => $template_path)); $template = '<strong title="'. $hint .'">' . $template . '</strong>'; } else { $template = '<strong class="error">' . $template . ' ' . t('(File not found, in folder @template-path)', array('@template-path' => $template_path)) . '</strong>'; } $picked = TRUE; } $fixed[] = $template; } return theme('item_list', array('items' => array_reverse($fixed))); } /** * Validate the options form. */ public function validateOptionsForm(&$form, &$form_state) { switch ($form_state['section']) { case 'display_title': if (empty($form_state['values']['display_title'])) { form_error($form['display_title'], t('Display title may not be empty.')); } break; case 'css_class': $css_class = $form_state['values']['css_class']; if (preg_match('/[^a-zA-Z0-9-_ ]/', $css_class)) { form_error($form['css_class'], t('CSS classes must be alphanumeric or dashes only.')); } break; case 'display_id': if ($form_state['values']['display_id']) { if (preg_match('/[^a-z0-9_]/', $form_state['values']['display_id'])) { form_error($form['display_id'], t('Display name must be letters, numbers, or underscores only.')); } foreach ($this->view->display as $id => $display) { if ($id != $this->view->current_display && ($form_state['values']['display_id'] == $id || (isset($display->new_id) && $form_state['values']['display_id'] == $display->new_id))) { form_error($form['display_id'], t('Display id should be unique.')); } } } break; case 'query': if ($this->view->query) { $this->view->query->validateOptionsForm($form['query'], $form_state); } break; } // Validate plugin options. Every section with "_options" in it, belongs to // a plugin type, like "style_options". if (strpos($form_state['section'], '_options') !== FALSE) { $plugin_type = str_replace('_options', '', $form_state['section']); // Load the plugin and let it handle the validation. if ($plugin = $this->getPlugin($plugin_type)) { $plugin->validateOptionsForm($form[$form_state['section']], $form_state); } } foreach ($this->extender as $extender) { $extender->validateOptionsForm($form, $form_state); } } /** * Perform any necessary changes to the form values prior to storage. * There is no need for this function to actually store the data. */ public function submitOptionsForm(&$form, &$form_state) { // Not sure I like this being here, but it seems (?) like a logical place. $cache_plugin = $this->getPlugin('cache'); if ($cache_plugin) { $cache_plugin->cache_flush(); } $section = $form_state['section']; switch ($section) { case 'display_id': if (isset($form_state['values']['display_id'])) { $this->display['new_id'] = $form_state['values']['display_id']; } break; case 'display_title': $this->display['display_title'] = $form_state['values']['display_title']; $this->setOption('display_description', $form_state['values']['display_description']); break; case 'access': $access = $this->getOption('access'); if ($access['type'] != $form_state['values']['access']['type']) { $plugin = Views::pluginManager('access')->createInstance($form_state['values']['access']['type']); if ($plugin) { $access = array('type' => $form_state['values']['access']['type']); $this->setOption('access', $access); if ($plugin->usesOptions()) { $form_state['view']->addFormToStack('display', $this->display['id'], 'access_options'); } } } break; case 'access_options': $plugin = $this->getPlugin('access'); if ($plugin) { $access = $this->getOption('access'); $plugin->submitOptionsForm($form['access_options'], $form_state); $access['options'] = $form_state['values'][$section]; $this->setOption('access', $access); } break; case 'cache': $cache = $this->getOption('cache'); if ($cache['type'] != $form_state['values']['cache']['type']) { $plugin = Views::pluginManager('cache')->createInstance($form_state['values']['cache']['type']); if ($plugin) { $cache = array('type' => $form_state['values']['cache']['type']); $this->setOption('cache', $cache); if ($plugin->usesOptions()) { $form_state['view']->addFormToStack('display', $this->display['id'], 'cache_options'); } } } break; case 'cache_options': $plugin = $this->getPlugin('cache'); if ($plugin) { $cache = $this->getOption('cache'); $plugin->submitOptionsForm($form['cache_options'], $form_state); $cache['options'] = $form_state['values'][$section]; $this->setOption('cache', $cache); } break; case 'query': $plugin = $this->getPlugin('query'); if ($plugin) { $plugin->submitOptionsForm($form['query']['options'], $form_state); $this->setOption('query', $form_state['values'][$section]); } break; case 'link_display': $this->setOption('link_url', $form_state['values']['link_url']); case 'title': case 'css_class': case 'display_comment': $this->setOption($section, $form_state['values'][$section]); break; case 'field_language': $this->setOption('field_langcode', $form_state['values']['field_langcode']); $this->setOption('field_langcode_add_to_query', $form_state['values']['field_langcode_add_to_query']); break; case 'use_ajax': case 'hide_attachment_summary': case 'show_admin_links': $this->setOption($section, (bool) $form_state['values'][$section]); break; case 'use_more': $this->setOption($section, intval($form_state['values'][$section])); $this->setOption('use_more_always', !intval($form_state['values']['use_more_always'])); $this->setOption('use_more_text', $form_state['values']['use_more_text']); case 'distinct': $this->setOption($section, $form_state['values'][$section]); break; case 'group_by': $this->setOption($section, $form_state['values'][$section]); break; case 'row': // This if prevents resetting options to default if they don't change // the plugin. $row = $this->getOption('row'); if ($row['type'] != $form_state['values'][$section]) { $plugin = Views::pluginManager('row')->createInstance($form_state['values'][$section]); if ($plugin) { $row = array('type' => $form_state['values'][$section]); $this->setOption($section, $row); // send ajax form to options page if we use it. if ($plugin->usesOptions()) { $form_state['view']->addFormToStack('display', $this->display['id'], 'row_options'); } } } break; case 'style': // This if prevents resetting options to default if they don't change // the plugin. $style = $this->getOption('style'); if ($style['type'] != $form_state['values'][$section]) { $plugin = views::pluginManager('style')->createInstance($form_state['values'][$section]); if ($plugin) { $row = array('type' => $form_state['values'][$section]); $this->setOption($section, $row); // send ajax form to options page if we use it. if ($plugin->usesOptions()) { $form_state['view']->addFormToStack('display', $this->display['id'], 'style_options'); } } } break; case 'style_options': $plugin = $this->getPlugin('style'); if ($plugin) { $style = $this->getOption('style'); $plugin->submitOptionsForm($form['style_options'], $form_state); $style['options'] = $form_state['values'][$section]; $this->setOption('style', $style); } break; case 'row_options': $plugin = $this->getPlugin('row'); if ($plugin) { $row = $this->getOption('row'); $plugin->submitOptionsForm($form['row_options'], $form_state); $row['options'] = $form_state['values'][$section]; $this->setOption('row', $row); } break; case 'exposed_block': $this->setOption($section, (bool) $form_state['values'][$section]); break; case 'exposed_form': $exposed_form = $this->getOption('exposed_form'); if ($exposed_form['type'] != $form_state['values']['exposed_form']['type']) { $plugin = Views::pluginManager('exposed_form')->createInstance($form_state['values']['exposed_form']['type']); if ($plugin) { $exposed_form = array('type' => $form_state['values']['exposed_form']['type'], 'options' => array()); $this->setOption('exposed_form', $exposed_form); if ($plugin->usesOptions()) { $form_state['view']->addFormToStack('display', $this->display['id'], 'exposed_form_options'); } } } break; case 'exposed_form_options': $plugin = $this->getPlugin('exposed_form'); if ($plugin) { $exposed_form = $this->getOption('exposed_form'); $plugin->submitOptionsForm($form['exposed_form_options'], $form_state); $exposed_form['options'] = $form_state['values'][$section]; $this->setOption('exposed_form', $exposed_form); } break; case 'pager': $pager = $this->getOption('pager'); if ($pager['type'] != $form_state['values']['pager']['type']) { $plugin = Views::pluginManager('pager')->createInstance($form_state['values']['pager']['type']); if ($plugin) { // Because pagers have very similar options, let's allow pagers to // try to carry the options over. $plugin->init($this->view, $this, $pager['options']); $pager = array('type' => $form_state['values']['pager']['type'], 'options' => $plugin->options); $this->setOption('pager', $pager); if ($plugin->usesOptions()) { $form_state['view']->addFormToStack('display', $this->display['id'], 'pager_options'); } } } break; case 'pager_options': $plugin = $this->getPlugin('pager'); if ($plugin) { $pager = $this->getOption('pager'); $plugin->submitOptionsForm($form['pager_options'], $form_state); $pager['options'] = $form_state['values'][$section]; $this->setOption('pager', $pager); } break; } foreach ($this->extender as $extender) { $extender->submitOptionsForm($form, $form_state); } } /** * If override/revert was clicked, perform the proper toggle. */ public function optionsOverride($form, &$form_state) { $this->setOverride($form_state['section']); } /** * Flip the override setting for the given section. * * @param string $section * Which option should be marked as overridden, for example "filters". * @param bool $new_state * Select the new state of the option. * - TRUE: Revert to default. * - FALSE: Mark it as overridden. */ public function setOverride($section, $new_state = NULL) { $options = $this->defaultableSections($section); if (!$options) { return; } if (!isset($new_state)) { $new_state = empty($this->options['defaults'][$section]); } // For each option that is part of this group, fix our settings. foreach ($options as $option) { if ($new_state) { // Revert to defaults. unset($this->options[$option]); unset($this->display['display_options'][$option]); } else { // copy existing values into our display. $this->options[$option] = $this->getOption($option); $this->display['display_options'][$option] = $this->options[$option]; } $this->options['defaults'][$option] = $new_state; $this->display['display_options']['defaults'][$option] = $new_state; } } /** * Inject anything into the query that the display handler needs. */ public function query() { foreach ($this->extender as $extender) { $extender->query(); } } /** * Not all display plugins will support filtering * * @todo this doesn't seems to be used */ public function renderFilters() { } /** * Not all display plugins will suppert pager rendering. */ public function renderPager() { return TRUE; } /** * Render the 'more' link */ public function renderMoreLink() { if ($this->usesMore() && ($this->useMoreAlways() || (!empty($this->view->pager) && $this->view->pager->has_more_records()))) { $path = $this->getPath(); if ($this->getOption('link_display') == 'custom_url' && $override_path = $this->getOption('link_url')) { $tokens = $this->getArgumentsTokens(); $path = strtr($override_path, $tokens); } if ($path) { if (empty($override_path)) { $path = $this->view->getUrl(NULL, $path); } $url_options = array(); if (!empty($this->view->exposed_raw_input)) { $url_options['query'] = $this->view->exposed_raw_input; } $theme = views_theme_functions('views_more', $this->view, $this->view->display_handler->display); $path = check_url(url($path, $url_options)); return theme($theme, array('more_url' => $path, 'link_text' => check_plain($this->useMoreText()), 'view' => $this->view)); } } } /** * If this display creates a page with a menu item, implement it here. * * @param array $callbacks * An array of already existing menu items provided by drupal. * * @return array * The menu router items registers for this display. * * @see hook_menu() */ public function executeHookMenu($callbacks) { return array(); } /** * Render this display. */ public function render() { $element = array( '#theme' => $this->themeFunctions(), '#view' => $this->view, ); $element['#attached'] = &$this->view->element['#attached']; return $element; } /** * Render one of the available areas. * * @param string $area * Identifier of the specific area to render. * @param bool $empty * (optional) Indicator whether or not the view result is empty. Defaults to * FALSE * * @return array * A render array for the given area. */ public function renderArea($area, $empty = FALSE) { $return = array(); foreach ($this->getHandlers($area) as $key => $area_handler) { $return[$key] = $area_handler->render($empty); } return $return; } /** * Determine if the user has access to this display of the view. */ public function access($account = NULL) { if (!isset($account)) { global $user; $account = $user; } // Full override. if (user_access('access all views', $account)) { return TRUE; } $plugin = $this->getPlugin('access'); if ($plugin) { return $plugin->access($account); } // fallback to all access if no plugin. return TRUE; } /** * Set up any variables on the view prior to execution. These are separated * from execute because they are extremely common and unlikely to be * overridden on an individual display. */ public function preExecute() { $this->view->setAjaxEnabled($this->ajaxEnabled()); if ($this->usesMore() && !$this->useMoreAlways()) { $this->view->get_total_rows = TRUE; } $this->view->initHandlers(); if ($this->usesExposed()) { $exposed_form = $this->getPlugin('exposed_form'); $exposed_form->pre_execute(); } foreach ($this->extender as $extender) { $extender->pre_execute(); } $this->view->setShowAdminLinks($this->getOption('show_admin_links')); } /** * When used externally, this is how a view gets run and returns * data in the format required. * * The base class cannot be executed. */ public function execute() { } /** * Fully render the display for the purposes of a live preview or * some other AJAXy reason. */ function preview() { return $this->view->render(); } /** * Returns the display type that this display requires. * * This can be used for filtering views plugins. E.g. if a plugin category of * 'foo' is specified, only plugins with no 'types' declared or 'types' * containing 'foo'. If you have a type of bar, this plugin will not be used. * This is applicable for style, row, access, cache, and exposed_form plugins. * * @return string * The required display type. Defaults to 'normal'. * * @see views_fetch_plugin_names() */ protected function getType() { return 'normal'; } /** * Make sure the display and all associated handlers are valid. * * @return * Empty array if the display is valid; an array of error strings if it is not. */ public function validate() { $errors = array(); // Make sure displays that use fields HAVE fields. if ($this->usesFields()) { $fields = FALSE; foreach ($this->getHandlers('field') as $field) { if (empty($field->options['exclude'])) { $fields = TRUE; } } if (!$fields) { $errors[] = t('Display "@display" uses fields but there are none defined for it or all are excluded.', array('@display' => $this->display['display_title'])); } } if ($this->hasPath() && !$this->getOption('path')) { $errors[] = t('Display "@display" uses a path but the path is undefined.', array('@display' => $this->display['display_title'])); } // Validate style plugin $style = $this->getPlugin('style'); if (empty($style)) { $errors[] = t('Display "@display" has an invalid style plugin.', array('@display' => $this->display['display_title'])); } else { $result = $style->validate(); if (!empty($result) && is_array($result)) { $errors = array_merge($errors, $result); } } // Validate query plugin. $query = $this->getPlugin('query'); $result = $query->validate(); if (!empty($result) && is_array($result)) { $errors = array_merge($errors, $result); } // Validate handlers foreach (ViewExecutable::viewsHandlerTypes() as $type => $info) { foreach ($this->getHandlers($type) as $handler) { $result = $handler->validate(); if (!empty($result) && is_array($result)) { $errors = array_merge($errors, $result); } } } return $errors; } /** * Reacts on deleting a display. */ public function remove() { } /** * Check if the provided identifier is unique. * * @param string $id * The id of the handler which is checked. * @param string $identifier * The actual get identifier configured in the exposed settings. * * @return bool * Returns whether the identifier is unique on all handlers. * */ public function isIdentifierUnique($id, $identifier) { foreach (ViewExecutable::viewsHandlerTypes() as $type => $info) { foreach ($this->getHandlers($type) as $key => $handler) { if ($handler->canExpose() && $handler->isExposed()) { if ($handler->isAGroup()) { if ($id != $key && $identifier == $handler->options['group_info']['identifier']) { return FALSE; } } else { if ($id != $key && $identifier == $handler->options['expose']['identifier']) { return FALSE; } } } } } return TRUE; } /** * Provide the block system with any exposed widget blocks for this display. */ public function getSpecialBlocks() { $blocks = array(); if ($this->usesExposedFormInBlock()) { $delta = '-exp-' . $this->view->storage->id() . '-' . $this->display['id']; $desc = t('Exposed form: @view-@display_id', array('@view' => $this->view->storage->id(), '@display_id' => $this->display['id'])); $blocks[$delta] = array( 'info' => $desc, 'cache' => DRUPAL_NO_CACHE, ); } return $blocks; } /** * Render the exposed form as block. * * @return string|NULL * The rendered exposed form as string or NULL otherwise. */ public function viewExposedFormBlocks() { // avoid interfering with the admin forms. if (arg(0) == 'admin' && arg(1) == 'structure' && arg(2) == 'views') { return; } $this->view->initHandlers(); if ($this->usesExposed() && $this->getOption('exposed_block')) { $exposed_form = $this->getPlugin('exposed_form'); return $exposed_form->render_exposed_form(TRUE); } } /** * Provide some helpful text for the arguments. * The result should contain of an array with * - filter value present: The title of the fieldset in the argument * where you can configure what should be done with a given argument. * - filter value not present: The tiel of the fieldset in the argument * where you can configure what should be done if the argument does not * exist. * - description: A description about how arguments comes to the display. * For example blocks don't get it from url. */ public function getArgumentText() { return array( 'filter value not present' => t('When the filter value is <em>NOT</em> available'), 'filter value present' => t('When the filter value <em>IS</em> available or a default is provided'), 'description' => t("This display does not have a source for contextual filters, so no contextual filter value will be available unless you select 'Provide default'."), ); } /** * Provide some helpful text for pagers. * * The result should contain of an array within * - items per page title */ public function getPagerText() { return array( 'items per page title' => t('Items to display'), 'items per page description' => t('Enter 0 for no limit.') ); } } /** * @} */
eugenesia/eugenesia.co.uk
core/modules/views/lib/Drupal/views/Plugin/views/display/DisplayPluginBase.php
PHP
gpl-2.0
93,395
<?php namespace Nutri\IngredientBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Nutri\IngredientBundle\Entity\Ingredient; use Nutri\IngredientBundle\Form\IngredientType; /** * Ingredient controller. * * @Route("/ingredient") */ class IngredientController extends Controller { /** ************************************************************************ * Display the Ingredient's homepage. * @Route("/{currentPageNumber}", requirements={"currentPageNumber" = "\d+"}, defaults={"currentPageNumber" = 1}) **************************************************************************/ public function homeAction($currentPageNumber) { $maxIngredients = 20; $ingredientsCount = $this->getDoctrine() ->getRepository('NutriIngredientBundle:Ingredient') ->countTotal(); $pagination = array( 'page' => $currentPageNumber, 'route' => 'nutri_ingredient_ingredient_home', 'pages_count' => ceil($ingredientsCount / $maxIngredients), 'route_params' => array() ); $ingredients = $this->getDoctrine()->getRepository('NutriIngredientBundle:Ingredient') ->getList($currentPageNumber, $maxIngredients); return $this->render('NutriIngredientBundle:Ingredient:home.html.twig', array( 'ingredients' => $ingredients, 'pagination' => $pagination )); } /** ************************************************************************ * Create a new Ingredient according to the information given in the form. * @Route("/add") **************************************************************************/ public function addAction() { $ingredient = new Ingredient(); $form = $this->createForm(new IngredientType(), $ingredient); // ------------- Request Management ------------------------------------ $request = $this->get('request'); if ($request->getMethod() == 'POST') { $form->bind($request);// Link Request and Form if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($ingredient); $em->flush(); return $this->redirect($this->generateUrl('nutri_ingredient_ingredient_see', array('ingredient_id' => $ingredient->getId()))); } } return $this->render('NutriIngredientBundle:Ingredient:add.html.twig', array( 'form' => $form->createView(), )); } /** ************************************************************************ * Display a Ingredient * @param Ingredient $ingredient * @ParamConverter("ingredient", options={"mapping": {"ingredient_id": "id"}}) * @Route("/see/{ingredient_id}", requirements={"ingredient_id" = "\d+"}) **************************************************************************/ public function seeAction(Ingredient $ingredient) { return $this->render('NutriIngredientBundle:Ingredient:see.html.twig', array( 'ingredient' => $ingredient, )); } /** ************************************************************************ * Modify a Ingredient according to the information given in the form. * * @param Ingredient $ingredient * @ParamConverter("ingredient", options={"mapping": {"ingredient_id": "id"}}) * @Route("/modify/{ingredient_id}", requirements={"ingredient_id" = "\d+"}) **************************************************************************/ public function modifyAction(Ingredient $ingredient) { $form = $this->createForm(new IngredientType($ingredient), $ingredient); // ------------- Request Management ------------------------------------ $request = $this->get('request'); if ($request->getMethod() == 'POST') { $form->bind($request); // Link Request and Form if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($ingredient); $em->flush(); return $this->redirect($this->generateUrl('nutri_ingredient_ingredient_see', array('ingredient_id' => $ingredient->getId()))); } } return $this->render('NutriIngredientBundle:Ingredient:modify.html.twig', array( 'ingredient' => $ingredient, 'form' => $form->createView(), )); } /** ************************************************************************ * Delete a Ingredient. * * @param Ingredient $ingredient * @ParamConverter("ingredient", options={"mapping": {"ingredient_id": "id"}}) * @Route("/delete/{ingredient_id}", requirements={"ingredient_id" = "\d+"}) **************************************************************************/ public function deleteAction(Ingredient $ingredient) { $request = $this->get('request'); if ($request->getMethod() == 'POST') { $em = $this->getDoctrine()->getManager(); $em->remove($ingredient); $em->flush(); return $this->redirect($this->generateUrl(/* Redirect to some page */)); } else{ throw new \Symfony\Component\Security\Core\Exception\AccessDeniedException; } } /** ************************************************************************ * Ajax function. * * @Route("/search") * @Method({"POST","GET"}) **************************************************************************/ public function searchAction() { $name = $this->get('request')->request->get('name'); $nameStringArray = explode(' ',$name); $searchInCiqual = ($this->get('request')->request->get('ciqual') === 'true'); $searchInOpenFoodFact = ($this->get('request')->request->get('openfoodfact') === 'true'); $em = $this->getDoctrine()->getManager(); $qb = $em->createQueryBuilder(); $qb->select('i'); $qb->from("NutriIngredientBundle:Ingredient",'i'); foreach($nameStringArray as $key=>$nameString) { $qb->andWhere($qb->expr()->like('i.name', ':nameSearched_'.$key)); $qb->setParameter(':nameSearched_'.$key, '%'.$nameString.'%'); } if(!$searchInCiqual) { $qb->andWhere($qb->expr()->isNull('i.ciqualcode')); } if(!$searchInOpenFoodFact) { $qb->andWhere($qb->expr()->isNull('i.barcode')); } $qb->orderBy('i.name'); $ingredientArray = $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); return $this->render('NutriIngredientBundle:Ingredient:searchResultDisplay.html.twig', array( 'ingredients' => $ingredientArray, )); } }
blacksad12/oliorga
src/Nutri/IngredientBundle/Controller/IngredientController.php
PHP
gpl-2.0
7,210
class Java::Util::ArrayList < Array overload_protected { include Java::Util::JavaList } class Iterator def initialize(array, from_index = 0, to_index = nil) @array = array @index = from_index @to_index = to_index || @array.size end def has_next @index < @to_index end def next_ entry = @array[@index] @index += 1 entry end def remove @index -= 1 @to_index -= 1 @array.delete_at @index end end class SubList def initialize(parent_list, from_index, to_index) @parent_list = parent_list @from_index = from_index @to_index = to_index end def size @to_index - @from_index end def iterator Iterator.new @parent_list, @from_index, @to_index end end def initialize(data = nil) case data when nil # do nothing when Array self.concat data when Integer # initial capacity, ignored else raise ArgumentError end end alias_method :add, :<< alias_method :get, :[] alias_method :contains, :include? alias_method :is_empty, :empty? def add(a1, a2 = nil) if a2 self.insert a1, a2 else self << a1 end end def remove(o) if o.is_a? Integer delete_at o else delete o end end def index_of(e) index(e) || -1 end def to_a self end def to_array(target_array = nil) target_array ||= Array.typed(Object).new if target_array.size <= self.size target_array.replace self else target_array[0, self.size] = self target_array[self.size] = nil end target_array end def iterator Iterator.new self end def sub_list(from_index, to_index) SubList.new self, from_index, to_index end def remove_all(list) delete_if { |item| list.include? item } end end
neelance/jre4ruby
jre4ruby/rep/java/util/ArrayList.rb
Ruby
gpl-2.0
1,889
<?php function ___main___() { $descriptor = json_decode(file_get_contents(dirname(dirname(dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME']))))) . '/program.json'), true); $versions = json_decode(file_get_contents(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/workspace/packages/test/etc/versions.json'), true); $urls = json_decode(file_get_contents(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/workspace/packages/test/etc/urls.json'), true); $url = str_replace('%%VERSION%%', $versions['ZendFramework'][$descriptor['implements']['github.com/firephp/firephp/workspace/packages/test/0.1']['dependencies']['ZendFramework']], $urls['ZendFramework']); $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/workspace/.pinf-packages/downloads/packages/' . substr($url, strpos($url, '/') + 2) . "~pkg/library"; set_include_path('.' . PATH_SEPARATOR . $path); date_default_timezone_set('America/Vancouver'); } ___main___(); // @see http://framework.zend.com/manual/1.11/en/learning.autoloading.usage.html require_once 'Zend/Loader/Autoloader.php'; Zend_Loader_Autoloader::getInstance(); /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * 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@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Wildfire * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /* NOTE: You must have Zend Framework in your include path! */ /* * Add our Firebug Log Writer to the registry */ require_once 'Zend/Registry.php'; require_once 'Zend/Log.php'; require_once 'Zend/Log/Writer/Firebug.php'; $writer = new Zend_Log_Writer_Firebug(); $writer->setPriorityStyle(8, 'TABLE'); $writer->setPriorityStyle(9, 'TRACE'); $logger = new Zend_Log($writer); $logger->addPriority('TABLE', 8); $logger->addPriority('TRACE', 9); Zend_Registry::set('logger',$logger); /* * Add our Firebug DB Profiler to the registry */ require_once 'Zend/Db.php'; require_once 'Zend/Db/Profiler/Firebug.php'; $profiler = new Zend_Db_Profiler_Firebug('All DB Queries'); $db = Zend_Db::factory('PDO_SQLITE', array('dbname' => ':memory:', 'profiler' => $profiler)); $db->getProfiler()->setEnabled(true); Zend_Registry::set('db',$db); /* * Run the front controller */ require_once 'Zend/Controller/Front.php'; Zend_Controller_Front::run(dirname(dirname(__FILE__)).'/application/controllers');
kennaisom/mk9
firephp-master/tests/zendframework/demo/public/index.php
PHP
gpl-2.0
2,893
<div id="page-wrapper" > <div id="page-inner"> <!-- Row de Titulos --> <div class="row"> <div class="col-lg-6"> <div class="input-group"> <input type="text" class="form-control" placeholder="Buscar por Palabras Clave"> <span class="input-group-btn"> <button class="btn btn-default glyphicon glyphicon-search" type="button"></button> </span> </div> </div> <br /> <hr /> <!-- paginacion de videos --> <div class="col-md-12"> <?php if ($material){ echo $material; } else { echo 'No Hay Nada Que Mostrar'; } ?> </div> <br /> <div align='center' class="col-sm-6 col-md-12"> <?=$pagination?> </div> <!-- END paginacion de videos --> <!-- /. row --> </div> <!-- /. PAGE INNER --> </div>
vanichel/Biblioteca-Virtual
application/views/wrapper/view_categoria_material.php
PHP
gpl-2.0
865
using NPOI.HSSF.UserModel; using NPOI.HSSF.Util; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; namespace NoRain.Toolkits { public class XMLOutputTool { private static Type[] _valueTypes = new[] { typeof(bool),typeof(byte),typeof(sbyte),typeof(char) ,typeof(decimal), typeof(double),typeof(float),typeof(int),typeof(uint),typeof(long),typeof(ulong),typeof(object),typeof(short),typeof(ushort),typeof(string)}; private static Type[] _numTypes = new[] {typeof(byte),typeof(sbyte) ,typeof(decimal), typeof(double),typeof(float),typeof(int),typeof(uint),typeof(long),typeof(ulong),typeof(short),typeof(ushort)}; /// <summary> /// 导出数据为Excel文件 /// </summary> /// <param name="items">数据源</param> public static void HandleItems<T>(IEnumerable<T> items, string tabelName) where T : class { var response = HttpContext.Current.Response; string filename = "test.xlsx"; response.Clear(); response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename)); XSSFWorkbook workbook = new XSSFWorkbook(); ISheet sheet1 = workbook.CreateSheet("Sheet1"); if (items == null || items.Count() == 0) { response.Write("无相关记录"); response.Flush(); response.End(); } var item = items.ToList()[0]; Type t = item.GetType(); var fields = t.GetFields(); var properties = t.GetProperties(); ICellStyle style = workbook.CreateCellStyle(); style.Alignment = HorizontalAlignment.Center; IFont font = workbook.CreateFont(); font.FontHeightInPoints = 12; font.FontHeight = 20; font.Boldweight = 600; style.SetFont(font); //标题行 var titleCell = sheet1.CreateRow(0).CreateCell(0); titleCell.SetCellValue(tabelName ?? "统计报表"); titleCell.CellStyle = style; //合并首行标题 sheet1.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, fields.Length + properties.Length - 1)); //列名 var headRow = sheet1.CreateRow(1); foreach (var f in fields) { var cell = headRow.CreateCell(fields.ToList().IndexOf(f)); cell.SetCellValue(f.Name); } foreach (var f in properties) { var cell = headRow.CreateCell(properties.ToList().IndexOf(f)); cell.SetCellValue(f.Name); } foreach (var obj in items) { var itemRow = sheet1.CreateRow(2 + items.ToList().IndexOf(obj)); foreach (var f in fields) { //判断单元格类型 var cellType = CellType.Blank; //数字 if (_numTypes.Contains(f.FieldType)) cellType = CellType.Numeric; var itemCell = itemRow.CreateCell(fields.ToList().IndexOf(f), cellType); if (_valueTypes.Contains(f.FieldType)) itemCell.SetCellValue(f.GetValue(obj).ToString()); else if (f.GetType() == typeof(DateTime) || f.GetType() == typeof(DateTime?)) itemCell.SetCellValue(f.GetValue(obj).ToString()); } foreach (var f in properties) { //判断单元格类型 var cellType = CellType.Blank; //数字 if (_numTypes.Contains(f.PropertyType)) cellType = CellType.Numeric; ////日期 //else if (f.GetType() == typeof(DateTime) || f.GetType() == typeof(DateTime?)) cellType=CellType.d; var itemCell = itemRow.CreateCell(fields.Length + properties.ToList().IndexOf(f), cellType); if (_valueTypes.Contains(f.PropertyType)) itemCell.SetCellValue(f.GetValue(obj, null).ToString()); else if (f.GetType() == typeof(DateTime) || f.GetType() == typeof(DateTime?)) itemCell.SetCellValue(f.GetValue(obj, null).ToString()); } } using (var f = File.Create(@"d:\test.xlsx")) { workbook.Write(f); } response.WriteFile(@"d:\test.xlsx"); //http://social.msdn.microsoft.com/Forums/en-US/3a7bdd79-f926-4a5e-bcb0-ef81b6c09dcf/responseoutputstreamwrite-writes-all-but-insetrs-a-char-every-64k?forum=ncl //workbook.Write(Response.OutputStream); cannot be used //root cause: Response.OutputStream will insert unnecessary byte into the response bytes. response.Flush(); response.End(); } /// <summary> /// 导出数据为Excel文件 /// </summary> /// <param name="items">数据源</param> /// <param name="nameFields">列对应的名称</param> public static void HandleItems(IEnumerable<dynamic> items, Dictionary<string, string> nameFields) { } } }
DonnotRain/NoRainWeb
Code/NoRain.Toolkits/Export/XMLOutputTool.cs
C#
gpl-2.0
5,480
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Reflection; using HazTech.Json.Utilities; using System.Globalization; namespace HazTech.Json.Serialization { /// <summary> /// Get and set values for a <see cref="MemberInfo"/> using reflection. /// </summary> public class ReflectionValueProvider : IValueProvider { private readonly MemberInfo _memberInfo; /// <summary> /// Initializes a new instance of the <see cref="ReflectionValueProvider"/> class. /// </summary> /// <param name="memberInfo">The member info.</param> public ReflectionValueProvider(MemberInfo memberInfo) { ValidationUtils.ArgumentNotNull(memberInfo, "memberInfo"); _memberInfo = memberInfo; } /// <summary> /// Sets the value. /// </summary> /// <param name="target">The target to set the value on.</param> /// <param name="value">The value to set on the target.</param> public void SetValue(object target, object value) { try { ReflectionUtils.SetMemberValue(_memberInfo, target, value); } catch (Exception ex) { throw new JsonSerializationException("Error setting value to '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex); } } /// <summary> /// Gets the value. /// </summary> /// <param name="target">The target to get the value from.</param> /// <returns>The value.</returns> public object GetValue(object target) { try { return ReflectionUtils.GetMemberValue(_memberInfo, target); } catch (Exception ex) { throw new JsonSerializationException("Error getting value from '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex); } } } }
marhazk/HazTechClass
AeraClass/Newtonsoft.Json/Serialization/ReflectionValueProvider.cs
C#
gpl-2.0
3,187
// ********************************************************************** // // Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** #include <Ice/Ice.h> #include <ThroughputI.h> using namespace std; class ThroughputServer : public Ice::Application { public: virtual int run(int, char*[]); }; int main(int argc, char* argv[]) { ThroughputServer app; return app.main(argc, argv, "config.server"); } int ThroughputServer::run(int argc, char*[]) { if(argc > 1) { cerr << appName() << ": too many arguments" << endl; return EXIT_FAILURE; } Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Throughput"); Demo::ThroughputPtr servant = new ThroughputI; adapter->add(servant, communicator()->stringToIdentity("throughput")); adapter->activate(); communicator()->waitForShutdown(); return EXIT_SUCCESS; }
dayongxie/zeroc-ice-androidndk
cpp/demo/Ice/throughput/Server.cpp
C++
gpl-2.0
1,094
#include "locked_queue.h"
antivo/Cluster-Manager
Cluster Manager/locked/locked_queue.cpp
C++
gpl-2.0
25
<?php // Just some basics. $per_page_limit = 20; // get all forms $forms = Caldera_Forms::get_forms(); $forms = apply_filters( 'caldera_forms_admin_forms', $forms ); $style_includes = get_option( '_caldera_forms_styleincludes' ); if(empty($style_includes)){ $style_includes = array( 'alert' => true, 'form' => true, 'grid' => true, ); update_option( '_caldera_forms_styleincludes', $style_includes); } // load fields //$field_types = apply_filters( 'caldera_forms_get_field_types', array() ); // create user modal buttons $modal_new_form = __('Create Form', 'caldera-forms').'|{"data-action" : "create_form", "data-active-class": "disabled", "data-load-class": "disabled", "data-callback": "new_form_redirect", "data-before" : "serialize_modal_form", "data-modal-autoclose" : "new_form" }'; ?><div class="caldera-editor-header"> <ul class="caldera-editor-header-nav"> <li class="caldera-editor-logo"> <span class="dashicons-cf-logo"></span> <?php _e('Caldera Forms', 'caldera-forms'); ?> </li> <li class="caldera-forms-version"> v<?php echo CFCORE_VER; ?> </li> <li class="caldera-forms-toolbar-item"> <a class="button ajax-trigger" data-request="start_new_form" data-modal-buttons='<?php echo $modal_new_form; ?>' data-modal-width="600" data-modal-height="400" data-load-class="none" data-modal="new_form" data-modal-title="<?php echo __('Create New Form', 'caldera-forms'); ?>" data-template="#new-form-tmpl"><?php echo __('New Form', 'caldera-forms'); ?></a> </li> <li class="caldera-forms-toolbar-item"> <a class="button ajax-trigger" data-request="start_new_form" data-modal-width="400" data-modal-height="192" data-modal-element="div" data-load-class="none" data-modal="new_form" data-template="#import-form-tmpl" data-modal-title="<?php echo __('Import Form', 'caldera-forms'); ?>" ><?php echo __('Import', 'caldera-forms'); ?></a> </li> <li class="caldera-forms-toolbar-item"> &nbsp;&nbsp; </li> <li class="caldera-forms-headtext"> <?php echo __('Front-end Style Includes', 'caldera-forms'); ?> </li> <li class="caldera-forms-toolbar-item"> <div class="toggle_option_preview"> <button type="button" title="<?php echo __('Includes Bootstrap 3 styles on the frontend for form alert notices', 'caldera-forms'); ?>" data-action="save_cf_setting" data-active-class="none" data-set="alert" data-callback="update_setting_toggle" class="ajax-trigger setting_toggle_alert button <?php if(!empty($style_includes['alert'])){ ?>button-primary<?php } ?>"><?php echo __('Alert' , 'caldera-forms'); ?></button> <button type="button" title="<?php echo __('Includes Bootstrap 3 styles on the frontend for form fields and buttons', 'caldera-forms'); ?>" data-action="save_cf_setting" data-active-class="none" data-set="form" data-callback="update_setting_toggle" class="ajax-trigger setting_toggle_form button <?php if(!empty($style_includes['form'])){ ?>button-primary<?php } ?>"><?php echo __('Form' , 'caldera-forms'); ?></button> <button type="button" title="<?php echo __('Includes Bootstrap 3 styles on the frontend for form grid layouts', 'caldera-forms'); ?>" data-action="save_cf_setting" data-active-class="none" data-set="grid" data-callback="update_setting_toggle" class="ajax-trigger setting_toggle_grid button <?php if(!empty($style_includes['grid'])){ ?>button-primary<?php } ?>"><?php echo __('Grid' , 'caldera-forms'); ?></button> </div> </li> <li class="caldera-forms-toolbar-item"> &nbsp; </li> </ul> </div> <div class="form-admin-page-wrap"> <div class="form-panel-wrap"> <?php if(!empty($forms)){ ?> <table class="widefat fixed"> <thead> <tr> <th><?php _e('Form', 'caldera-forms'); ?></th> <th style="width:5em; text-align:center;"><?php _e('Entries', 'caldera-forms'); ?></th> </tr> </thead> <tbody> <?php global $wpdb; $class = "alternate"; foreach($forms as $form_id=>$form){ if( !empty( $form['hidden'] ) ){ continue; } if(!empty($form['db_support'])){ $total = $wpdb->get_var($wpdb->prepare("SELECT COUNT(`id`) AS `total` FROM `" . $wpdb->prefix . "cf_form_entries` WHERE `form_id` = %s && `status` = 'active';", $form_id)); }else{ $total = __('Disabled', 'caldera-forms'); } ?> <tr id="form_row_<?php echo $form_id; ?>" class="<?php echo $class; ?> form_entry_row"> <td class="<?php if( !empty( $form['form_draft'] ) ) { echo 'draft-form'; }else{ echo 'active-form'; } ?>"> <?php echo $form['name']; ?> <?php if( !empty( $form['debug_mailer'] ) ) { ?> <span style="color: rgb(207, 0, 0);" class="description"><?php _e('Mailer Debug enabled.', 'caldera-forms') ;?></span> <?php } ?> <div class="row-actions"> <?php if( empty( $form['_external_form'] ) ){ ?><span class="edit"><a class="form-control" href="admin.php?page=caldera-forms&edit=<?php echo $form_id; ?>"><?php echo __('Edit'); ?></a> | </span> <span class="edit"><a class="form-control ajax-trigger" href="#entres" data-load-element="#form_row_<?php echo $form_id; ?>" data-action="toggle_form_state" data-active-element="#form_row_<?php echo $form_id; ?>" data-callback="set_form_state" data-form="<?php echo $form_id; ?>" ><?php if( !empty( $form['form_draft'] ) ) { echo __('Activate', 'caldera-forms'); }else{ echo __('Deactivate', 'caldera-forms'); } ?></a> | </span><?php } ?> <?php if(!empty($form['db_support'])){ ?><span class="edit"><a class="form-control form-entry-trigger ajax-trigger" href="#entres" data-action="browse_entries" data-target="#form-entries-viewer" data-form="<?php echo $form_id; ?>" data-template="#forms-list-alt-tmpl" data-active-element="#form_row_<?php echo $form_id; ?>" data-load-class="spinner" data-active-class="highlight" data-group="entry_nav" data-callback="setup_pagination" data-status="active" data-page="1" ><?php echo __('Entries', 'caldera-forms'); ?></a> | </span><?php } ?> <?php if( empty( $form['_external_form'] ) ){ ?><span class="export"><a class="form-control" href="admin.php?page=caldera-forms&export-form=<?php echo $form_id; ?>&cal_del=<?php echo wp_create_nonce( 'cf_del_frm' ); ?>"><?php echo __('Export', 'caldera-forms'); ?></a> | </span><?php } ?> <span><a class="ajax-trigger" href="#clone" data-request="start_new_form" data-modal-buttons='<?php echo $modal_new_form; ?>' data-clone="<?php echo $form_id; ?>" data-modal-width="600" data-modal-height="400" data-load-class="none" data-modal="new_form" data-modal-title="<?php echo __('Clone Form', 'caldera-forms'); ?>" data-template="#new-form-tmpl"><?php echo __('Clone', 'caldera-forms'); ?></a><?php if( empty( $form['_external_form'] ) ){ ?> | </span> <span class="trash form-delete"><a class="form-control" data-confirm="<?php echo __('This will delete this form permanently. Continue?', 'caldera-forms'); ?>" href="admin.php?page=caldera-forms&delete=<?php echo $form_id; ?>&cal_del=<?php echo wp_create_nonce( 'cf_del_frm' ); ?>"><?php echo __('Delete'); ?></a></span><?php } ?> </div> </td> <td style="width:4em; text-align:center;" class="entry_count_<?php echo $form_id; ?>"><?php echo $total; ?></td> </tr> <?php if($class == 'alternate'){ $class = ''; }else{ $class = "alternate"; } } ?></tbody> </table> <?php }else{ ?> <p><?php echo __('You don\'t have any forms.', 'caldera-forms'); ?></p> <?php } ?> </div> <div class="form-entries-wrap"> <?php include CFCORE_PATH . 'ui/entries_toolbar.php'; ?> <div id="form-entries-viewer"></div> </div> </div> <?php do_action('caldera_forms_admin_templates'); ?> <script type="text/javascript"> function set_form_state( obj ){ if( true === obj.data.success ){ var row = jQuery('#form_row_' + obj.data.data.ID + '>td'); row.first().attr('class', obj.data.data.state ); obj.params.trigger.text( obj.data.data.label ); } } function new_form_redirect(obj){ if(typeof obj.data === 'string'){ window.location = 'admin.php?page=caldera-forms&edit=' + obj.data; }else{ alert(obj.data.error); } } // profile form saver function serialize_modal_form(el){ var clicked = jQuery(el), data = jQuery('#new_form_baldrickModal'), name = data.find('.new-form-name'); //verify name is set if(name.val().length < 1){ alert("<?php echo __('An form name is required', 'caldera-forms'); ?>"); name.focus().addClass('has-error'); return false; } clicked.data('data', data.serialize()); return true; } function update_setting_toggle(obj){ for( var k in obj.data){ if(obj.data[k] === true){ jQuery('.setting_toggle_' + k).addClass('button-primary'); }else{ jQuery('.setting_toggle_' + k).removeClass('button-primary'); } } //for() } function extend_fail_notice(el){ jQuery("#extend_cf_baldrickModalBody").html('<div class="alert error"><p><?php echo __('Looks like something is not working. Please try again a little later or post to the <a href="http://wordpress.org/support/plugin/caldera-forms" target="_blank">support forum</a>.', 'caldera-forms'); ?></p></div>'); } function start_new_form(obj){ if( obj.trigger.data('clone') ){ return {clone: obj.trigger.data('clone') }; } return {}; } </script> <?php include CFCORE_PATH . 'ui/entry_navigation.php'; do_action('caldera_forms_admin_footer'); ?>
janmolemans/wordpressdrugs
wp-content/plugins/caldera-forms/ui/admin.php
PHP
gpl-2.0
9,468
<?php /** * The Header for our theme. * * Displays all of the <head> section and everything up till <main id="main"> * * @package GeneratePress */ ?><!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <?php if ( ! function_exists( '_wp_render_title_tag' ) ) : ?> <title><?php wp_title( '|', true, 'right' ); ?></title> <?php endif; ?> <link rel="profile" href="http://gmpg.org/xfn/11"> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"> <?php wp_head(); ?> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> </head> <body <?php generate_body_schema();?> <?php body_class(); ?>> <?php do_action( 'generate_before_header' ); ?> <a class="screen-reader-text skip-link" href="#content" title="<?php esc_attr_e( 'Skip to content', 'generate' ); ?>"><?php _e( 'Skip to content', 'generate' ); ?></a> <header itemtype="http://schema.org/WPHeader" itemscope="itemscope" id="masthead" <?php generate_header_class(); ?>> <div <?php generate_inside_header_class(); ?>> <?php do_action( 'generate_before_header_content'); ?> <?php generate_header_items(); ?> <?php do_action( 'generate_after_header_content'); ?> </div><!-- .inside-header --> </header><!-- #masthead --> <?php do_action( 'generate_after_header' ); ?> <div id="page" class="hfeed site grid-container container grid-parent"> <div id="content" class="site-content"> <?php do_action('generate_inside_container'); ?>
geraldpasion/gsm
wp-content/themes/generatepress/header.php
PHP
gpl-2.0
1,701
<?php declare(strict_types=1); class CommentListTest extends ShimmiePHPUnitTestCase { public function setUp(): void { global $config; parent::setUp(); $config->set_int("comment_limit", 100); $this->log_out(); } public function tearDown(): void { global $config; $config->set_int("comment_limit", 10); parent::tearDown(); } public function testCommentsPage() { global $user; $this->log_in_as_user(); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx"); # a good comment send_event(new CommentPostingEvent($image_id, $user, "Test Comment ASDFASDF")); $this->get_page("post/view/$image_id"); $this->assert_text("ASDFASDF"); # dupe try { send_event(new CommentPostingEvent($image_id, $user, "Test Comment ASDFASDF")); } catch (CommentPostingException $e) { $this->assertStringContainsString("try and be more original", $e->getMessage()); } # empty comment try { send_event(new CommentPostingEvent($image_id, $user, "")); } catch (CommentPostingException $e) { $this->assertStringContainsString("Comments need text", $e->getMessage()); } # whitespace is still empty... try { send_event(new CommentPostingEvent($image_id, $user, " \t\r\n")); } catch (CommentPostingException $e) { $this->assertStringContainsString("Comments need text", $e->getMessage()); } # repetitive (aka. gzip gives >= 10x improvement) try { send_event(new CommentPostingEvent($image_id, $user, str_repeat("U", 5000))); } catch (CommentPostingException $e) { $this->assertStringContainsString("Comment too repetitive", $e->getMessage()); } # test UTF8 send_event(new CommentPostingEvent($image_id, $user, "Test Comment むちむち")); $this->get_page("post/view/$image_id"); $this->assert_text("むちむち"); # test that search by comment metadata works // $this->get_page("post/list/commented_by=test/1"); // $this->assert_title("Image $image_id: pbx"); // $this->get_page("post/list/comments=2/1"); // $this->assert_title("Image $image_id: pbx"); $this->log_out(); $this->get_page('comment/list'); $this->assert_title('Comments'); $this->assert_text('ASDFASDF'); $this->get_page('comment/list/2'); $this->assert_title('Comments'); $this->log_in_as_admin(); $this->delete_image($image_id); $this->log_out(); $this->get_page('comment/list'); $this->assert_title('Comments'); $this->assert_no_text('ASDFASDF'); } public function testSingleDel() { global $database, $user; $this->log_in_as_admin(); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx"); # make a comment send_event(new CommentPostingEvent($image_id, $user, "Test Comment ASDFASDF")); $this->get_page("post/view/$image_id"); $this->assert_text("ASDFASDF"); # delete a comment $comment_id = (int)$database->get_one("SELECT id FROM comments"); send_event(new CommentDeletionEvent($comment_id)); $this->get_page("post/view/$image_id"); $this->assert_no_text("ASDFASDF"); } }
shish/shimmie2
ext/comment/test.php
PHP
gpl-2.0
3,501
<?php namespace RandomRango\Bundle\MainBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction() { return $this->render('RandomRangoMainBundle:Default:index.html.twig'); } }
polypapps/RandomRango_Web
src/RandomRango/Bundle/MainBundle/Controller/DefaultController.php
PHP
gpl-2.0
291
package com.rideon.web.security; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.DefaultHttpClient; import org.springframework.web.client.RestTemplate; public class ClientAuthenticator { public ClientAuthenticator() { super(); } // API public static void setAuthentication(final RestTemplate restTemplate, final String username, final String password) { basicAuth(restTemplate, username, password); } private static void basicAuth(final RestTemplate restTemplate, final String username, final String password) { final HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory = ((HttpComponentsClientHttpRequestFactoryBasicAuth) restTemplate.getRequestFactory()); DefaultHttpClient httpClient = (DefaultHttpClient) requestFactory.getHttpClient(); CredentialsProvider prov = httpClient.getCredentialsProvider(); prov.setCredentials(requestFactory.getAuthScope(), new UsernamePasswordCredentials(username, password)); } }
vilasmaciel/rideon
rideon-client/src/main/java/com/rideon/web/security/ClientAuthenticator.java
Java
gpl-2.0
1,128
<?php namespace TYPO3\CMS\T3editor; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use TYPO3\CMS\Core\Utility\GeneralUtility; /** * Code completion for t3editor */ class CodeCompletion { /** * @var \TYPO3\CMS\Core\Http\AjaxRequestHandler */ protected $ajaxObj; /** * Default constructor */ public function __construct() { $GLOBALS['LANG']->includeLLFile('EXT:t3editor/Resources/Private/Language/locallang.xlf'); } /** * General processor for AJAX requests. * Called by AjaxRequestHandler * * @param ServerRequestInterface $request * @param ResponseInterface $response * @return ResponseInterface */ public function processAjaxRequest(ServerRequestInterface $request, ResponseInterface $response) { $pageId = (int)(isset($request->getParsedBody()['pageId']) ? $request->getParsedBody()['pageId'] : $request->getQueryParams()['pageId']); return $this->loadTemplates($pageId); } /** * Loads all templates up to a given page id (walking the rootline) and * cleans parts that are not required for the t3editor codecompletion. * * @param int $pageId ID of the page * @return ResponseInterface */ protected function loadTemplates($pageId) { /** @var \TYPO3\CMS\Core\Http\Response $response */ $response = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Http\Response::class); // Check whether access is granted (only admin have access to sys_template records): if ($GLOBALS['BE_USER']->isAdmin()) { // Check whether there is a pageId given: if ($pageId) { $response->getBody()->write(json_encode($this->getMergedTemplates($pageId))); } else { $response->getBody()->write($GLOBALS['LANG']->getLL('pageIDInteger')); $response = $response->withStatus(500); } } else { $response->getBody()->write($GLOBALS['LANG']->getLL('noPermission')); $response = $response->withStatus(500); } return $response; } /** * Gets merged templates by walking the rootline to a given page id. * * @todo oliver@typo3.org: Refactor this method and comment what's going on there * @param int $pageId * @param int $templateId * @return array Setup part of merged template records */ protected function getMergedTemplates($pageId, $templateId = 0) { /** @var $tsParser \TYPO3\CMS\Core\TypoScript\ExtendedTemplateService */ $tsParser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\ExtendedTemplateService::class); $tsParser->init(); // Gets the rootLine $page = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Page\PageRepository::class); $rootLine = $page->getRootLine($pageId); // This generates the constants/config + hierarchy info for the template. $tsParser->runThroughTemplates($rootLine); // ts-setup & ts-constants of the currently edited template should not be included // therefor we have to delete the last template from the stack array_pop($tsParser->config); array_pop($tsParser->constants); $tsParser->linkObjects = true; $tsParser->ext_regLinenumbers = false; $tsParser->generateConfig(); $result = $this->treeWalkCleanup($tsParser->setup); return $result; } /** * Walks through a tree of TypoScript configuration an cleans it up. * * @TODO oliver@typo3.org: Define and comment why this is necessary and exactly happens below * @param array $treeBranch TypoScript configuration or sub branch of it * @return array Cleaned TypoScript branch */ private function treeWalkCleanup(array $treeBranch) { $cleanedTreeBranch = array(); foreach ($treeBranch as $key => $value) { $dotCount = substr_count($key, '.'); //type definition or value-assignment if ($dotCount == 0) { if ($value != '') { if (strlen($value) > 20) { $value = substr($value, 0, 20); } if (!isset($cleanedTreeBranch[$key])) { $cleanedTreeBranch[$key] = array(); } $cleanedTreeBranch[$key]['v'] = $value; } } elseif ($dotCount == 1) { // subtree (definition of properties) $subBranch = $this->treeWalkCleanup($value); if ($subBranch) { $key = str_replace('.', '', $key); if (!isset($cleanedTreeBranch[$key])) { $cleanedTreeBranch[$key] = array(); } $cleanedTreeBranch[$key]['c'] = $subBranch; } } } return $cleanedTreeBranch; } }
michaelklapper/TYPO3.CMS
typo3/sysext/t3editor/Classes/CodeCompletion.php
PHP
gpl-2.0
5,509
# -*- encoding: utf-8 -*- try: from httplib import HTTPSConnection from urlparse import urlparse except ImportError: from http.client import HTTPSConnection from urllib.parse import urlparse from json import dumps, loads from django.conf import settings class GCMError(Exception): pass def send(user, message, **kwargs): """ Site: https://developers.google.com API: https://developers.google.com/cloud-messaging/ Desc: Android notifications """ headers = { "Content-type": "application/json", "Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY) } hook_url = 'https://android.googleapis.com/gcm/send' data = { "registration_ids": [user], "data": { "title": kwargs.pop("event"), 'message': message, } } data['data'].update(kwargs) up = urlparse(hook_url) http = HTTPSConnection(up.netloc) http.request( "POST", up.path, headers=headers, body=dumps(data)) response = http.getresponse() if response.status != 200: raise GCMError(response.reason) body = response.read() if loads(body).get("failure") > 0: raise GCMError(repr(body)) return True
LPgenerator/django-db-mailer
dbmail/providers/google/android.py
Python
gpl-2.0
1,265
<?php /*************************************************************** * Copyright notice * * (c) 2011 Adrien LUCAS (adrien@oblady.fr) * All rights reserved * * This script is part of the TYPO3 project. The Typo3 project 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. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * * This script 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 copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ class tx_obladydebug_Reporting_SystemeLog extends tx_obladydebug_Reporting_Base{ public function report($error, $index, $showSource){ $rendering = new tx_obladydebug_Rendering_PlainText; @error_log($this->classicRendering($error, $rendering), SYSTEM_LOG); } public function finish(){} }
Oblady/oblady-debug
oblady_debug/Classes/Reporting/SystemeLog.php
PHP
gpl-2.0
1,267
#ifndef COIN_SBPIMPLPTR_HPP #define COIN_SBPIMPLPTR_HPP /**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) 1998-2008 by Kongsberg SIM. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg SIM about acquiring * a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg SIM, Postboks 1283, Pirsenteret, 7462 Trondheim, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ #ifndef COIN_SBPIMPLPTR_H #error do not include Inventor/tools/SbPimplPtr.hpp directly, use Inventor/tools/SbPimplPtr.h #endif // !COIN_SBPIMPLPTR_H /* ********************************************************************** */ template <typename T> SbPimplPtr<T>::SbPimplPtr(void) : ptr(NULL) { this->set(this->getNew()); } template <typename T> SbPimplPtr<T>::SbPimplPtr(T * initial) { this->ptr = initial; } template <typename T> SbPimplPtr<T>::SbPimplPtr(const SbPimplPtr<T> & copy) { *this = copy; } template <typename T> SbPimplPtr<T>::~SbPimplPtr(void) { this->set(NULL); } template <typename T> void SbPimplPtr<T>::set(T * value) { if (this->ptr) { delete this->ptr; } this->ptr = value; } template <typename T> T & SbPimplPtr<T>::get(void) const { return *(this->ptr); } template <typename T> T * SbPimplPtr<T>::getNew(void) const { return new T; } template <typename T> SbPimplPtr<T> & SbPimplPtr<T>::operator = (const SbPimplPtr<T> & copy) { this->get() = copy.get(); return *this; } template <typename T> SbBool SbPimplPtr<T>::operator == (const SbPimplPtr<T> & rhs) const { return this->get() == rhs.get(); } template <typename T> SbBool SbPimplPtr<T>::operator != (const SbPimplPtr<T> & rhs) const { return !(*this == rhs); } template <typename T> const T * SbPimplPtr<T>::operator -> (void) const { return &(this->get()); } template <typename T> T * SbPimplPtr<T>::operator -> (void) { return &(this->get()); } /* ********************************************************************** */ #endif // !COIN_SBPIMPLPTR_HPP
erik132/MolekelCUDA
deps/include/Inventor/tools/SbPimplPtr.hpp
C++
gpl-2.0
2,699
#include "StdInc.h" #include <ShellAPI.h> unsigned int _gameFlags; typedef struct { const wchar_t* argument; unsigned int flag; } flagDef_t; flagDef_t flags[] = { { L"offline", GAME_FLAG_OFFLINE }, { L"console", GAME_FLAG_CONSOLE }, { 0, 0 } }; void DetermineGameFlags() { int numArgs; LPCWSTR commandLine = GetCommandLineW(); LPWSTR* argv = CommandLineToArgvW(commandLine, &numArgs); for (int i = 0; i < numArgs; i++) { if (argv[i][0] != L'-') continue; for (wchar_t* c = argv[i]; *c != L'\0'; c++) { if (*c != L'-') { for (flagDef_t* flag = flags; flag->argument; flag++) { if (!wcscmp(c, flag->argument)) { _gameFlags |= flag->flag; break; } } break; } } } }
Sofakante/iw4m-lan
steam_api/Flags.cpp
C++
gpl-2.0
740
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebMvc.App.Views.Default.Common.Public { public partial class Footer : System.Web.UI.UserControl { public App.Common.UserControl.Footer FooterViewBag { get; set; } protected void Page_Load(object sender, EventArgs e) { } } }
xiaolu6t6t/NFinal
WebMvc/App/Views/Default/Common/Public/Footer.ascx.cs
C#
gpl-2.0
422
<?php class UpdateCartAction extends Action{ public function execute() { $quantities = getParam('ProductQuantity'); $cart = new Cart(); foreach($quantities as $productId => $quantities){ if($quantities > 0){ $cart->updateQuantity($productId, $quantities); } } $this->getController()->redirect('view_cart.php'); } } ?>
viktortod/magtools-cart
html/modules/store/action/UpdateCartAction.php
PHP
gpl-2.0
409
<?php /* * FileCtrl.class.php -- file system control * * Copyright 2011 World Three Technologies, Inc. * All Rights Reserved. * * 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 * * Written by Yaxing Chen <Yaxing@masxaro.com> * */ class FileCtrl{ } ?>
World-Three-Technologies/Masxaro-Prototype
proj/php/class/control/FileCtrl.class.php
PHP
gpl-2.0
949
/* * Copyright 2006-2020 The MZmine Development Team * * This file is part of MZmine. * * MZmine 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. * * MZmine 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 MZmine; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package io.github.mzmine.parameters.parametertypes.ranges; import java.text.NumberFormat; import java.util.Collection; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.google.common.collect.Range; import io.github.mzmine.parameters.UserParameter; public class DoubleRangeParameter implements UserParameter<Range<Double>, DoubleRangeComponent> { private final String name, description; protected final boolean valueRequired; private final boolean nonEmptyRequired; private NumberFormat format; private Range<Double> value; private Range<Double> maxAllowedRange; public DoubleRangeParameter(String name, String description, NumberFormat format) { this(name, description, format, true, false, null); } public DoubleRangeParameter(String name, String description, NumberFormat format, Range<Double> defaultValue) { this(name, description, format, true, false, defaultValue); } public DoubleRangeParameter(String name, String description, NumberFormat format, boolean valueRequired, Range<Double> defaultValue) { this(name, description, format, valueRequired, false, defaultValue); } public DoubleRangeParameter(String name, String description, NumberFormat format, boolean valueRequired, boolean nonEmptyRequired, Range<Double> defaultValue) { this(name, description, format, valueRequired, nonEmptyRequired, defaultValue, null); } public DoubleRangeParameter(String name, String description, NumberFormat format, boolean valueRequired, boolean nonEmptyRequired, Range<Double> defaultValue, Range<Double> maxAllowedRange) { this.name = name; this.description = description; this.format = format; this.valueRequired = valueRequired; this.nonEmptyRequired = nonEmptyRequired; this.value = defaultValue; this.maxAllowedRange = maxAllowedRange; } /** * @see io.github.mzmine.data.Parameter#getName() */ @Override public String getName() { return name; } /** * @see io.github.mzmine.data.Parameter#getDescription() */ @Override public String getDescription() { return description; } public boolean isValueRequired() { return valueRequired; } @Override public DoubleRangeComponent createEditingComponent() { return new DoubleRangeComponent(format); } public Range<Double> getValue() { return value; } @Override public void setValue(Range<Double> value) { this.value = value; } @Override public DoubleRangeParameter cloneParameter() { DoubleRangeParameter copy = new DoubleRangeParameter(name, description, format); copy.setValue(this.getValue()); return copy; } @Override public void setValueFromComponent(DoubleRangeComponent component) { value = component.getValue(); } @Override public void setValueToComponent(DoubleRangeComponent component, Range<Double> newValue) { component.setValue(newValue); } @Override public void loadValueFromXML(Element xmlElement) { NodeList minNodes = xmlElement.getElementsByTagName("min"); if (minNodes.getLength() != 1) return; NodeList maxNodes = xmlElement.getElementsByTagName("max"); if (maxNodes.getLength() != 1) return; String minText = minNodes.item(0).getTextContent(); String maxText = maxNodes.item(0).getTextContent(); double min = Double.valueOf(minText); double max = Double.valueOf(maxText); value = Range.closed(min, max); } @Override public void saveValueToXML(Element xmlElement) { if (value == null) return; Document parentDocument = xmlElement.getOwnerDocument(); Element newElement = parentDocument.createElement("min"); newElement.setTextContent(String.valueOf(value.lowerEndpoint())); xmlElement.appendChild(newElement); newElement = parentDocument.createElement("max"); newElement.setTextContent(String.valueOf(value.upperEndpoint())); xmlElement.appendChild(newElement); } @Override public boolean checkValue(Collection<String> errorMessages) { if (valueRequired && (value == null)) { errorMessages.add(name + " is not set properly"); return false; } if (value != null) { if (!nonEmptyRequired && value.lowerEndpoint() > value.upperEndpoint()) { errorMessages.add(name + " range maximum must be higher than minimum, or equal"); return false; } if (nonEmptyRequired && value.lowerEndpoint() >= value.upperEndpoint()) { errorMessages.add(name + " range maximum must be higher than minimum"); return false; } } if (value != null && maxAllowedRange != null) { if (maxAllowedRange.intersection(value) != value) { errorMessages.add(name + " must be within " + maxAllowedRange.toString()); return false; } } return true; } }
tomas-pluskal/mzmine3
src/main/java/io/github/mzmine/parameters/parametertypes/ranges/DoubleRangeParameter.java
Java
gpl-2.0
5,669
//---------------------------------------------------------------------------- #pragma hdrstop #include <stdio.h> #include <memory> #include "uCM.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma classgroup "Vcl.Controls.TControl" #pragma resource "*.dfm" TCM *CM; //--------------------------------------------------------------------------- __fastcall TCM::TCM(TComponent* Owner) : TDataModule(Owner) { FInstanceOwner = true; } __fastcall TCM::~TCM() { delete FSMClient; } TSMClient* TCM::GetSMClient(void) { if (FSMClient == NULL) FSMClient= new TSMClient(DSRestConnection1, FInstanceOwner); return FSMClient; };
cassioferrazzo/fila.cliente.desktop
uCM.cpp
C++
gpl-2.0
695
/* HexChat * Copyright (C) 1998-2010 Peter Zelezny. * Copyright (C) 2009-2013 Berke Viktor. * * 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 St, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef HEXCHAT_ASCII_HPP #define HEXCHAT_ASCII_HPP void ascii_open (void); #endif
leeter/hexchat
src/fe-gtk/ascii.hpp
C++
gpl-2.0
900
<?php /******************************************************************************* Copyright 2021 Whole Foods Co-op This file is part of CORE-POS. IT CORE 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. IT CORE 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 in the file license.txt along with IT CORE; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *********************************************************************************/ /** @class MercatoOrdersModel */ class MercatoNotesModel extends BasicModel { protected $name = "MercatoNotes"; protected $columns = array( 'mercatoNoteID' => array('type'=>'INT', 'primary_key'=>true, 'increment'=>true), 'name' => array('type'=>'VARCHAR(255)', 'index'=>true), 'modified' => array('type'=>'DATETIME'), 'note' => array('type'=>'TEXT'), ); }
CORE-POS/IS4C
fannie/modules/plugins2.0/Mercato/models/MercatoNotesModel.php
PHP
gpl-2.0
1,374
/* * RapidMiner * * Copyright (C) 2001-2008 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * 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 com.rapidminer.gui.tools; import java.awt.Component; import java.awt.Dialog; import java.awt.Frame; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * Some utils for the creation of a modal progress monitor dialog. * * @author Santhosh Kumar, Ingo Mierswa * @version $Id: ProgressUtils.java,v 1.3 2008/05/09 19:22:59 ingomierswa Exp $ */ public class ProgressUtils { static class MonitorListener implements ChangeListener, ActionListener { private ProgressMonitor monitor; private Window owner; private Timer timer; private boolean modal; public MonitorListener(Window owner, ProgressMonitor monitor, boolean modal) { this.owner = owner; this.monitor = monitor; this.modal = modal; } public void stateChanged(ChangeEvent ce) { ProgressMonitor monitor = (ProgressMonitor) ce.getSource(); if (monitor.getCurrent() != monitor.getTotal()) { if (timer == null) { timer = new Timer(monitor.getWaitingTime(), this); timer.setRepeats(false); timer.start(); } } else { if (timer != null && timer.isRunning()) timer.stop(); monitor.removeChangeListener(this); } } public void actionPerformed(ActionEvent e) { monitor.removeChangeListener(this); ProgressDialog dlg = owner instanceof Frame ? new ProgressDialog((Frame) owner, monitor, modal) : new ProgressDialog((Dialog) owner, monitor, modal); dlg.pack(); dlg.setLocationRelativeTo(null); dlg.setVisible(true); } } /** Create a new (modal) progress monitor dialog. Please note the the value for total (the maximum * number of possible steps) is greater then 0 even for indeterminate progresses. The value * of waitingTime is used before the dialog is actually created and shown. */ public static ProgressMonitor createModalProgressMonitor(Component owner, int total, boolean indeterminate, int waitingTimeBeforeDialogAppears, boolean modal) { ProgressMonitor monitor = new ProgressMonitor(total, indeterminate, waitingTimeBeforeDialogAppears); Window window = owner instanceof Window ? (Window) owner : SwingUtilities.getWindowAncestor(owner); monitor.addChangeListener(new MonitorListener(window, monitor, modal)); return monitor; } }
ntj/ComplexRapidMiner
src/com/rapidminer/gui/tools/ProgressUtils.java
Java
gpl-2.0
3,354
#include <filezilla.h> #include "directorycache.h" #include "list.h" enum listStates { list_init = 0, list_waitresolve, list_waitlock, list_list }; int CStorjListOpData::Send() { LogMessage(MessageType::Debug_Verbose, L"CStorjListOpData::Send() in state %d", opState); switch (opState) { case list_init: if (!subDir_.empty()) { LogMessage(MessageType::Error, _("Invalid path")); return FZ_REPLY_ERROR; } if (path_.empty()) { path_ = CServerPath(L"/"); } currentPath_ = path_; if (!currentServer_) { LogMessage(MessageType::Debug_Warning, L"CStorjControlSocket::List called with m_pCurrenServer == 0"); return FZ_REPLY_INTERNALERROR; } if (currentPath_.GetType() != ServerType::UNIX) { LogMessage(MessageType::Debug_Warning, L"CStorControlSocket::List called with incompatible server type %d in path", currentPath_.GetType()); return FZ_REPLY_INTERNALERROR; } opState = list_waitresolve; controlSocket_.Resolve(path_, std::wstring(), bucket_); return FZ_REPLY_CONTINUE; case list_waitlock: if (!holdsLock_) { LogMessage(MessageType::Debug_Warning, L"Not holding the lock as expected"); return FZ_REPLY_INTERNALERROR; } { // Check if we can use already existing listing CDirectoryListing listing; bool is_outdated = false; bool found = engine_.GetDirectoryCache().Lookup(listing, currentServer_, path_, false, is_outdated); if (found && !is_outdated && listing.m_firstListTime >= time_before_locking_) { controlSocket_.SendDirectoryListingNotification(listing.path, topLevel_, false); return FZ_REPLY_OK; } } opState = list_list; return FZ_REPLY_CONTINUE; case list_list: if (bucket_.empty()) { return controlSocket_.SendCommand(L"list-buckets"); } else { std::wstring path = path_.GetPath(); auto pos = path.find('/', 1); if (pos == std::string::npos) { path.clear(); } else { path = controlSocket_.QuoteFilename(path.substr(pos + 1) + L"/"); } return controlSocket_.SendCommand(L"list " + bucket_ + L" " + path); } } LogMessage(MessageType::Debug_Warning, L"Unknown opState in CStorjListOpData::ListSend()"); return FZ_REPLY_INTERNALERROR; } int CStorjListOpData::ParseResponse() { LogMessage(MessageType::Debug_Verbose, L"CStorjListOpData::ParseResponse() in state %d", opState); if (opState == list_list) { if (controlSocket_.result_ != FZ_REPLY_OK) { return controlSocket_.result_; } directoryListing_.path = path_; directoryListing_.m_firstListTime = fz::monotonic_clock::now(); engine_.GetDirectoryCache().Store(directoryListing_, currentServer_); controlSocket_.SendDirectoryListingNotification(directoryListing_.path, topLevel_, false); currentPath_ = path_; return FZ_REPLY_OK; } LogMessage(MessageType::Debug_Warning, L"ListParseResponse called at inproper time: %d", opState); return FZ_REPLY_INTERNALERROR; } int CStorjListOpData::SubcommandResult(int prevResult, COpData const&) { LogMessage(MessageType::Debug_Verbose, L"CStorjListOpData::SubcommandResult() in state %d", opState); if (prevResult != FZ_REPLY_OK) { return prevResult; } switch (opState) { case list_waitresolve: opState = list_waitlock; if (!controlSocket_.TryLockCache(CStorjControlSocket::lock_list, path_)) { time_before_locking_ = fz::monotonic_clock::now(); return FZ_REPLY_WOULDBLOCK; } opState = list_list; return FZ_REPLY_CONTINUE; } LogMessage(MessageType::Debug_Warning, L"Unknown opState in CStorjListOpData::SubcommandResult()"); return FZ_REPLY_INTERNALERROR; } int CStorjListOpData::ParseEntry(std::wstring && name, std::wstring const& size, std::wstring && id, std::wstring const& created) { if (opState != list_list) { LogMessage(MessageType::Debug_Warning, L"ListParseResponse called at inproper time: %d", opState); return FZ_REPLY_INTERNALERROR; } if (name == L".") { pathId_ = id; return FZ_REPLY_WOULDBLOCK; } CDirentry entry; entry.name = name; entry.ownerGroup.get() = id; if (bucket_.empty()) { entry.flags = CDirentry::flag_dir; } else { if (!entry.name.empty() && entry.name.back() == '/') { entry.flags = CDirentry::flag_dir; entry.name.pop_back(); } else { entry.flags = 0; } } if (entry.is_dir()) { entry.size = -1; } else { entry.size = fz::to_integral<int64_t>(size, -1); } entry.time.set(created, fz::datetime::utc); if (!entry.name.empty()) { directoryListing_.Append(std::move(entry)); } return FZ_REPLY_WOULDBLOCK; }
madnight/filezilla
src/engine/storj/list.cpp
C++
gpl-2.0
4,511
<?php include(HTML_DIR . 'overall/header.php'); ?> <body> <section class="engine"><a rel="nofollow" href="#"><?php echo APP_TITLE ?></a></section> <?php include(HTML_DIR . '/overall/topnav.php'); ?> <section class="mbr-section mbr-after-navbar"> <div class="mbr-section__container container mbr-section__container--isolated"> <?php if(isset($_GET['success'])) { echo '<div class="alert alert-dismissible alert-success"> <strong>Completado!</strong> el producto ha sido subido</div>'; } if(isset($_GET['error'])) { if($_GET['error'] == 1) { echo '<div class="alert alert-dismissible alert-danger"> <strong>Error!</strong></strong> todos los campos deben estar llenos. </div>'; } else { echo '<div class="alert alert-dismissible alert-danger"> <strong>Error!</strong></strong> debe existir una categoría para asociar al foro. </div>'; } } ?> <div class="row container"> <div class="pull-right"> <div class="mbr-navbar__column"><ul class="mbr-navbar__items mbr-navbar__items--right mbr-buttons mbr-buttons--freeze mbr-buttons--right btn-inverse mbr-buttons--active"><li class="mbr-navbar__item"> <a class="mbr-buttons__btn btn btn-danger " href="?view=productos">Gestionar Productos</a> </li></ul></div> <div class="mbr-navbar__column"><ul class="mbr-navbar__items mbr-navbar__items--right mbr-buttons mbr-buttons--freeze mbr-buttons--right btn-inverse mbr-buttons--active"><li class="mbr-navbar__item"> <a class="mbr-buttons__btn btn btn-danger active" href="?view=productos&mode=add">Subir Producto</a> </li></ul></div> </div> <ol class="breadcrumb"> <li><a href="?view=index"><i class="fa fa-comments"></i> Productos</a></li> </ol> </div> <div class="row categorias_con_foros"> <div class="col-sm-12"> <div class="row titulo_categoria">Subir un producto</div> <div class="row cajas"> <div class="col-md-12"> <form class="form-horizontal" action="?view=productos&mode=add" method="POST" enctype="multipart/form-data"> <fieldset> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Tipo de celular</label> <div class="col-lg-10"> <script> $(document).ready(function(){ $('#marca').change(function() { var id=$('#marca').val(); $('#modelo').load('?view=datos&mode=combo&id='+id); }); }); </script> <select class="form-control" name='marca' id='marca'> <?php if(false != $_tipos) { foreach($_tipos as $id_tipo => $array_tipo) { echo '<option value="'.$id_tipo.'">'.$_tipos[$id_tipo]['DES_TIPO'].'</option>'; } }else{ echo '<option value="0">No existen marcas</option>'; } ?> </select> </div> </div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Modelo</label> <div class="col-lg-10"> <select class='form-control' name='modelo' id='modelo'> <option value="OpModeloTodos">TODOS</option> </select> </div> </div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Precio</label> <div class="col-lg-10"> <input type="text" class="form-control" maxlength="250" name="precio" placeholder="Precio del celular"> </div> </div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Condicion</label> <div class="col-lg-10"> <select name="estado" class="form-control"> <option value="N">nuevo</option>'; <option value="U">usado</option> </select> </div> </div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Descripcion</label> <div class="col-lg-10"> <textarea class="form-control" name="descripcion" maxlength="100"></textarea> </div> </div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label"> Imagen</label> <div class="col-lg-10"> <input id="imagen" name="imagen" type="file" /> </div> </div> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2"> <button type="reset" class="btn btn-default">Resetear</button> <button type="submit" class="btn btn-primary">Crear</button> </div> </div> </fieldset> </form> </div> </div> </div> </div> </div> </section> <?php include(HTML_DIR . 'overall/footer.php'); ?> </body> </html>
sofiaqsy/Opensale
html/productos/add_producto.php
PHP
gpl-2.0
5,407
/*************************************************************************** * Copyright (C) 2011 by Christoph Thelen * * doc_bacardi@users.sourceforge.net * * * * 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 "muhkuh_split_testdescription.h" #include <wx/filename.h> #include <wx/log.h> #include <wx/txtstrm.h> #include <wx/wfstream.h> muhkuh_split_testdescription::muhkuh_split_testdescription(void) { } muhkuh_split_testdescription::~muhkuh_split_testdescription(void) { } bool muhkuh_split_testdescription::split(wxString strWorkingFolder) { bool fResult; wxFileName tFileName; wxString strXmlFullPath; wxXmlNode *ptNodeTestDescription; size_t sizSubTestIndex; wxXmlNode *ptNode; /* Set the working folder. */ m_strWorkingFolder = strWorkingFolder; /* Create the full path to the test description. */ tFileName.AssignDir(strWorkingFolder); tFileName.SetFullName("test_description.xml"); strXmlFullPath = tFileName.GetFullPath(); /* Does the test description exist and is it readable? */ if( tFileName.FileExists()!=true ) { wxLogError(_("The file %s does not exist!"), strXmlFullPath); fResult = false; } else if( tFileName.IsFileReadable()!=true ) { wxLogError(_("The file %s can not be read!"), strXmlFullPath); fResult = false; } else { /* Ok, we can access the file -> parse the XML tree. */ fResult = m_tXmlDoc.Load(strXmlFullPath); if( fResult!=true ) { /* FIXME: How can I get more information what went wrong here? */ wxLogError(_("Failed to load the XML document!")); } else { /* Search the TestDescription node. */ ptNodeTestDescription = search_node(m_tXmlDoc.GetRoot(), "TestDescription"); if( ptNodeTestDescription==NULL ) { wxLogError(_("Can not find the TestDescription node!")); fResult = false; } else { fResult = generate_description(ptNodeTestDescription); if( fResult==true ) { sizSubTestIndex = 0; /* Add the init code block. */ fResult = subtests_read_test(ptNodeTestDescription, sizSubTestIndex); if( fResult==true ) { ++sizSubTestIndex; /* Search all subtests. */ ptNode = ptNodeTestDescription->GetChildren(); while( ptNode!=NULL ) { if( ptNode->GetType()==wxXML_ELEMENT_NODE && ptNode->GetName()=="Test" ) { fResult = subtests_read_test(ptNode, sizSubTestIndex); if( fResult!=true ) { break; } ++sizSubTestIndex; } ptNode = ptNode->GetNext(); } } } } } } return fResult; } bool muhkuh_split_testdescription::generate_description(wxXmlNode *ptNodeTestDescription) { wxArrayString astrTestNames; wxArrayString astrTestVersions; wxArrayString astrTestDescription; wxXmlNode *ptNode; size_t sizSubTestIndex; wxString strArg; bool fResult; /* Get the name and version attribute. */ astrTestNames.Add(ptNodeTestDescription->GetAttribute("name", wxEmptyString)); astrTestVersions.Add(ptNodeTestDescription->GetAttribute("version", wxEmptyString)); /* Search all subtests. */ ptNode = ptNodeTestDescription->GetChildren(); while( ptNode!=NULL ) { if( ptNode->GetType()==wxXML_ELEMENT_NODE && ptNode->GetName()=="Test" ) { astrTestNames.Add(ptNode->GetAttribute("name", wxEmptyString)); astrTestVersions.Add(ptNode->GetAttribute("version", wxEmptyString)); } ptNode = ptNode->GetNext(); } /* Write all test names and versions to the file "test_description.lua". */ astrTestDescription.Add("_G.__MUHKUH_ALL_TESTS = {\n"); for(sizSubTestIndex=0; sizSubTestIndex<astrTestNames.GetCount(); ++sizSubTestIndex) { strArg.Printf("\t[%d] = { [\"name\"]=\"%s\", [\"version\"]=\"%s\" },\n", sizSubTestIndex, astrTestNames.Item(sizSubTestIndex), astrTestVersions.Item(sizSubTestIndex)); astrTestDescription.Add(strArg); } astrTestDescription.Add("}\n"); /* Write this to a file. */ fResult = write_textfile(MUHKUH_TESTDESCRIPTION_TYP_DESCRIPTION, 0, astrTestDescription); return fResult; } bool muhkuh_split_testdescription::subtests_read_test(wxXmlNode *ptParent, size_t sizSubTestIndex) { bool fResult; wxXmlNode *ptNode; wxString strData; wxArrayString astrParameter; wxString strParameterName; wxString strParameterValue; /* Expect failure. */ fResult = false; /* Search the code node. */ ptNode = search_node(ptParent->GetChildren(), "Code"); if( ptNode!=NULL ) { /* Get the node contents. */ strData = ptNode->GetNodeContent(); fResult = write_textfile(MUHKUH_TESTDESCRIPTION_TYP_CODE, sizSubTestIndex, strData); if( fResult==true ) { /* Collect all parameters. */ ptNode = ptParent->GetChildren(); while( ptNode!=NULL ) { if( ptNode->GetType()==wxXML_ELEMENT_NODE && ptNode->GetName()=="Parameter" ) { /* Get the name parameter. */ if( ptNode->GetAttribute("name", &strParameterName)==false ) { wxLogError(_("The parameter has no name attribute.")); fResult = false; break; } /* Get the value parameter. */ strParameterValue = ptNode->GetNodeContent(); /* Combine the name and value. */ strData.Printf("_G.__MUHKUH_TEST_PARAMETER[\"%s\"] = \"%s\"\n", strParameterName, strParameterValue); astrParameter.Add(strData); } ptNode = ptNode->GetNext(); } /* Write all parameters to a file. */ fResult = write_textfile(MUHKUH_TESTDESCRIPTION_TYP_PARAMETER, sizSubTestIndex, astrParameter); } } return fResult; } wxXmlNode *muhkuh_split_testdescription::search_node(wxXmlNode *ptNode, wxString strName) { while( ptNode!=NULL ) { if( ptNode->GetType()==wxXML_ELEMENT_NODE && ptNode->GetName()==strName ) { break; } ptNode = ptNode->GetNext(); } return ptNode; } wxString muhkuh_split_testdescription::get_lua_filename(MUHKUH_TESTDESCRIPTION_TYP_T tTyp, size_t sizSubTextIndex) { wxFileName tFileName; wxString strFileName; /* Construct the name and extension part of the filename. */ switch( tTyp ) { case MUHKUH_TESTDESCRIPTION_TYP_DESCRIPTION: strFileName = "test_description.lua"; break; case MUHKUH_TESTDESCRIPTION_TYP_CODE: strFileName.Printf("test_description_%d_code.lua", sizSubTextIndex); break; case MUHKUH_TESTDESCRIPTION_TYP_PARAMETER: strFileName.Printf("test_description_%d_par.lua", sizSubTextIndex); break; } /* Construct the complete path. */ tFileName.AssignDir(m_strWorkingFolder); tFileName.SetFullName(strFileName); return tFileName.GetFullPath(); } bool muhkuh_split_testdescription::write_textfile(MUHKUH_TESTDESCRIPTION_TYP_T tTyp, size_t sizSubTextIndex, wxString strContents) { bool fResult; wxString strFileName; wxFFileOutputStream *ptOutputStream; wxTextOutputStream *ptTextOutputStream; /* Create a new file. */ strFileName = get_lua_filename(tTyp, sizSubTextIndex); ptOutputStream = new wxFFileOutputStream(strFileName, "w"); if( ptOutputStream->IsOk()!=true ) { wxLogError("Failed to create new file %s!", strFileName); fResult = false; } else { /* Create the text output stream. */ ptTextOutputStream = new wxTextOutputStream(*ptOutputStream); /* Write the complete data to the file. */ ptTextOutputStream->WriteString(strContents); delete ptTextOutputStream; ptOutputStream->Close(); fResult = true; } delete ptOutputStream; return fResult; } bool muhkuh_split_testdescription::write_textfile(MUHKUH_TESTDESCRIPTION_TYP_T tTyp, size_t sizSubTextIndex, wxArrayString &astrContents) { bool fResult; wxString strFileName; wxFFileOutputStream *ptOutputStream; wxTextOutputStream *ptTextOutputStream; size_t sizStringCnt; size_t sizStringEnd; /* Create a new file. */ strFileName = get_lua_filename(tTyp, sizSubTextIndex); ptOutputStream = new wxFFileOutputStream(strFileName, "w"); if( ptOutputStream->IsOk()!=true ) { wxLogError("Failed to create new file %s!", strFileName); fResult = false; } else { /* Create the text output stream. */ ptTextOutputStream = new wxTextOutputStream(*ptOutputStream); /* Write the complete data to the file. */ sizStringCnt = 0; sizStringEnd = astrContents.GetCount(); while( sizStringCnt<sizStringEnd ) { ptTextOutputStream->WriteString(astrContents.Item(sizStringCnt)); ++sizStringCnt; } delete ptTextOutputStream; ptOutputStream->Close(); fResult = true; } delete ptOutputStream; return fResult; }
muhkuh-sys/org.muhkuh.tools-muhkuh_gui
application/muhkuh_split_testdescription.cpp
C++
gpl-2.0
9,641
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Eli # # Created: 06/04/2014 # Copyright: (c) Eli 2014 # Licence: <your licence> #------------------------------------------------------------------------------- def main(): pass if __name__ == '__main__': main() import sys #This script filters a data file by id's listed one per line in another file ids = open("C:/rnaseq/mirna_data/clusters/10rep_redo_deseq-edger/DEseq2_1cpm3redo_nopara2_logFCall.txt", "r") #Take header from ID file & initialize empty dict head_ids = ids.readline().strip("\n") idlist1 = {} #id_count = 0 #Make dict of ID's (key) & selected variables/annotations (values) for line in ids: name = line.strip('\n').split('\t')[0] #name = name[4:] #if len(name.split('-')) > 3: # name = '-'.join(name.split('-')[1:]) #arm = name.split('-')[-1] #name = '-'.join(['-'.join(name.split('-')[0:2]), arm]) name = name.strip('cin-') #print name #name = name[-5:] #values = '\t'.join(line.strip('\n').split('\t')[1:3]) values = '\t'.join(line.strip('\n').split('\t')[1:4]) #if "ENSCINP" in values: # values2 = values[7:] # values = "ENSCINT" + values2 #values = '\t'.join(line.strip('\n').split('\t')[2:]) #values = values[0:-3] if name in idlist1 and len(name) > 0: if values in idlist1[name]: continue else: idlist1[name].append(values) elif len(name) > 0: idlist1[name] = [values] #id_count+=1 #if id_count%1000==0: # print id_count ids.close #Debugging code below: #print 'idlist1:', len(idlist1) #sorted(idlist1) #print idlist1 idlist1 = ['miR-216'] data = open("C:/rnaseq/coexpression/mirna-mrna/logfc_pearson/1cpm3_5rpkm3_redo2_edger_logfcValues_pearson_targetscan_deseq2logfc_mirs2.txt", "r") #Output merged header & initialize retrieved list + row counter #sys.stdout.write("LogFC.consensus" + '\t' + data.readline()) #sys.stdout.write("LogFC.consensus" + '\t' + '\t'.join(data.readline().split('\t')[0:3]) + '\n') #sys.stdout.write(data.readline()) #data.readline() matched = 0 idlist2 = {} out = 0 #Match ID's between lists and return associated variables for line in data: #print line name = line.strip('\n').split('\t')[6] #print name #name = name.split('|')[3].split('.')[0] # for first ID from BLAST target #name = name[0:7] #if name[-1].isalpha(): # name = name[0:-1] #print name #variables = line.strip('\n').split('\t')[5,9,10] #idlist2[name] = line.split('\t')[1] descr = line.strip('\n').split('\t')[1] #if "," in descr: # descr = descr.split(',')[0] #name = line[1:20] # for trimmed encin gene name #kh = '.'.join(line.split('\t')[1].split(':')[1].split('.')[0:4]) #Loop through input dict ID's and search for "name" in associated variables #for item in idlist1: #Loop through keys (refseq) if name in idlist1: #match primary ID's #for item in idlist1[name].split(' '): sys.stdout.write('\t'.join(idlist1[0]) + '\t' + line) #EXCHANGE ID'S BUT KEEP REST OF LINE/DESCRIPTION # sys.stdout.write(descr + '\t' + '\t'.join(idlist1[name]) + '\n') #else: # sys.stdout.write(descr + '\t' + name + '\n') #print idlist1[name] #sys.stdout.write(line.strip('\n') + '\t' + '\t'.join(idlist1[name]) + '\n') #continue #matched +=1 else: sys.stdout.write(line) #if name in idlist1[item]: #Check for each ID in the name variable # idlist2[name] = variables # values = idlist1[item] # stop = 1 #while stop <= len(values): # if descr in idlist1[name]: # sys.stdout.write(line) # out+=1 #print out #Return items in matched list (idlist2) using associations from idlist1 #for mir in idlist1: # if mir in idlist2: # sys.stdout.write(mir + '\t' + '\t'.join(idlist2[mir]) + '\n') # for mrna in idlist1[mir]: # if mrna in idlist2: # sys.stdout.write(mrna+ '\t' + '\t'.join(idlist2[mrna]) + '\n') #if len(idlist1[name]) > 1: # for value in idlist1[name]: #Print all values on separate lines # sys.stdout.write(value + '\t' + line) #sys.stdout.write(descr + '\t' + value + '\t' + name + '\t' + '\t'.join(variables) + '\n') # sys.stdout.write(value + '\t' + '\t'.join(line.split('\t')[0:])) #sys.stdout.write(value + '\t' + '\t'.join(line.split('\t')[0:3]) + '\n') # out+=1 #else: # sys.stdout.write('\t'.join(idlist1[name]) + '\t' + line) #sys.stdout.write(descr + '\t' + ".\t".join(idlist1[name]) + '\t' + name + '\t' + '\t'.join(variables) + '\n') #print idlist1[name] # sys.stdout.write(('\t'.join(idlist1[name]) + '\t' + '\t'.join(line.split('\t')[0:]))) #sys.stdout.write(name + '\t' + '\t'.join(idlist1[name]) + '\t' + '\t'.join(line.split('\t')[2:])) # out+=1 #print matched, out #print gene #print idlist1[item] # sys.stdout.write(value + "\t" + name + '\t' + line)#'\t' + '\t'.join(line.split('\t')[2:])) # stop+=1 #continue #if name in idlist1: # if descr in idlist1[name]: # sys.stdout.write(line) # descr = idlist1[name] # sys.stdout.write('\t'.join(idlist1[name]) + '\t' + '\t'.join(line.split('\t')[2:])) #sys.stdout.write('\t'.join(line.split('\t')[0:2]) + '\t' + descr + '\n') #del idlist1[name] #else: # pass #sys.stdout.write(line + '\n') #if name in idlist2: # pass #else: #idlist2.append(name) #idlist1.remove(name) #print line #count+=1 #Code for checking remaining values in ID list #for item in idlist1: # print "bakow!" # sys.stdout.write(item + '\t' + idlist2[item] + '\t' + idlist1[item] + '\n') #else: # print line.split('\t')[0] #print len(idlist1), len(idlist2) #print len(idlist1)-len(idlist2) #print len(idlist1) #sorted(idlist2) #print idlist1 #for item in idlist2: # if item in idlist1: # idlist1.remove(item) #print 'idlist1-idlist2', len(idlist1) #for item in idlist1: # print item #cross check input and output lists #idlist3= [] #for thing in idlist1: # if thing in idlist2: # pass # else: # idlist3.append(thing) #print len(idlist3) #print len(idlist4) #idlist4 = [x for x in idlist1 if x not in idlist2]
ejspina/Gene_expression_tools
Python/FilterByID_dict_parse.py
Python
gpl-2.0
7,098
package org.mo.jfa.face.database.connector; import org.mo.web.core.container.AContainer; import org.mo.web.core.webform.IFormPage; import org.mo.web.protocol.context.IWebContext; public interface IConnectorAction { String catalog(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String list(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String sort(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String insert(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String update(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String delete(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); }
favedit/MoPlatform
mo-4-web/src/web-face/org/mo/jfa/face/database/connector/IConnectorAction.java
Java
gpl-2.0
890
<?php /* * * Swift Page Builder - Default Shortcodes * ------------------------------------------------ * Swift Framework * Copyright Swift Ideas 2016 - http://www.swiftideas.com * */ /* TEXT BLOCK ASSET ================================================== */ class SwiftPageBuilderShortcode_spb_text_block extends SwiftPageBuilderShortcode { public function content( $atts, $content = null ) { $title = $el_class = $width = $el_position = $inline_style = $form_content = $custom_css = $bk_image_global = ''; extract( shortcode_atts( array( 'title' => '', 'icon' => '', 'padding_vertical' => '0', 'padding_horizontal' => '0', 'animation' => '', 'animation_delay' => '', 'el_class' => '', 'el_position' => '', 'form_content' => '', 'width' => '1/2', 'custom_css' => '', 'bk_image_global' => '', ), $atts ) ); if ( $form_content != '' ){ $content = html_entity_decode($form_content); } $output = ''; $el_class = $this->getExtraClass( $el_class ); $width = spb_translateColumnWidthToSpan( $width ); $el_class .= ' spb_text_column'; if( $custom_css != "" ){ $inline_style .= $custom_css; $img_url = wp_get_attachment_image_src( $bk_image_global, 'full' ); if( isset( $img_url ) && $img_url[0] != "" ) { $inline_style .= 'background-image: url(' . $img_url[0] . ');'; } }else{ if ( $padding_vertical != "" ) { $inline_style .= 'padding-top:' . $padding_vertical . '%;padding-bottom:' . $padding_vertical . '%;'; } if ( $padding_horizontal != "" ) { $inline_style .= 'padding-left:' . $padding_horizontal . '%;padding-right:' . $padding_horizontal . '%;'; } } $icon_output = ""; if ( $icon ) { $icon_output = '<i class="' . $icon . '"></i>'; } if ( $animation != "" && $animation != "none" ) { $output .= "\n\t" . '<div class="spb_content_element sf-animation ' . $width . $el_class . '" data-animation="' . $animation . '" data-delay="' . $animation_delay . '">'; } else { $output .= "\n\t" . '<div class="spb_content_element ' . $width . $el_class . '">'; } $output .= "\n\t\t" . '<div class="spb-asset-content" style="' . $inline_style . '">'; if ( $icon_output != "" ) { $output .= ( $title != '' ) ? "\n\t\t\t" . '<div class="title-wrap"><h3 class="spb-heading spb-icon-heading"><span>' . $icon_output . '' . $title . '</span></h3></div>' : ''; } else { $output .= ( $title != '' ) ? "\n\t\t\t" . $this->spb_title( $title, 'spb-text-heading' ) : ''; } $output .= "\n\t\t\t" . do_shortcode( $content ); $output .= "\n\t\t" . '</div>'; $output .= "\n\t" . '</div> ' . $this->endBlockComment( $width ); $output = $this->startRow( $el_position ) . $output . $this->endRow( $el_position ); return $output; } } SPBMap::map( 'spb_text_block', array( "name" => __( "Text Block", 'swift-framework-plugin' ), "base" => "spb_text_block", "class" => "spb_tab_media", "icon" => "icon-text-block", "wrapper_class" => "clearfix", "controls" => "full", "params" => array( array( "type" => "textfield", "holder" => "div", "heading" => __( "Widget title", 'swift-framework-plugin' ), "param_name" => "title", "value" => "", "description" => __( "Heading text. Leave it empty if not needed.", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Title icon", 'swift-framework-plugin' ), "param_name" => "icon", "value" => "", "description" => __( "Icon to the left of the title text. This is the class name for the icon, e.g. fa-cloud", 'swift-framework-plugin' ) ), array( "type" => "textarea_html", "holder" => "div", "class" => "", "heading" => __( "Text", 'swift-framework-plugin' ), "param_name" => "content", "value" => '', //"value" => __("<p>This is a text block. Click the edit button to change this text.</p>", 'swift-framework-plugin'), "description" => __( "Enter your content.", 'swift-framework-plugin' ) ), array( "type" => "section_tab", "param_name" => "animation_options_tab", "heading" => __( "Animation", 'swift-framework-plugin' ), ), array( "type" => "dropdown", "heading" => __( "Intro Animation", 'swift-framework-plugin' ), "param_name" => "animation", "value" => spb_animations_list(), "description" => __( "Select an intro animation for the text block that will show it when it appears within the viewport.", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Animation Delay", 'swift-framework-plugin' ), "param_name" => "animation_delay", "value" => "0", "description" => __( "If you wish to add a delay to the animation, then you can set it here (ms).", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Data Form Content", 'swift-framework-plugin' ), "param_name" => "form_content", "value" => "", "description" => __( "This is a hidden field that is used to save the content when using forms inside the content.", 'swift-framework-plugin' ) ) ) ) ); /* BOXED CONTENT ASSET ================================================== */ class SwiftPageBuilderShortcode_spb_boxed_content extends SwiftPageBuilderShortcode { public function content( $atts, $content = null ) { $title = $type = $bg_style = $inline_style = $custom_bg_colour = $custom_text_colour = $padding_vertical = $padding_horizontal = $el_class = $width = $el_position = ''; extract( shortcode_atts( array( 'title' => '', 'type' => '', 'custom_bg_colour' => '', 'custom_text_colour' => '', 'box_link' => '', 'box_link_target' => '_self', 'padding_vertical' => '0', 'padding_horizontal' => '0', 'el_class' => '', 'el_position' => '', 'width' => '1/2' ), $atts ) ); $output = ''; $el_class = $this->getExtraClass( $el_class ); $width = spb_translateColumnWidthToSpan( $width ); if ( $custom_bg_colour != "" ) { $bg_style .= 'background: ' . $custom_bg_colour . '!important;'; } if ( $custom_text_colour != "" ) { $inline_style .= 'color: ' . $custom_text_colour . '!important;'; } if ( $padding_vertical != "" ) { $inline_style .= 'padding-top:' . $padding_vertical . '%;padding-bottom:' . $padding_vertical . '%;'; } if ( $padding_horizontal != "" ) { $inline_style .= 'padding-left:' . $padding_horizontal . '%;padding-right:' . $padding_horizontal . '%;'; } $output .= "\n\t" . '<div class="spb_content_element spb_box_content ' . $width . $el_class . '">'; $output .= ( $title != '' ) ? "\n\t\t\t" . $this->spb_title( $title, '' ) : ''; $output .= "\n\t" . '<div class="spb-bg-color-wrap ' . $type . '" style="' . $bg_style . '">'; $output .= "\n\t\t" . '<div class="spb-asset-content">'; if ( $box_link != "" ) { $output .= '<a href="' . $box_link . '" target="' . $box_link_target . '" class="box-link"></a>'; } $output .= "\n\t\t"; if ( $inline_style != "" ) { $output .= '<div class="box-content-wrap" style="' . $inline_style . '">' . do_shortcode( $content ) . '</div>'; } else { $output .= '<div class="box-content-wrap">' . do_shortcode( $content ) . '</div>'; } $output .= "\n\t\t" . '</div>'; $output .= "\n\t\t" . '</div>'; $output .= "\n\t" . '</div> ' . $this->endBlockComment( $width ); $output = $this->startRow( $el_position ) . $output . $this->endRow( $el_position ); return $output; } } $target_arr = array( __( "Same window", 'swift-framework-plugin' ) => "_self", __( "New window", 'swift-framework-plugin' ) => "_blank" ); SPBMap::map( 'spb_boxed_content', array( "name" => __( "Boxed Content", 'swift-framework-plugin' ), "base" => "spb_boxed_content", "class" => "spb_tab_media", "icon" => "icon-boxed-content", "wrapper_class" => "clearfix", "controls" => "full", "params" => array( array( "type" => "textfield", "holder" => "div", "heading" => __( "Widget title", 'swift-framework-plugin' ), "param_name" => "title", "value" => "", "description" => __( "Heading text. Leave it empty if not needed.", 'swift-framework-plugin' ) ), array( "type" => "textarea_html", "holder" => "div", "class" => "", "heading" => __( "Text", 'swift-framework-plugin' ), "param_name" => "content", "value" => __( "<p>This is a boxed content block. Click the edit button to edit this text.</p>", 'swift-framework-plugin' ), "description" => __( "Enter your content.", 'swift-framework-plugin' ) ), array( "type" => "dropdown", "heading" => __( "Box type", 'swift-framework-plugin' ), "param_name" => "type", "value" => array( __( 'Coloured', 'swift-framework-plugin' ) => "coloured", __( 'White with stroke', 'swift-framework-plugin' ) => "whitestroke" ), "description" => __( "Choose the surrounding box type for this content", 'swift-framework-plugin' ) ), array( "type" => "colorpicker", "heading" => __( "Background color", 'swift-framework-plugin' ), "param_name" => "custom_bg_colour", "value" => "", "description" => __( "Provide a background colour here. If blank, your colour customisaer settings will be used.", 'swift-framework-plugin' ) ), array( "type" => "colorpicker", "heading" => __( "Text colour", 'swift-framework-plugin' ), "param_name" => "custom_text_colour", "value" => "", "description" => __( "Provide a text colour here. If blank, your colour customisaer settings will be used.", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Overlay Link", 'swift-framework-plugin' ), "param_name" => "box_link", "value" => "", "description" => __( "Optionally provide a link here. This will overlay the boxed content and make the asset a whole clickable link.", 'swift-framework-plugin' ) ), array( "type" => "dropdown", "heading" => __( "Overlay Link Target", 'swift-framework-plugin' ), "param_name" => "box_link_target", "value" => $target_arr ), array( "type" => "uislider", "heading" => __( "Padding - Vertical", 'swift-framework-plugin' ), "param_name" => "padding_vertical", "value" => "0", "step" => "1", "min" => "0", "max" => "20", "description" => __( "Adjust the vertical padding for the text block (percentage).", 'swift-framework-plugin' ) ), array( "type" => "uislider", "heading" => __( "Padding - Horizontal", 'swift-framework-plugin' ), "param_name" => "padding_horizontal", "value" => "0", "step" => "1", "min" => "0", "max" => "20", "description" => __( "Adjust the horizontal padding for the text block (percentage).", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Extra class", 'swift-framework-plugin' ), "param_name" => "el_class", "value" => "", "description" => __( "If you wish to style this particular content element differently, then use this field to add a class name and then refer to it in your css file.", 'swift-framework-plugin' ) ) ) ) ); /* DIVIDER ASSET ================================================== */ class SwiftPageBuilderShortcode_spb_divider extends SwiftPageBuilderShortcode { protected function content( $atts, $content = null ) { $with_line = $fullwidth = $type = $width = $el_class = $text = ''; extract( shortcode_atts( array( 'with_line' => '', 'type' => '', 'heading_text' => '', 'top_margin' => '0px', 'bottom_margin' => '30px', 'fullwidth' => '', 'text' => '', 'width' => '1/1', 'el_class' => '', 'el_position' => '' ), $atts ) ); $width = spb_translateColumnWidthToSpan( $width ); $up_icon = apply_filters( 'sf_up_icon' , '<i class="ss-up"></i>' ); $style = "margin-top: " . $top_margin . "; margin-bottom: " . $bottom_margin . ";"; $output = ''; $output .= '<div class="divider-wrap ' . $width . '">'; if ( $type == "heading" ) { $output .= '<div class="spb_divider ' . $el_class . '" style="' . $style . '">'; $output .= '<h3 class="divider-heading">' . $heading_text . '</h3>'; $output .= '</div>' . $this->endBlockComment( 'divider' ) . "\n"; } else { $output .= '<div class="spb_divider ' . $type . ' spb_content_element ' . $el_class . '" style="' . $style . '">'; if ( $type == "go_to_top" ) { $output .= '<a class="animate-top" href="#">' . $text . '</a>'; } else if ( $type == "go_to_top_icon1" ) { $output .= '<a class="animate-top" href="#">' . $up_icon . '</a>'; } else if ( $type == "go_to_top_icon2" ) { $output .= '<a class="animate-top" href="#">' . $text . $up_icon . '</a>'; } $output .= '</div>' . $this->endBlockComment( 'divider' ) . "\n"; } $output .= '</div>'; if ( $fullwidth == "yes" && $width == "col-sm-12" ) { $output = $this->startRow( $el_position, '', true ) . $output . $this->endRow( $el_position, '', true ); } else { $output = $this->startRow( $el_position ) . $output . $this->endRow( $el_position ); } return $output; } } SPBMap::map( 'spb_divider', array( "name" => __( "Divider", 'swift-framework-plugin' ), "base" => "spb_divider", "class" => "spb_divider", 'icon' => 'icon-divider', "controls" => '', "params" => array( array( "type" => "dropdown", "heading" => __( "Divider type", 'swift-framework-plugin' ), "param_name" => "type", "value" => array( __( 'Standard', 'swift-framework-plugin' ) => "standard", __( 'Thin', 'swift-framework-plugin' ) => "thin", __( 'Dotted', 'swift-framework-plugin' ) => "dotted", __( 'Heading', 'swift-framework-plugin' ) => "heading", __( 'Go to top (text)', 'swift-framework-plugin' ) => "go_to_top", __( 'Go to top (Icon 1)', 'swift-framework-plugin' ) => "go_to_top_icon1", __( 'Go to top (Icon 2)', 'swift-framework-plugin' ) => "go_to_top_icon2" ), "description" => __( "Select divider type.", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Divider Heading Text", 'swift-framework-plugin' ), "param_name" => "heading_text", "value" => '', "description" => __( "The text for the the 'Heading' divider type.", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Go to top text", 'swift-framework-plugin' ), "param_name" => "text", "value" => __( "Go to top", 'swift-framework-plugin' ), "required" => array("blog_type", "or", "go_to_top,go_to_top_icon1,go_to_top_icon2"), "description" => __( "The text for the 'Go to top (text)' divider type.", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Top Margin", 'swift-framework-plugin' ), "param_name" => "top_margin", "value" => __( "0px", 'swift-framework-plugin' ), "description" => __( "Set the margin above the divider (include px).", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Bottom Margin", 'swift-framework-plugin' ), "param_name" => "bottom_margin", "value" => __( "30px", 'swift-framework-plugin' ), "description" => __( "Set the margin below the divider (include px).", 'swift-framework-plugin' ) ), array( "type" => "buttonset", "heading" => __( "Full width", 'swift-framework-plugin' ), "param_name" => "fullwidth", "value" => array( __( 'No', 'swift-framework-plugin' ) => "no", __( 'Yes', 'swift-framework-plugin' ) => "yes" ), "buttonset_on" => "yes", "description" => __( "Select yes if you'd like the divider to be full width (only to be used with no sidebars, and with Standard/Thin/Dotted divider types).", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Extra class", 'swift-framework-plugin' ), "param_name" => "el_class", "value" => "", "description" => __( "If you wish to style this particular content element differently, then use this field to add a class name and then refer to it in your css file.", 'swift-framework-plugin' ) ) ), "js_callback" => array( "init" => "spbTextSeparatorInitCallBack" ) ) ); /* BLANK SPACER ASSET ================================================== */ class SwiftPageBuilderShortcode_spb_blank_spacer extends SwiftPageBuilderShortcode { protected function content( $atts, $content = null ) { $height = $el_class = ''; extract( shortcode_atts( array( 'height' => '', 'width' => '', 'responsive_vis' => '', 'el_position' => '', 'el_class' => '', ), $atts ) ); $responsive_vis = str_replace( "_", " ", $responsive_vis ); $width = spb_translateColumnWidthToSpan( $width ); $el_class = $this->getExtraClass( $el_class ) . ' ' . $responsive_vis; $output = ''; $output .= '<div class="blank_spacer ' . $width . ' ' . $el_class . '" style="height:' . $height . ';">'; $output .= '</div>' . $this->endBlockComment( 'divider' ) . "\n"; $output = $this->startRow( $el_position ) . $output . $this->endRow( $el_position ); return $output; } } SPBMap::map( 'spb_blank_spacer', array( "name" => __( "Blank Spacer", 'swift-framework-plugin' ), "base" => "spb_blank_spacer", "class" => "spb_blank_spacer", 'icon' => 'icon-blank-spacer', "params" => array( array( "type" => "textfield", "heading" => __( "Height", 'swift-framework-plugin' ), "param_name" => "height", "value" => __( "30px", 'swift-framework-plugin' ), "description" => __( "The height of the spacer, in px (required).", 'swift-framework-plugin' ) ), array( "type" => "dropdown", "heading" => __( "Responsive Visiblity", 'swift-framework-plugin' ), "param_name" => "responsive_vis", "holder" => 'indicator', "value" => spb_responsive_vis_list(), "description" => __( "Set the responsive visiblity for the row, if you would only like it to display on certain display sizes.", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Extra class", 'swift-framework-plugin' ), "param_name" => "el_class", "value" => "", "description" => __( "If you wish to style this particular content element differently, then use this field to add a class name and then refer to it in your css file.", 'swift-framework-plugin' ) ) ), ) ); /* MESSAGE BOX ASSET ================================================== */ class SwiftPageBuilderShortcode_spb_message extends SwiftPageBuilderShortcode { protected function content( $atts, $content = null ) { $color = ''; extract( shortcode_atts( array( 'color' => 'alert-info', 'el_position' => '' ), $atts ) ); $output = ''; if ( $color == "alert-block" ) { $color = ""; } $width = spb_translateColumnWidthToSpan( "1/1" ); $output .= '<div class="' . $width . '"><div class="alert spb_content_element ' . $color . '"><div class="messagebox_text">' . spb_format_content( $content ) . '</div></div></div>' . $this->endBlockComment( 'alert box' ) . "\n"; //$output .= '<div class="spb_messagebox message '.$color.'"><div class="messagebox_text">'.spb_format_content($content).'</div></div>'; $output = $this->startRow( $el_position ) . $output . $this->endRow( $el_position ); return $output; } } SPBMap::map( 'spb_message', array( "name" => __( "Message Box", 'swift-framework-plugin' ), "base" => "spb_message", "class" => "spb_messagebox spb_controls_top_right spb_tab_ui", "icon" => "icon-message-box", "wrapper_class" => "alert", "controls" => "edit_popup_delete", "params" => array( array( "type" => "dropdown", "heading" => __( "Message box type", 'swift-framework-plugin' ), "param_name" => "color", "value" => array( __( 'Informational', 'swift-framework-plugin' ) => "alert-info", __( 'Warning', 'swift-framework-plugin' ) => "alert-block", __( 'Success', 'swift-framework-plugin' ) => "alert-success", __( 'Error', 'swift-framework-plugin' ) => "alert-error" ), "description" => __( "Select message type.", 'swift-framework-plugin' ) ), array( "type" => "textarea_html", "holder" => "div", "class" => "messagebox_text", "heading" => __( "Message text", 'swift-framework-plugin' ), "param_name" => "content", "value" => __( "<p>This is a message box. Click the edit button to edit this text.</p>", 'swift-framework-plugin' ), "description" => __( "Message text.", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Extra class", 'swift-framework-plugin' ), "param_name" => "el_class", "value" => "", "description" => __( "If you wish to style this particular content element differently, then use this field to add a class name and then refer to it in your css file.", 'swift-framework-plugin' ) ) ), "js_callback" => array( "init" => "spbMessageInitCallBack" ) ) ); /* TOGGLE ASSET ================================================== */ class SwiftPageBuilderShortcode_spb_toggle extends SwiftPageBuilderShortcode { protected function content( $atts, $content = null ) { $title = $el_class = $open = null; extract( shortcode_atts( array( 'title' => __( "Click to toggle", 'swift-framework-plugin' ), 'el_class' => '', 'open' => 'false', 'el_position' => '', 'width' => '1/1' ), $atts ) ); $output = ''; $width = spb_translateColumnWidthToSpan( $width ); $el_class = $this->getExtraClass( $el_class ); $open = ( $open == 'true' ) ? ' spb_toggle_title_active' : ''; $el_class .= ( $open == ' spb_toggle_title_active' ) ? ' spb_toggle_open' : ''; $output .= '<div class="toggle-wrap ' . $width . '">'; $output .= '<h4 class="spb_toggle' . $open . '">' . $title . '</h4><div class="spb_toggle_content' . $el_class . '">' . spb_format_content( $content ) . '</div>' . $this->endBlockComment( 'toggle' ) . "\n"; $output .= '</div>'; $output = $this->startRow( $el_position ) . $output . $this->endRow( $el_position ); return $output; } } SPBMap::map( 'spb_toggle', array( "name" => __( "Toggle", 'swift-framework-plugin' ), "base" => "spb_toggle", "class" => "spb_faq spb_tab_ui", "icon" => "icon-toggle", "params" => array( array( "type" => "textfield", "class" => "toggle_title", "heading" => __( "Toggle title", 'swift-framework-plugin' ), "param_name" => "title", "value" => __( "Toggle title", 'swift-framework-plugin' ), "description" => __( "Toggle block title.", 'swift-framework-plugin' ) ), array( "type" => "textarea_html", "holder" => "div", "class" => "toggle_content", "heading" => __( "Toggle content", 'swift-framework-plugin' ), "param_name" => "content", "value" => __( "<p>The toggle content goes here, click the edit button to change this text.</p>", 'swift-framework-plugin' ), "description" => __( "Toggle block content.", 'swift-framework-plugin' ) ), array( "type" => "dropdown", "heading" => __( "Default state", 'swift-framework-plugin' ), "param_name" => "open", "value" => array( __( "Closed", 'swift-framework-plugin' ) => "false", __( "Open", 'swift-framework-plugin' ) => "true" ), "description" => __( "Select this if you want toggle to be open by default.", 'swift-framework-plugin' ) ), array( "type" => "textfield", "heading" => __( "Extra class", 'swift-framework-plugin' ), "param_name" => "el_class", "value" => "", "description" => __( "If you wish to style this particular content element differently, then use this field to add a class name and then refer to it in your css file.", 'swift-framework-plugin' ) ) ) ) );
tuffon/imaginewithus
wp-content/plugins/swift-framework/includes/page-builder/shortcodes/default.php
PHP
gpl-2.0
31,195
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.epl.join.rep; import com.espertech.esper.client.EventBean; import com.espertech.esper.support.epl.join.SupportJoinResultNodeFactory; import com.espertech.esper.support.event.SupportEventBeanFactory; import java.util.*; import junit.framework.TestCase; public class TestRepositoryImpl extends TestCase { private EventBean s0Event; private RepositoryImpl repository; public void setUp() { s0Event = SupportEventBeanFactory.createObject(new Object()); repository = new RepositoryImpl(0, s0Event, 6); } public void testGetCursors() { // get cursor for root stream lookup Iterator<Cursor> it = repository.getCursors(0); assertTrue(it.hasNext()); Cursor cursor = it.next(); assertSame(s0Event, cursor.getTheEvent()); assertSame(0, cursor.getStream()); assertFalse(it.hasNext()); tryIteratorEmpty(it); // try invalid get cursor for no results try { repository.getCursors(2); fail(); } catch (NullPointerException ex) { // expected } } public void testAddResult() { Set<EventBean> results = SupportJoinResultNodeFactory.makeEventSet(2); repository.addResult(repository.getCursors(0).next(), results, 1); assertEquals(1, repository.getNodesPerStream()[1].size()); try { repository.addResult(repository.getCursors(0).next(), new HashSet<EventBean>(), 1); fail(); } catch (IllegalArgumentException ex) { // expected } try { repository.addResult(repository.getCursors(0).next(), null, 1); fail(); } catch (NullPointerException ex) { // expected } } public void testFlow() { // Lookup from s0 Cursor cursors[] = read(repository.getCursors(0)); assertEquals(1, cursors.length); Set<EventBean> resultsS1 = SupportJoinResultNodeFactory.makeEventSet(2); repository.addResult(cursors[0], resultsS1, 1); // Lookup from s1 cursors = read(repository.getCursors(1)); assertEquals(2, cursors.length); Set<EventBean> resultsS2[] = SupportJoinResultNodeFactory.makeEventSets(new int[] {2, 3}); repository.addResult(cursors[0], resultsS2[0], 2); repository.addResult(cursors[1], resultsS2[1], 2); // Lookup from s2 cursors = read(repository.getCursors(2)); assertEquals(5, cursors.length); // 2 + 3 for s2 Set<EventBean> resultsS3[] = SupportJoinResultNodeFactory.makeEventSets(new int[] {2, 1, 3, 5, 1}); repository.addResult(cursors[0], resultsS3[0], 3); repository.addResult(cursors[1], resultsS3[1], 3); repository.addResult(cursors[2], resultsS3[2], 3); repository.addResult(cursors[3], resultsS3[3], 3); repository.addResult(cursors[4], resultsS3[4], 3); // Lookup from s3 cursors = read(repository.getCursors(3)); assertEquals(12, cursors.length); } private void tryIteratorEmpty(Iterator it) { try { it.next(); fail(); } catch (NoSuchElementException ex) { // expected } } private Cursor[] read(Iterator<Cursor> iterator) { List<Cursor> cursors = new ArrayList<Cursor>(); while (iterator.hasNext()) { Cursor cursor = iterator.next(); cursors.add(cursor); } return cursors.toArray(new Cursor[0]); } }
sungsoo/esper
esper/src/test/java/com/espertech/esper/epl/join/rep/TestRepositoryImpl.java
Java
gpl-2.0
4,571
package doodle; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Comparator; import java.util.Date; /** * A poll is made up of two or more time slots, which are voted on by poll * invitees. A time slot is defined by a start datetime and optionally an end * datetime. * * @author Jonas Michel * */ public class TimeSlot implements Serializable { private static final long serialVersionUID = -8690469227753138784L; /** The time slot's start time. */ private Date start = null; /** The time slot's end time (optional). */ private Date end = null; public TimeSlot(Date start, Date end) { this.start = start; this.end = end; } public TimeSlot(Date start) { this.start = start; } public TimeSlot(Date day, String timeStr) throws NumberFormatException { if (timeStr.contains("-")) initDoubleTime(day, timeStr); else initSingleTime(day, timeStr); } public Date getStart() { return start; } public Date getEnd() { return end; } private void initSingleTime(Date day, String timeStr) throws NumberFormatException { start = parseTimeString(day, timeStr); } private void initDoubleTime(Date day, String timeStr) throws NumberFormatException { String[] timeStrArr = timeStr.split("-"); start = parseTimeString(day, timeStrArr[0]); end = parseTimeString(day, timeStrArr[1]); } private Date parseTimeString(Date day, String timeStr) throws NumberFormatException { int hour = 0, minute = 0; if (timeStr.contains(":")) { hour = Integer.parseInt(timeStr.split(":")[0]); minute = Integer.parseInt(timeStr.split(":")[1]); } else { hour = Integer.parseInt(timeStr); } Calendar cal = Calendar.getInstance(); cal.setTime(day); cal.add(Calendar.HOUR_OF_DAY, hour); cal.add(Calendar.MINUTE, minute); return cal.getTime(); } public String toDayString() { SimpleDateFormat day = new SimpleDateFormat("MM/dd/yyyy"); return day.format(start); } public String toTimeString() { SimpleDateFormat time = new SimpleDateFormat("HH:mm"); StringBuilder sb = new StringBuilder(); sb.append(time.format(start)); if (end == null) return sb.toString(); sb.append("-" + time.format(end)); return sb.toString(); } @Override public String toString() { return toDayString() + " " + toTimeString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((end == null) ? 0 : end.hashCode()); result = prime * result + ((start == null) ? 0 : start.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof TimeSlot)) return false; TimeSlot other = (TimeSlot) obj; if (end == null) { if (other.end != null) return false; } else if (!end.equals(other.end)) return false; if (start == null) { if (other.start != null) return false; } else if (!start.equals(other.start)) return false; return true; } public static class TimeSlotComparator implements Comparator<TimeSlot> { @Override public int compare(TimeSlot ts1, TimeSlot ts2) { if (ts1.getStart().before(ts2.getStart())) return -1; else if (ts1.getStart().after(ts2.getStart())) return 1; else return 0; } } }
jonasrmichel/jms-doodle-poll
joram-jms/samples/src/joram/doodle/TimeSlot.java
Java
gpl-2.0
3,355
<?php /* * Fixed blog_media hash column * Add "level" to blogs posts, which will be used as previous priority column */ sql_query('ALTER TABLE `blogs_media` CHANGE COLUMN `hash` `hash` VARCHAR(64) NOT NULL'); $medias = sql_query('SELECT `id`, `file` FROM `blogs_media`'); $update = sql_prepare('UPDATE `blogs_media` SET `hash` = :hash WHERE `id` = :id'); log_console(tr('Updating all blog media hash values. This might take a little while. NOTE: Each following dot represents one file')); while($media = sql_fetch($medias)){ if(empty($media['file'])) continue; cli_dot(1); $hash = ''; $file = ROOT.'data/content/photos/'.$media['file'].'-original.jpg'; if(file_exists($file)){ $hash = hash('sha256', $file); } if($hash){ $update->execute(array(':id' => $media['id'], ':hash' => $hash)); } } cli_dot(false); sql_column_exists('blogs_posts', 'level', '!ALTER TABLE `blogs_posts` ADD COLUMN `level` INT(11) NOT NULL AFTER `priority`'); sql_index_exists ('blogs_posts', 'level', '!ALTER TABLE `blogs_posts` ADD INDEX `level` (`level`)'); sql_query('ALTER TABLE `blogs_posts` CHANGE COLUMN `priority` `priority` INT(11) NOT NULL'); sql_index_exists ('blogs_posts', 'priority', 'ALTER TABLE `blogs_posts` DROP KEY `priority`'); sql_query('UPDATE `blogs_posts` SET `level` = `priority`'); /* * Ensure that all priorities are unique per blog */ $blogs = sql_query('SELECT `id`, `name` FROM `blogs`'); $update = sql_prepare('UPDATE `blogs_posts` SET `priority` = :priority WHERE `id` = :id'); while($blog = sql_fetch($blogs)){ log_console(tr('Updating priorities for blog ":blog"', array(':blog' => $blog['name']))); $priority = 1; $posts = sql_query('SELECT `id`, `name` FROM `blogs_posts` WHERE `blogs_id` = :blogs_id ORDER BY `createdon` ASC', array(':blogs_id' => $blog['id'])); while($post = sql_fetch($posts)){ cli_dot(1); $update->execute(array(':id' => $post['id'], ':priority' => $priority++)); } cli_dot(false); } sql_query('ALTER TABLE `blogs_posts` ADD UNIQUE KEY `priority` (`priority`, `blogs_id`)'); ?>
phoenixz/base
init/framework/0.47.4.php
PHP
gpl-2.0
2,194
package tim.prune.threedee; import java.awt.event.InputEvent; /* * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. * * Copyright (c) 2021 ActivityWorkshop simplifications and renamings, * and restriction to upright orientations. */ import java.awt.event.MouseEvent; import java.awt.AWTEvent; import javax.media.j3d.Transform3D; import javax.media.j3d.Canvas3D; import javax.vecmath.Vector3d; import javax.vecmath.Point3d; import javax.vecmath.Matrix3d; import com.sun.j3d.utils.behaviors.vp.ViewPlatformAWTBehavior; import com.sun.j3d.utils.universe.ViewingPlatform; /** * Moves the View around a point of interest when the mouse is dragged with * a mouse button pressed. Includes rotation, zoom, and translation * actions. Zooming can also be obtained by using mouse wheel. * <p> * The rotate action rotates the ViewPlatform around the point of interest * when the mouse is moved with the main mouse button pressed. The * rotation is in the direction of the mouse movement, with a default * rotation of 0.01 radians for each pixel of mouse movement. * <p> * The zoom action moves the ViewPlatform closer to or further from the * point of interest when the mouse is moved with the middle mouse button * pressed (or Alt-main mouse button on systems without a middle mouse button). * The default zoom action is to translate the ViewPlatform 0.01 units for each * pixel of mouse movement. Moving the mouse up moves the ViewPlatform closer, * moving the mouse down moves the ViewPlatform further away. * <p> * The translate action translates the ViewPlatform when the mouse is moved * with the right mouse button pressed. The translation is in the direction * of the mouse movement, with a default translation of 0.01 units for each * pixel of mouse movement. * <p> * The actions can be reversed using the <code>REVERSE_</code><i>ACTION</i> * constructor flags. The default action moves the ViewPlatform around the * objects in the scene. The <code>REVERSE_</code><i>ACTION</i> flags can * make the objects in the scene appear to be moving in the direction * of the mouse movement. */ public class UprightOrbiter extends ViewPlatformAWTBehavior { private Transform3D _longitudeTransform = new Transform3D(); private Transform3D _latitudeTransform = new Transform3D(); private Transform3D _rotateTransform = new Transform3D(); // needed for integrateTransforms but don't want to new every time private Transform3D _temp1 = new Transform3D(); private Transform3D _temp2 = new Transform3D(); private Transform3D _translation = new Transform3D(); private Vector3d _transVector = new Vector3d(); private Vector3d _distanceVector = new Vector3d(); private Vector3d _centerVector = new Vector3d(); private Vector3d _invertCenterVector = new Vector3d(); private double _deltaYaw = 0.0, _deltaPitch = 0.0; private double _startDistanceFromCenter = 20.0; private double _distanceFromCenter = 20.0; private Point3d _rotationCenter = new Point3d(); private Matrix3d _rotMatrix = new Matrix3d(); private int _mouseX = 0, _mouseY = 0; private double _xtrans = 0.0, _ytrans = 0.0, _ztrans = 0.0; private static final double MIN_RADIUS = 0.0; // the factor to be applied to wheel zooming so that it does not // look much different with mouse movement zooming. private static final float wheelZoomFactor = 50.0f; private static final double NOMINAL_ZOOM_FACTOR = .01; private static final double NOMINAL_ROT_FACTOR = .008; private static final double NOMINAL_TRANS_FACTOR = .003; private double _pitchAngle = 0.0; /** * Creates a new OrbitBehaviour * @param inCanvas The Canvas3D to add the behaviour to * @param inInitialPitch pitch angle in degrees */ public UprightOrbiter(Canvas3D inCanvas, double inInitialPitch) { super(inCanvas, MOUSE_LISTENER | MOUSE_MOTION_LISTENER | MOUSE_WHEEL_LISTENER ); _pitchAngle = Math.toRadians(inInitialPitch); } protected synchronized void processAWTEvents( final AWTEvent[] events ) { motion = false; for (AWTEvent event : events) { if (event instanceof MouseEvent) { processMouseEvent((MouseEvent) event); } } } protected void processMouseEvent( final MouseEvent evt ) { if (evt.getID() == MouseEvent.MOUSE_PRESSED) { _mouseX = evt.getX(); _mouseY = evt.getY(); motion = true; } else if (evt.getID() == MouseEvent.MOUSE_DRAGGED) { int xchange = evt.getX() - _mouseX; int ychange = evt.getY() - _mouseY; // rotate if (isRotateEvent(evt)) { _deltaYaw -= xchange * NOMINAL_ROT_FACTOR; _deltaPitch -= ychange * NOMINAL_ROT_FACTOR; } // translate else if (isTranslateEvent(evt)) { _xtrans -= xchange * NOMINAL_TRANS_FACTOR; _ytrans += ychange * NOMINAL_TRANS_FACTOR; } // zoom else if (isZoomEvent(evt)) { doZoomOperations( ychange ); } _mouseX = evt.getX(); _mouseY = evt.getY(); motion = true; } else if (evt.getID() == MouseEvent.MOUSE_WHEEL ) { if (isZoomEvent(evt)) { // if zooming is done through mouse wheel, the number of wheel increments // is multiplied by the wheelZoomFactor, to make zoom speed look natural if ( evt instanceof java.awt.event.MouseWheelEvent) { int zoom = ((int)(((java.awt.event.MouseWheelEvent)evt).getWheelRotation() * wheelZoomFactor)); doZoomOperations( zoom ); motion = true; } } } } /* * zoom but stop at MIN_RADIUS */ private void doZoomOperations( int ychange ) { if ((_distanceFromCenter - ychange * NOMINAL_ZOOM_FACTOR) > MIN_RADIUS) { _distanceFromCenter -= ychange * NOMINAL_ZOOM_FACTOR; } else { _distanceFromCenter = MIN_RADIUS; } } /** * Sets the ViewingPlatform for this behaviour. This method is * called by the ViewingPlatform. * If a sub-calls overrides this method, it must call * super.setViewingPlatform(vp). * NOTE: Applications should <i>not</i> call this method. */ @Override public void setViewingPlatform(ViewingPlatform vp) { super.setViewingPlatform( vp ); if (vp != null) { resetView(); integrateTransforms(); } } /** * Reset the orientation and distance of this behaviour to the current * values in the ViewPlatform Transform Group */ private void resetView() { Vector3d centerToView = new Vector3d(); targetTG.getTransform( targetTransform ); targetTransform.get( _rotMatrix, _transVector ); centerToView.sub( _transVector, _rotationCenter ); _distanceFromCenter = centerToView.length(); _startDistanceFromCenter = _distanceFromCenter; targetTransform.get( _rotMatrix ); _rotateTransform.set( _rotMatrix ); // compute the initial x/y/z offset _temp1.set(centerToView); _rotateTransform.invert(); _rotateTransform.mul(_temp1); _rotateTransform.get(centerToView); _xtrans = centerToView.x; _ytrans = centerToView.y; _ztrans = centerToView.z; // reset rotMatrix _rotateTransform.set( _rotMatrix ); } protected synchronized void integrateTransforms() { // Check if the transform has been changed by another behaviour Transform3D currentXfm = new Transform3D(); targetTG.getTransform(currentXfm); if (! targetTransform.equals(currentXfm)) resetView(); // Three-step rotation process, firstly undo the pitch and apply the delta yaw _latitudeTransform.rotX(_pitchAngle); _rotateTransform.mul(_rotateTransform, _latitudeTransform); _longitudeTransform.rotY( _deltaYaw ); _rotateTransform.mul(_rotateTransform, _longitudeTransform); // Now update pitch angle according to delta and apply _pitchAngle = Math.min(Math.max(0.0, _pitchAngle - _deltaPitch), Math.PI/2.0); _latitudeTransform.rotX(-_pitchAngle); _rotateTransform.mul(_rotateTransform, _latitudeTransform); _distanceVector.z = _distanceFromCenter - _startDistanceFromCenter; _temp1.set(_distanceVector); _temp1.mul(_rotateTransform, _temp1); // want to look at rotationCenter _transVector.x = _rotationCenter.x + _xtrans; _transVector.y = _rotationCenter.y + _ytrans; _transVector.z = _rotationCenter.z + _ztrans; _translation.set(_transVector); targetTransform.mul(_temp1, _translation); // handle rotationCenter _temp1.set(_centerVector); _temp1.mul(targetTransform); _invertCenterVector.x = -_centerVector.x; _invertCenterVector.y = -_centerVector.y; _invertCenterVector.z = -_centerVector.z; _temp2.set(_invertCenterVector); targetTransform.mul(_temp1, _temp2); Vector3d finalTranslation = new Vector3d(); targetTransform.get(finalTranslation); targetTG.setTransform(targetTransform); // reset yaw and pitch deltas _deltaYaw = 0.0; _deltaPitch = 0.0; } private boolean isRotateEvent(MouseEvent evt) { final boolean isRightDrag = (evt.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) > 0; return !evt.isAltDown() && !isRightDrag; } private boolean isZoomEvent(MouseEvent evt) { if (evt instanceof java.awt.event.MouseWheelEvent) { return true; } return evt.isAltDown() && !evt.isMetaDown(); } private boolean isTranslateEvent(MouseEvent evt) { final boolean isRightDrag = (evt.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) > 0; return !evt.isAltDown() && isRightDrag; } }
activityworkshop/GpsPrune
src/tim/prune/threedee/UprightOrbiter.java
Java
gpl-2.0
10,939
/** * 对公众平台发送给公众账号的消息加解密示例代码. * * @copyright Copyright (c) 1998-2014 Tencent Inc. */ // ------------------------------------------------------------------------ package com.weixin.sdk.encrypt; import java.security.MessageDigest; import java.util.Arrays; /** * SHA1 class * * 计算公众平台的消息签名接口. */ class SHA1 { /** * 用SHA1算法生成安全签名 * @param token 票据 * @param timestamp 时间戳 * @param nonce 随机字符串 * @param encrypt 密文 * @return 安全签名 * @throws AesException */ public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException { try { String[] array = new String[] { token, timestamp, nonce, encrypt }; StringBuffer sb = new StringBuffer(); // 字符串排序 Arrays.sort(array); for (int i = 0; i < 4; i++) { sb.append(array[i]); } String str = sb.toString(); // SHA1签名生成 MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes()); byte[] digest = md.digest(); StringBuffer hexstr = new StringBuffer(); String shaHex = ""; for (int i = 0; i < digest.length; i++) { shaHex = Integer.toHexString(digest[i] & 0xFF); if (shaHex.length() < 2) { hexstr.append(0); } hexstr.append(shaHex); } return hexstr.toString(); } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.ComputeSignatureError); } } }
teabo/wholly-framework
wholly-demo/wholly_weixin/src/main/java/com/weixin/sdk/encrypt/SHA1.java
Java
gpl-2.0
1,592
/* Copyright (C) 2015 Panagiotis Roubatsis 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. */ /* * Created by Panagiotis Roubatsis * * Description: A single adjacency for the adjacency list. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Map_Creator { class MapAdjacency { public int destIndex; public int cost; public bool invisible; public MapAdjacency(int dest, int cost, bool invisible) { this.destIndex = dest; this.cost = cost; this.invisible = invisible; } } }
proubatsis/Map-Creator
Map Creator/MapAdjacency.cs
C#
gpl-2.0
1,312
package com.rockey.emonitor.jms.controller; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import com.rockey.emonitor.jms.component.AppList; import com.rockey.emonitor.jms.component.EmonitorContext; import com.rockey.emonitor.jms.component.FilterList; import com.rockey.emonitor.jms.model.LogMessage; import com.rockey.emonitor.jms.service.MessageService; import com.rockey.emonitor.jms.util.Base64; import com.rockey.emonitor.jms.util.Util; import com.rockey.emonitor.model.AppFilter; public class MessageController extends AbstractController{ private static final Log log = LogFactory.getLog(MessageController.class); @Autowired private MessageService messageService; @Autowired private EmonitorContext runtimeContext; @Autowired private AppList appListComponent; @Autowired private FilterList filterListComponent; private String key; public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("utf-8"); log.info("requestURL =[ " + request.getRequestURI() + "?" + request.getQueryString() + " ]"); if (!runtimeContext.isReadyProcess()) { log.error("EmonitorContext not init complete ! please wait..."); return null; } try { List<String> appList = appListComponent.getAppList(); Map<String, List<AppFilter>> filterMap = filterListComponent.getFilterMap(); Map<String,String> params = new HashMap<String,String>(); // 打印参数列表 @SuppressWarnings("unchecked") Enumeration<String> names = request.getParameterNames(); if(names.hasMoreElements()) { while (names.hasMoreElements()) { String paramName = (String) names.nextElement(); String paramValue = request.getParameter(paramName); //将所有参数转为大写 params.put(paramName.toUpperCase(), paramValue); log.info("Request Parameter:" + paramName + "=" + paramValue); } } //获取消息 String message = params.get("MESSAGE"); if (message!= null && !message.isEmpty()) { message = new String(Base64.decode(message.getBytes("UTF-8")),"UTF-8"); } log.info("client IP :" + request.getRemoteAddr() + ", message = " + message); LogMessage logMessage = Util.createMessageFromXml(message); //密钥检测 String sign = Util.ComputeHash(logMessage, this.key); if (logMessage.getSign().equals(sign)) { if (!appList.isEmpty() && appList.contains(logMessage.getApplicationID())) {//应用合法检测 if (!filterMap.isEmpty() && filterMap.containsKey(logMessage.getApplicationID())) {//过滤器检测 List<AppFilter> fiterList = filterMap.get(logMessage.getApplicationID()); for (AppFilter filter : fiterList) { if (logMessage.getTitle().contains(filter.getContent())) { log.info("告警标题包含过滤信息[" + filter.getContent() + "],信息将会被过滤。"); return null; } if (logMessage.getBody().contains(filter.getContent())) { log.info("告警内容包含过滤信息[" + filter.getContent() + "],信息将会被过滤。"); return null; } } } messageService.sendAlertMessage(logMessage); } else { log.error("invalid applicationId (" + logMessage.getApplicationID() + ") ...."); } } } catch (Exception e) { log.error("MessageController err", e); } return null; } }
RockeyHoo/icheck
emonitor/src/main/java/com/rockey/emonitor/jms/controller/MessageController.java
Java
gpl-2.0
4,087
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace FormsAuthWeb { public partial class MyInfo { } }
cbfjay/Aspnet.Login
FormsAuthWeb/MyInfo.aspx.designer.cs
C#
gpl-2.0
452
<?php if ( ! defined( 'ABSPATH' ) ) { exit; // disable direct access } if ( ! class_exists( 'Mega_Menu_Nav_Menus' ) ) : /** * Handles all admin related functionality. */ class Mega_Menu_Nav_Menus { /** * Return the default settings for each menu item * * @since 1.5 */ public static function get_menu_item_defaults() { $defaults = array( 'type' => 'flyout', 'align' => 'bottom-left', 'icon' => 'disabled', 'hide_text' => 'false', 'disable_link' => 'false', 'hide_arrow' => 'false', 'item_align' => 'left', 'panel_columns' => 6, // total number of columns displayed in the panel 'mega_menu_columns' => 1 // for sub menu items, how many columns to span in the panel ); return apply_filters( "megamenu_menu_item_defaults", $defaults ); } /** * Constructor * * @since 1.0 */ public function __construct() { add_action( 'admin_init', array( $this, 'register_nav_meta_box' ), 11 ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_menu_page_scripts' ) ); add_action( 'megamenu_save_settings', array($this, 'save') ); add_filter( 'hidden_meta_boxes', array( $this, 'show_mega_menu_metabox' ) ); } /** * By default the mega menu meta box is hidden - show it. * * @since 1.0 * @param array $hidden * @return array */ public function show_mega_menu_metabox( $hidden ) { if ( is_array( $hidden ) && count( $hidden ) > 0 ) { foreach ( $hidden as $key => $value ) { if ( $value == 'mega_menu_meta_box' ) { unset( $hidden[$key] ); } } } return $hidden; } /** * Adds the meta box container * * @since 1.0 */ public function register_nav_meta_box() { global $pagenow; if ( 'nav-menus.php' == $pagenow ) { add_meta_box( 'mega_menu_meta_box', __("Mega Menu Settings", "megamenu"), array( $this, 'metabox_contents' ), 'nav-menus', 'side', 'high' ); } } /** * Enqueue required CSS and JS for Mega Menu * * @since 1.0 */ public function enqueue_menu_page_scripts($hook) { if( 'nav-menus.php' != $hook ) return; // http://wordpress.org/plugins/image-widget/ if ( class_exists( 'Tribe_Image_Widget' ) ) { $image_widget = new Tribe_Image_Widget; $image_widget->admin_setup(); } wp_enqueue_style( 'colorbox', MEGAMENU_BASE_URL . 'js/colorbox/colorbox.css', false, MEGAMENU_VERSION ); wp_enqueue_style( 'mega-menu', MEGAMENU_BASE_URL . 'css/admin-menus.css', false, MEGAMENU_VERSION ); wp_enqueue_script( 'mega-menu', MEGAMENU_BASE_URL . 'js/admin.js', array( 'jquery', 'jquery-ui-core', 'jquery-ui-sortable', 'jquery-ui-accordion'), MEGAMENU_VERSION ); wp_enqueue_script( 'colorbox', MEGAMENU_BASE_URL . 'js/colorbox/jquery.colorbox-min.js', array( 'jquery' ), MEGAMENU_VERSION ); wp_localize_script( 'mega-menu', 'megamenu', array( 'debug_launched' => __("Launched for Menu ID", "megamenu"), 'launch_lightbox' => __("Mega Menu", "megamenu"), 'saving' => __("Saving", "megamenu"), 'nonce' => wp_create_nonce('megamenu_edit'), 'nonce_check_failed' => __("Oops. Something went wrong. Please reload the page.", "megamenu") ) ); do_action("megamenu_enqueue_admin_scripts"); } /** * Show the Meta Menu settings * * @since 1.0 */ public function metabox_contents() { $menu_id = $this->get_selected_menu_id(); do_action("megamenu_save_settings"); $this->print_enable_megamenu_options( $menu_id ); } /** * Save the mega menu settings (submitted from Menus Page Meta Box) * * @since 1.0 */ public function save() { if ( isset( $_POST['menu'] ) && $_POST['menu'] > 0 && is_nav_menu( $_POST['menu'] ) && isset( $_POST['megamenu_meta'] ) ) { $submitted_settings = $_POST['megamenu_meta']; if ( ! get_site_option( 'megamenu_settings' ) ) { add_site_option( 'megamenu_settings', $submitted_settings ); } else { $existing_settings = get_site_option( 'megamenu_settings' ); $new_settings = array_merge( $existing_settings, $submitted_settings ); update_site_option( 'megamenu_settings', $new_settings ); } do_action( "megamenu_after_save_settings" ); } } /** * Print the custom Meta Box settings * * @param int $menu_id * @since 1.0 */ public function print_enable_megamenu_options( $menu_id ) { $tagged_menu_locations = $this->get_tagged_theme_locations_for_menu_id( $menu_id ); $theme_locations = get_registered_nav_menus(); $saved_settings = get_site_option( 'megamenu_settings' ); if ( ! count( $theme_locations ) ) { echo "<p>" . __("This theme does not have any menu locations.", "megamenu") . "</p>"; } else if ( ! count ( $tagged_menu_locations ) ) { echo "<p>" . __("This menu is not tagged to a location. Please tag a location to enable the Mega Menu settings.", "megamenu") . "</p>"; } else { ?> <?php if ( count( $tagged_menu_locations ) == 1 ) : ?> <?php $locations = array_keys( $tagged_menu_locations ); $location = $locations[0]; if (isset( $tagged_menu_locations[ $location ] ) ) { $this->settings_table( $location, $saved_settings ); } ?> <?php else: ?> <div id='megamenu_accordion'> <?php foreach ( $theme_locations as $location => $name ) : ?> <?php if ( isset( $tagged_menu_locations[ $location ] ) ): ?> <h3 class='theme_settings'><?php echo esc_html( $name ); ?></h3> <div class='accordion_content' style='display: none;'> <?php $this->settings_table( $location, $saved_settings ); ?> </div> <?php endif; ?> <?php endforeach;?> </div> <?php endif; ?> <?php submit_button( __( 'Save' ), 'button-primary alignright'); } } /** * Print the list of Mega Menu settings * * @since 1.0 */ public function settings_table( $location, $settings ) { ?> <table> <tr> <td><?php _e("Enable", "megamenu") ?></td> <td> <input type='checkbox' name='megamenu_meta[<?php echo $location ?>][enabled]' value='1' <?php checked( isset( $settings[$location]['enabled'] ) ); ?> /> </td> </tr> <tr> <td><?php _e("Event", "megamenu") ?></td> <td> <select name='megamenu_meta[<?php echo $location ?>][event]'> <option value='hover' <?php selected( isset( $settings[$location]['event'] ) && $settings[$location]['event'] == 'hover'); ?>><?php _e("Hover", "megamenu"); ?></option> <option value='click' <?php selected( isset( $settings[$location]['event'] ) && $settings[$location]['event'] == 'click'); ?>><?php _e("Click", "megamenu"); ?></option> </select> </td> </tr> <tr> <td><?php _e("Effect", "megamenu") ?></td> <td> <select name='megamenu_meta[<?php echo $location ?>][effect]'> <?php $selected = isset( $settings[$location]['effect'] ) ? $settings[$location]['effect'] : 'disabled'; $options = apply_filters("megamenu_effects", array( "disabled" => array( 'label' => __("None", "megamenu"), 'selected' => $selected == 'disabled', ), "fade" => array( 'label' => __("Fade", "megamenu"), 'selected' => $selected == 'fade', ), "slide" => array( 'label' => __("Slide", "megamenu"), 'selected' => $selected == 'slide', ) ), $selected ); foreach ( $options as $key => $value ) { ?><option value='<?php echo $key ?>' <?php selected( $value['selected'] ); ?>><?php echo $value['label'] ?></option><?php } ?> </select> </td> </tr> <tr> <td><?php _e("Theme", "megamenu"); ?></td> <td> <select name='megamenu_meta[<?php echo $location ?>][theme]'> <?php $style_manager = new Mega_Menu_Style_Manager(); $themes = $style_manager->get_themes(); foreach ( $themes as $key => $theme ) { echo "<option value='{$key}' " . selected( $settings[$location]['theme'], $key ) . ">{$theme['title']}</option>"; } ?> </select> </td> </tr> <?php do_action('megamenu_settings_table', $location, $settings); ?> </table> <?php } /** * Return the locations that a specific menu ID has been tagged to. * * @param $menu_id int * @return array */ public function get_tagged_theme_locations_for_menu_id( $menu_id ) { $locations = array(); $nav_menu_locations = get_nav_menu_locations(); foreach ( get_registered_nav_menus() as $id => $name ) { if ( isset( $nav_menu_locations[ $id ] ) && $nav_menu_locations[$id] == $menu_id ) $locations[$id] = $name; } return $locations; } /** * Get the current menu ID. * * Most of this taken from wp-admin/nav-menus.php (no built in functions to do this) * * @since 1.0 * @return int */ public function get_selected_menu_id() { $nav_menus = wp_get_nav_menus( array('orderby' => 'name') ); $menu_count = count( $nav_menus ); $nav_menu_selected_id = isset( $_REQUEST['menu'] ) ? (int) $_REQUEST['menu'] : 0; $add_new_screen = ( isset( $_GET['menu'] ) && 0 == $_GET['menu'] ) ? true : false; // If we have one theme location, and zero menus, we take them right into editing their first menu $page_count = wp_count_posts( 'page' ); $one_theme_location_no_menus = ( 1 == count( get_registered_nav_menus() ) && ! $add_new_screen && empty( $nav_menus ) && ! empty( $page_count->publish ) ) ? true : false; // Get recently edited nav menu $recently_edited = absint( get_user_option( 'nav_menu_recently_edited' ) ); if ( empty( $recently_edited ) && is_nav_menu( $nav_menu_selected_id ) ) $recently_edited = $nav_menu_selected_id; // Use $recently_edited if none are selected if ( empty( $nav_menu_selected_id ) && ! isset( $_GET['menu'] ) && is_nav_menu( $recently_edited ) ) $nav_menu_selected_id = $recently_edited; // On deletion of menu, if another menu exists, show it if ( ! $add_new_screen && 0 < $menu_count && isset( $_GET['action'] ) && 'delete' == $_GET['action'] ) $nav_menu_selected_id = $nav_menus[0]->term_id; // Set $nav_menu_selected_id to 0 if no menus if ( $one_theme_location_no_menus ) { $nav_menu_selected_id = 0; } elseif ( empty( $nav_menu_selected_id ) && ! empty( $nav_menus ) && ! $add_new_screen ) { // if we have no selection yet, and we have menus, set to the first one in the list $nav_menu_selected_id = $nav_menus[0]->term_id; } return $nav_menu_selected_id; } } endif;
Metrashev/Obuhte
wp-content/plugins/megamenu/classes/nav-menus.class.php
PHP
gpl-2.0
12,985
using System; namespace Player.Model { /// <remarks> /// A button can only be rectangular, if there should be other forms, you have to use more buttons which reference each other. /// </remarks> public interface ButtonPosition { int X { get; } int Y { get; } /// <summary>The dimension in x coordinates, i.e. how many columns are allocated.</summary> int DimX { get; } /// <summary>The dimension in y coordinates, i.e. how many rows are allocated.</summary> int DimY { get; } } }
asterics/KeyboardX
Player/Model/ButtonPosition.cs
C#
gpl-2.0
579
/* * Copyright (C) 2011-2021 Project SkyFire <https://www.projectskyfire.org/> * Copyright (C) 2008-2021 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2021 MaNGOS <https://www.getmangos.eu/> * Copyright (C) 2006-2014 ScriptDev2 <https://github.com/scriptdev2/scriptdev2/> * * 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/>. */ /* ScriptData SDName: Shattrath_City SD%Complete: 100 SDComment: Quest support: 10004, 10009, 10211. Flask vendors, Teleport to Caverns of Time SDCategory: Shattrath City EndScriptData */ /* ContentData npc_raliq_the_drunk npc_salsalabim npc_shattrathflaskvendors npc_zephyr npc_kservant npc_ishanah npc_khadgar EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "ScriptedEscortAI.h" #include "Player.h" #include "WorldSession.h" /*###### ## npc_raliq_the_drunk ######*/ #define GOSSIP_RALIQ "You owe Sim'salabim money. Hand them over or die!" enum Raliq { SPELL_UPPERCUT = 10966, QUEST_CRACK_SKULLS = 10009, FACTION_HOSTILE_RD = 45 }; class npc_raliq_the_drunk : public CreatureScript { public: npc_raliq_the_drunk() : CreatureScript("npc_raliq_the_drunk") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) OVERRIDE { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_INFO_DEF+1) { player->CLOSE_GOSSIP_MENU(); creature->setFaction(FACTION_HOSTILE_RD); creature->AI()->AttackStart(player); } return true; } bool OnGossipHello(Player* player, Creature* creature) OVERRIDE { if (player->GetQuestStatus(QUEST_CRACK_SKULLS) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_RALIQ, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); player->SEND_GOSSIP_MENU(9440, creature->GetGUID()); return true; } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_raliq_the_drunkAI(creature); } struct npc_raliq_the_drunkAI : public ScriptedAI { npc_raliq_the_drunkAI(Creature* creature) : ScriptedAI(creature) { m_uiNormFaction = creature->getFaction(); } uint32 m_uiNormFaction; uint32 Uppercut_Timer; void Reset() OVERRIDE { Uppercut_Timer = 5000; me->RestoreFaction(); } void UpdateAI(uint32 diff) OVERRIDE { if (!UpdateVictim()) return; if (Uppercut_Timer <= diff) { DoCastVictim(SPELL_UPPERCUT); Uppercut_Timer = 15000; } else Uppercut_Timer -= diff; DoMeleeAttackIfReady(); } }; }; /*###### # npc_salsalabim ######*/ enum Salsalabim { // Factions FACTION_HOSTILE_SA = 90, FACTION_FRIENDLY_SA = 35, // Quests QUEST_10004 = 10004, // Spells SPELL_MAGNETIC_PULL = 31705 }; class npc_salsalabim : public CreatureScript { public: npc_salsalabim() : CreatureScript("npc_salsalabim") { } bool OnGossipHello(Player* player, Creature* creature) OVERRIDE { if (player->GetQuestStatus(QUEST_10004) == QUEST_STATUS_INCOMPLETE) { creature->setFaction(FACTION_HOSTILE_SA); creature->AI()->AttackStart(player); } else { if (creature->IsQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); } return true; } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_salsalabimAI(creature); } struct npc_salsalabimAI : public ScriptedAI { npc_salsalabimAI(Creature* creature) : ScriptedAI(creature) { } uint32 MagneticPull_Timer; void Reset() OVERRIDE { MagneticPull_Timer = 15000; me->RestoreFaction(); } void DamageTaken(Unit* done_by, uint32 &damage) OVERRIDE { if (done_by->GetTypeId() == TypeID::TYPEID_PLAYER && me->HealthBelowPctDamaged(20, damage)) { done_by->ToPlayer()->GroupEventHappens(QUEST_10004, me); damage = 0; EnterEvadeMode(); } } void UpdateAI(uint32 diff) OVERRIDE { if (!UpdateVictim()) return; if (MagneticPull_Timer <= diff) { DoCastVictim(SPELL_MAGNETIC_PULL); MagneticPull_Timer = 15000; } else MagneticPull_Timer -= diff; DoMeleeAttackIfReady(); } }; }; /* ################################################## Shattrath City Flask Vendors provides flasks to people exalted with 3 fActions: Haldor the Compulsive Arcanist Xorith Both sell special flasks for use in Outlands 25man raids only, purchasable for one Mark of Illidari each Purchase requires exalted reputation with Scryers/Aldor, Cenarion Expedition and The Sha'tar ################################################## */ class npc_shattrathflaskvendors : public CreatureScript { public: npc_shattrathflaskvendors() : CreatureScript("npc_shattrathflaskvendors") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) OVERRIDE { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_TRADE) player->GetSession()->SendListInventory(creature->GetGUID()); return true; } bool OnGossipHello(Player* player, Creature* creature) OVERRIDE { if (creature->GetEntry() == 23484) { // Aldor vendor if (creature->IsVendor() && (player->GetReputationRank(932) == REP_EXALTED) && (player->GetReputationRank(935) == REP_EXALTED) && (player->GetReputationRank(942) == REP_EXALTED)) { player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE); player->SEND_GOSSIP_MENU(11085, creature->GetGUID()); } else { player->SEND_GOSSIP_MENU(11083, creature->GetGUID()); } } if (creature->GetEntry() == 23483) { // Scryers vendor if (creature->IsVendor() && (player->GetReputationRank(934) == REP_EXALTED) && (player->GetReputationRank(935) == REP_EXALTED) && (player->GetReputationRank(942) == REP_EXALTED)) { player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE); player->SEND_GOSSIP_MENU(11085, creature->GetGUID()); } else { player->SEND_GOSSIP_MENU(11084, creature->GetGUID()); } } return true; } }; /*###### # npc_zephyr ######*/ #define GOSSIP_HZ "Take me to the Caverns of Time." class npc_zephyr : public CreatureScript { public: npc_zephyr() : CreatureScript("npc_zephyr") { } bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) OVERRIDE { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_INFO_DEF+1) player->CastSpell(player, 37778, false); return true; } bool OnGossipHello(Player* player, Creature* creature) OVERRIDE { if (player->GetReputationRank(989) >= REP_REVERED) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HZ, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } }; /*###### # npc_kservant ######*/ enum KServant { SAY1 = 0, WHISP1 = 1, WHISP2 = 2, WHISP3 = 3, WHISP4 = 4, WHISP5 = 5, WHISP6 = 6, WHISP7 = 7, WHISP8 = 8, WHISP9 = 9, WHISP10 = 10, WHISP11 = 11, WHISP12 = 12, WHISP13 = 13, WHISP14 = 14, WHISP15 = 15, WHISP16 = 16, WHISP17 = 17, WHISP18 = 18, WHISP19 = 19, WHISP20 = 20, WHISP21 = 21 }; class npc_kservant : public CreatureScript { public: npc_kservant() : CreatureScript("npc_kservant") { } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_kservantAI(creature); } struct npc_kservantAI : public npc_escortAI { public: npc_kservantAI(Creature* creature) : npc_escortAI(creature) { } void WaypointReached(uint32 waypointId) OVERRIDE { Player* player = GetPlayerForEscort(); if (!player) return; switch (waypointId) { case 0: Talk(SAY1, player); break; case 4: Talk(WHISP1, player); break; case 6: Talk(WHISP2, player); break; case 7: Talk(WHISP3, player); break; case 8: Talk(WHISP4, player); break; case 17: Talk(WHISP5, player); break; case 18: Talk(WHISP6, player); break; case 19: Talk(WHISP7, player); break; case 33: Talk(WHISP8, player); break; case 34: Talk(WHISP9, player); break; case 35: Talk(WHISP10, player); break; case 36: Talk(WHISP11, player); break; case 43: Talk(WHISP12, player); break; case 44: Talk(WHISP13, player); break; case 49: Talk(WHISP14, player); break; case 50: Talk(WHISP15, player); break; case 51: Talk(WHISP16, player); break; case 52: Talk(WHISP17, player); break; case 53: Talk(WHISP18, player); break; case 54: Talk(WHISP19, player); break; case 55: Talk(WHISP20, player); break; case 56: Talk(WHISP21, player); player->GroupEventHappens(10211, me); break; } } void MoveInLineOfSight(Unit* who) OVERRIDE { if (HasEscortState(STATE_ESCORT_ESCORTING)) return; Player* player = who->ToPlayer(); if (player && player->GetQuestStatus(10211) == QUEST_STATUS_INCOMPLETE) { float Radius = 10.0f; if (me->IsWithinDistInMap(who, Radius)) { Start(false, false, who->GetGUID()); } } } void Reset() OVERRIDE { } }; }; /*###### # npc_ishanah ######*/ #define ISANAH_GOSSIP_1 "Who are the Sha'tar?" #define ISANAH_GOSSIP_2 "Isn't Shattrath a draenei city? Why do you allow others here?" class npc_ishanah : public CreatureScript { public: npc_ishanah() : CreatureScript("npc_ishanah") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) OVERRIDE { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_INFO_DEF+1) player->SEND_GOSSIP_MENU(9458, creature->GetGUID()); else if (action == GOSSIP_ACTION_INFO_DEF+2) player->SEND_GOSSIP_MENU(9459, creature->GetGUID()); return true; } bool OnGossipHello(Player* player, Creature* creature) OVERRIDE { if (creature->IsQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, ISANAH_GOSSIP_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, ISANAH_GOSSIP_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } }; /*###### # npc_khadgar ######*/ #define KHADGAR_GOSSIP_1 "I've heard your name spoken only in whispers, mage. Who are you?" #define KHADGAR_GOSSIP_2 "Go on, please." #define KHADGAR_GOSSIP_3 "I see." //6th too this #define KHADGAR_GOSSIP_4 "What did you do then?" #define KHADGAR_GOSSIP_5 "What happened next?" #define KHADGAR_GOSSIP_7 "There was something else I wanted to ask you." class npc_khadgar : public CreatureScript { public: npc_khadgar() : CreatureScript("npc_khadgar") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) OVERRIDE { player->PlayerTalkClass->ClearMenus(); switch (action) { case GOSSIP_ACTION_INFO_DEF+1: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, KHADGAR_GOSSIP_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); player->SEND_GOSSIP_MENU(9876, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+2: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, KHADGAR_GOSSIP_3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); player->SEND_GOSSIP_MENU(9877, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+3: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, KHADGAR_GOSSIP_4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+4); player->SEND_GOSSIP_MENU(9878, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+4: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, KHADGAR_GOSSIP_5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+5); player->SEND_GOSSIP_MENU(9879, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+5: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, KHADGAR_GOSSIP_3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+6); player->SEND_GOSSIP_MENU(9880, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+6: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, KHADGAR_GOSSIP_7, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+7); player->SEND_GOSSIP_MENU(9881, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+7: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, KHADGAR_GOSSIP_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); player->SEND_GOSSIP_MENU(9243, creature->GetGUID()); break; } return true; } bool OnGossipHello(Player* player, Creature* creature) OVERRIDE { if (creature->IsQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); if (player->GetQuestStatus(10211) != QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, KHADGAR_GOSSIP_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); player->SEND_GOSSIP_MENU(9243, creature->GetGUID()); return true; } }; void AddSC_shattrath_city() { new npc_raliq_the_drunk(); new npc_salsalabim(); new npc_shattrathflaskvendors(); new npc_zephyr(); new npc_kservant(); new npc_ishanah(); new npc_khadgar(); }
ProjectSkyfire/SkyFire.548
src/server/scripts/Outland/zone_shattrath_city.cpp
C++
gpl-2.0
16,677
<?php /** * Template Name: Sidebar Left Template * * @package WordPress * @subpackage Invictus * @since Invictus 1.0 */ get_header(); ?> <div id="single-page" class="clearfix left-sidebar"> <div id="primary"> <div id="content" role="main"> <?php the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> </div><!-- #content --> </div><!-- #primary --> <div id="sidebar"> <?php /* Widgetised Area */ if ( !function_exists( 'dynamic_sidebar' ) || !dynamic_sidebar('sidebar-main') ) ?> </div> </div> <?php get_footer(); ?>
iTTemple/html
wp-content/themes/invictus_2.6.2/template-sidebar-left.php
PHP
gpl-2.0
568
// // CRTDispatchConnection.cpp // dyncRTConnector // // Created by hp on 12/8/15. // Copyright (c) 2015 hp. All rights reserved. // #include "CRTDispatchConnection.h" #include "CRTConnManager.h" #include "CRTConnection.h" #include "CRTConnectionTcp.h" #include "rtklog.h" void CRTDispatchConnection::DispatchMsg(const std::string& uid, pms::RelayMsg& r_msg) { //find connector CRTConnManager::ConnectionInfo* pci = CRTConnManager::Instance().findConnectionInfoById(uid); if (!pci) { LE("CRTDispatchConnection::DispatchMsg not find user:%s connection\n", uid.c_str()); LI("CRTDispatchConnection::DispatchMsg handle_cmd:%s, handle_mtype:%s, handle_data:%s\n", r_msg.handle_cmd().c_str(), r_msg.handle_mtype().c_str(), r_msg.handle_data().c_str()); // not set push in this msg if (r_msg.handle_cmd().length()==0 \ || r_msg.handle_cmd().compare("push")!=0 \ || r_msg.handle_data().length()==0 \ || r_msg.handle_data().compare("1")!=0) { LE("CRTDispatchConnection::DispatchMsg this type of message is no need to push, so return\n"); return; } LI("CRTDispatchConnection::DispatchMsg userid:%s, r_msg.cont_module:%d\n\n", uid.c_str(), r_msg.cont_module()); // user set not accept push // user set mute notification if (!CRTConnManager::Instance().CouldPush(uid, r_msg.cont_module())) { LE("CRTDispatchConnection::DispatchMsg user set do not accept push or mute notify, so return\n"); return; } // get redis setting enablepush // find pusher module and sent to pusher CRTConnManager::ModuleInfo* pmodule = CRTConnManager::Instance().findModuleInfo("", pms::ETransferModule::MPUSHER); if (pmodule && pmodule->pModule && pmodule->pModule->IsLiveSession()) { pms::TransferMsg t_msg; //r_msg.set_svr_cmds(cmd); r_msg.set_tr_module(pms::ETransferModule::MCONNECTOR); r_msg.set_connector(CRTConnManager::Instance().ConnectorId()); t_msg.set_type(pms::ETransferType::TQUEUE); t_msg.set_content(r_msg.SerializeAsString()); std::string s = t_msg.SerializeAsString(); pmodule->pModule->SendTransferData(s.c_str(), (int)s.length()); LI("CRTDispatchConnection::DispatchMsg has send push msg to pusher, module type:%d, module id:%s!!!\n\n", pmodule->othModuleType, pmodule->othModuleId.c_str()); } else { LE("CRTDispatchConnection::DispatchMsg module pusher is not liveeeeeeeeeeee!!!\n"); } return; } else { //!pci if (pci->_pConn && pci->_pConn->IsLiveSession()) { if (pci->_connType == pms::EConnType::THTTP) { CRTConnection *c = dynamic_cast<CRTConnection*>(pci->_pConn); if (c) { c->SendDispatch(uid, r_msg.content()); } } else if (pci->_connType == pms::EConnType::TTCP) { CRTConnectionTcp *ct = dynamic_cast<CRTConnectionTcp*>(pci->_pConn); if (ct) { ct->SendDispatch(uid, r_msg.content()); } } } } }
Teameeting/Teameeting-MsgServer
MsgServer/MsgServerConnector/CRTDispatchConnection.cpp
C++
gpl-2.0
3,277
'use strict'; /*@ngInject*/ function repoItemClassifierFilter() { return function(node) { if (node.type) { return 'uib-repository__item--movable'; } else { return 'uib-repository__group'; } }; } module.exports = repoItemClassifierFilter;
raqystyle/ui-builder
frontend/scripts/builder/modules/repository/filters/repoItemClassifier.filter.js
JavaScript
gpl-2.0
268
class ActorEffectActorPen < ActorEffect title 'Actor Pen' description 'Uses chosen actor as a brush tip, rendering it multiple times per frame to smoothly follow a chosen X,Y point.' hint 'This effect is primarily intended for use with the Canvas actor.' categories :canvas setting 'actor', :actor setting 'offset_x', :float, :default => 0.0..1.0 setting 'offset_y', :float, :default => 0.0..1.0 setting 'period', :float, :default => 0.01..1.0 setting 'scale', :float, :default => 1.0..2.0 setting 'alpha', :float, :default => 1.0..1.0, :range => 0.0..1.0 setting 'maximum_per_frame', :integer, :range => 1..1000, :default => 50..1000 def render return yield if scale == 0.0 actor.one { |a| parent_user_object.using { with_alpha(alpha) { prev_x = offset_x_setting.last_value prev_y = offset_y_setting.last_value delta_x = offset_x - prev_x delta_y = offset_y - prev_y prev_scale = scale_setting.last_value delta_scale = (scale - prev_scale) distance = Math.sqrt(delta_x*delta_x + delta_y*delta_y) count = ((distance / scale) / period).floor count = maximum_per_frame if count > maximum_per_frame if count < 2 with_translation(offset_x, offset_y) { with_scale(scale) { a.render! } } else step_x = delta_x / count step_y = delta_y / count step_scale = delta_scale / count beat_delta = $env[:beat_delta] for i in 1..count progress = (i.to_f / count) with_beat_shift(-beat_delta * (1.0 - progress)) { with_translation(prev_x + step_x*i, prev_y + step_y*i) { with_scale(prev_scale + step_scale*i) { a.render! } } } end end } } } yield end end
lighttroupe/luz-next
engine/plugins/actor_effects/actor-pen.luz.rb
Ruby
gpl-2.0
1,787
<?php // (C) Copyright Bobbing Wide 2012, 2017 /** * Determine the reference_type from PHP tokens * * Attempt to determine what sort of API this is using token_get_all() * * @param string $string - the "api" name * @return string - the reference type determined from token_name() * */ function oikai_determine_from_tokens( $string ) { $reference_type = null; $tokens = token_get_all( "<?php $string" ); $token = array_shift( $tokens ); while ( $token ) { $token = array_shift( $tokens ); if ( is_array( $token ) ) { //print_r( $token ); $token_name = token_name( $token[0] ); //$reference_type = _oikai_determine_reference_type( $ $reference_type = $token_name; $token = null; } } return( $reference_type ); } /** * See if this is a constant name * * @param string $string - could be ABSPATH or WPINC or something * * */ function oikai_check_constants( $string ) { $constants = get_defined_constants( false ); //$reference_type = oikai_query_function_type $constant = bw_array_get( $constants, $string, null ); if ( $constant ) { $reference_type = "constant"; } else { $reference_type = "T_STRING"; } return( $reference_type ); } /** * */ function oikai_check_class_method_or_function( $string ) { $reference_type = "T_STRING"; $class = oikai_get_class( $string, null ); if ( $class ) { $func = oikai_get_func( $string, $class ); if ( $func ) { $reference_type = "method"; } else { $reference_type = "class"; } } else { $reference_type = "function"; } return( $reference_type ); } /** * Determine the reference type for a string * * @param string $string - the passed string literal * @return string - the determined reference type * * Value | Meaning * -------- | ------- * internal | This is a PHP function * user | This is a currently active application function * T_STRING | We couldn't decide * constant | It's a defined constant name ( currently active ) * T_ other | It's a PHP token such as T_REQUIRE, T_REQUIRE_ONCE, etc * class | It's a class * function | It's a function - but it's not active otherwise we'd have received "user" or "internal" * method | It's a method ( with class name ) * null | Not expected at the end of this processing */ function oikai_determine_reference_type( $string ) { $reference_type = oikai_determine_function_type( $string ); if ( !$reference_type ) { $reference_type = oikai_determine_from_tokens( $string ); } if ( $reference_type == "T_STRING" ) { $reference_type = oikai_check_constants( $string ); } if ( $reference_type == "T_STRING" ) { $reference_type = oikai_check_class_method_or_function( $string ); } //p( "$string:$reference_type" ); return( $reference_type ); } /** * Handle a link to a "user" function * */ function oikai_handle_reference_type_user( $api, $reference_type ) { $posts = oikai_get_oik_apis_byname( $api ); bw_trace2( $posts ); if ( $posts ) { oikapi_simple_link( $api, $posts ); } else { e( oikai_link_to_wordpress( $api ) ); } e( "()" ); } /** * Handle a link to an "internal" PHP function * * This includes T_xxx values we don't yet cater for * * */ function oikai_handle_reference_type_internal( $api, $reference_type ) { e( oikai_link_to_php( $api )); e( "()" ); } /** * Handle a link to a "function" */ function oikai_handle_reference_type_function( $api, $reference_type ) { oikai_handle_reference_type_user( $api, $reference_type ); } /** * Handle a link to a "class" * */ function oikai_handle_reference_type_class( $api, $reference_type ) { $posts = oikai_get_oik_class_byname( $api ); bw_trace2( $posts ); if ( $posts ) { oikapi_simple_link( $api, $posts ); } else { e( oikai_link_to_wordpress( $api ) ); } } /** * Produce a link to the API based on the reference_type * * @param string $api - the API name * @param string $reference_type - the determined reference type * */ function oikai_handle_reference_type( $api, $reference_type ) { $funcname = bw_funcname( __FUNCTION__, $reference_type ); //e( $funcname ); if ( $funcname != __FUNCTION__ ) { if ( is_callable( $funcname ) ) { call_user_func( $funcname, $api, $reference_type ); } else { fob(); oikai_handle_reference_type_internal( $api, $reference_type ); } } else { oikai_handle_reference_type_internal( $api, $reference_type ); } } /** * Simplify the API name * * Sometimes we write an API as apiname() * If we wrap this in the API shortcode we should be able to cater for the extraneous ()'s * * There could be other things we could also do... such as sanitization * * @param string $api - the given API name * @return string - the simplified API name * */ function oikai_simplify_apiname( $api ) { $api = str_replace( "()", "", $api ); return( $api ); } /** * Implement [api] shortcode to produce simple links to an API * * If there's just one API it's shown as "api()". * If more than one then they're comma separated, but NOT in an HTML list "api(), api2()" * Links are created to PHP, the local site or the 'preferred' WordPress reference site. * * @param array $atts - shortcode parameters * @param string $content - content * @param string $tag - the shortcode tag * @return string - generated HTML * */ function oikai_api( $atts=null, $content=null, $tag=null ) { oiksc_autoload(); $apis = bw_array_get_from( $atts, "api,0", null ); if ( $apis ) { $apia = bw_as_array( $apis ); oik_require( "shortcodes/oik-apilink.php", "oik-shortcodes" ); oik_require( "shortcodes/oik-api-importer.php", "oik-shortcodes" ); $count = 0; foreach ( $apia as $key => $api ) { $api = oikai_simplify_apiname( $api ); if ( $count ) { e( "," ); e( "&nbsp;" ); } $count++; $type = oikai_determine_reference_type( $api ); oikai_handle_reference_type( $api, $type ); } } else { oik_require( "shortcodes/oik-api-status.php", "oik-shortcodes" ); oikai_api_status( $atts ); } return( bw_ret() ); } /** * OK, but we also want to link to PHP stuff * So we need to be able to call that function * */ function oikapi_simple_link( $api, $posts ) { if ( $posts ) { $post = bw_array_get( $posts, 0, null ); } else { $post = null; } if ( $post ) { alink( "bw_api", get_permalink( $post ), $api, $post->title ); } else { e( $api ); } } /** * Help hook for [api] shortcode */ function api__help( $shortcode="api" ) { return( "Simple API link" ); } /** * Syntax hook for [api] shortcode */ function api__syntax( $shortcode="api" ) { $syntax = array( "api|0" => bw_skv( null, "<i>api</i>", "API name" ) ); return( $syntax ); } /** * Example hook for [api] shortcode */ function api__example( $shortcode="api" ) { oik_require( "includes/oik-sc-help.php" ); $text = "Links to different APIs: PHP,locally documented,WordPress reference" ; $example = "require,oik_require,hello_dolly"; bw_invoke_shortcode( $shortcode, $example, $text ); }
bobbingwide/oik-shortcodes
shortcodes/oik-api.php
PHP
gpl-2.0
7,237
<?php /** * Custom Article Page Type * * @package tub */ /* * Register an article post type. */ add_action( 'init', 'tub_articles_init' ); function tub_articles_init() { $labels = array( 'name' => _x( 'Articles', 'post type general name', 'tub' ), 'singular_name' => _x( 'Article', 'post type singular name', 'tub' ), 'menu_name' => _x( 'Articles', 'admin menu', 'tub' ), 'name_admin_bar' => _x( 'Article', 'add new on admin bar', 'tub' ), 'add_new' => _x( 'Add New', 'article', 'tub' ), 'add_new_item' => __( 'Add New Article', 'tub' ), 'new_item' => __( 'New Article', 'tub' ), 'edit_item' => __( 'Edit Article', 'tub' ), 'view_item' => __( 'View Article', 'tub' ), 'all_items' => __( 'All Articles', 'tub' ), 'search_items' => __( 'Search Articles', 'tub' ), 'parent_item_colon' => __( 'Parent Articles:', 'tub' ), 'not_found' => __( 'No articles found.', 'tub' ), 'not_found_in_trash' => __( 'No articles found in Trash.', 'tub' ) ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_nav_menus' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'article' ), 'capability_type' => 'page', 'hierarchical' => true, 'menu_position' => 20, 'menu_icon' => 'dashicons-format-aside', 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'revisions', 'page-attributes' ) ); register_post_type( 'article', $args ); } /** * Change Title Placeholder Text */ function tub_change_article_title( $title ){ $screen = get_current_screen(); if ( 'article' == $screen->post_type ){ $title = 'Enter menu label here'; } return $title; } add_filter( 'enter_title_here', 'tub_change_article_title' ); /** * Add a page title meta box */ // Add box function tub_article_add_title(){ add_meta_box( 'article_title_meta', __('Page Title'), 'tub_article_title_content', 'article', 'normal', 'high' ); } add_action("add_meta_boxes", "tub_article_add_title"); // Print box content function tub_article_title_content( $post ){ // Add an nonce field so we can check for it later. wp_nonce_field( 'tub_article_meta_box', 'tub_article_meta_box_nonce' ); $article_title = get_post_meta( $post->ID, 'tub_article_title', true ); echo '<input type="text" name="tub_article_title" value="' . esc_attr( $article_title ) . '" style="width: 100%;margin-top: 6px;" placeholder="Enter title here" />'; } /** * Save Data */ function tub_article_title_save( $post_id ) { /* * We need to verify this came from our screen and with proper authorization, * because the save_post action can be triggered at other times. */ // Check if our nonce is set. if ( ! isset( $_POST['tub_article_meta_box_nonce'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['tub_article_meta_box_nonce'], 'tub_article_meta_box' ) ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } // Check the user's permissions. if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } /* OK, it's safe for us to save the data now. */ // Save testimonial date data if the field isset if ( isset( $_POST['tub_article_title'] ) ) { $tub_article_title_data = sanitize_text_field( $_POST['tub_article_title'] ); update_post_meta( $post_id, 'tub_article_title', $tub_article_title_data ); } return; } add_action( 'save_post', 'tub_article_title_save' );
joshevensen/theunassistedbaby.com
wp-content/plugins/tub-functions/cpt/articles.php
PHP
gpl-2.0
4,026
<?php include_once "../libs/myLib.php"; if (!isset($_SESSION['login'])) { session_start(); } $nombre = $_POST['nombre']; $fechaInicio= $_POST['fechaInicio']; $horaInicio = $_POST['horaInicio']; $fechaFin = $_POST['fechaInicio']; $horaFin = $_POST['horaFin']; $precio = $_POST['precio']; $plazas = $_POST['plazas']; $descripcion = $_POST['descripcion']; $requisitos = $_POST['requisitos']; $imagen = "assets/img/evento.png"; $empresa = ""; $usuario = ""; $fechaI = $fechaInicio.' '.$horaInicio; $fechaF = $fechaFin.' '.$horaFin; $todoInicio = date('Y-m-d H:i:s', strtotime($fechaI)); $todoFin = date('Y-m-d H:i:s', strtotime($fechaF)); $salir = false; if ($_POST['empresa'] != "" && $_POST['usuario'] == ""){ $empresa = $_POST['empresa']; $sql = "INSERT INTO evento (nombre,fechaInicio,fechaFin,precio,plazas,descripcion,requisitos,empresa,imagen) VALUES ('$nombre','$todoInicio','$todoFin','$precio','$plazas','$descripcion','$requisitos','$empresa','$imagen')"; } else if ($_POST['empresa'] == "" && $_POST['usuario'] != ""){ $usuario = $_POST['usuario']; $sql = "INSERT INTO evento (nombre,fechaInicio,fechaFin,precio,plazas,descripcion,requisitos,usuario,imagen) VALUES ('$nombre','$todoInicio','$todoFin','$precio','$plazas','$descripcion','$requisitos','$usuario','$imagen')"; } else { $salir = true; } if (!$salir) { $conexion = dbConnect(); $resultado = mysqli_query($conexion, $sql); if ($resultado) { if (isset($_FILES['imagen']) && $_FILES['imagen']['name']) { $subidaCorrecta = false; $sql = "SELECT id FROM evento WHERE id=@@Identity"; $resultado = mysqli_query($conexion, $sql); $row = mysqli_fetch_array($resultado); $id = $row['id']; if ($_FILES['imagen']['error'] > 0) { salir2("Ha ocurrido un error en la carga de la imagen", -1, "gestionarEventos.php"); } else { $extensiones = array("image/jpg", "image/jpeg", "image/png"); $limite = 4096; if (in_array($_FILES['imagen']['type'], $extensiones) && $_FILES['imagen']['size'] < $limite * 1024) { $foldername = "assets/img/eventos"; $foldermkdir = "../" . $foldername; if (!is_dir($foldermkdir)) { mkdir($foldermkdir, 0777, true); } $extension = "." . split("/", $_FILES['imagen']['type'])[1]; $filename = $id . $extension; $ruta = $foldername . "/" . $filename; $rutacrear = $foldermkdir . "/" . $filename; if (!file_exists($rutacrear)) { $subidaCorrecta = @move_uploaded_file($_FILES['imagen']['tmp_name'], $rutacrear); $imagen = $ruta; } } if ($subidaCorrecta) { $sql = "UPDATE evento SET imagen='$imagen' WHERE id=$id"; $resultado = mysqli_query($conexion, $sql); mysqli_close($conexion); if ($resultado) { salir2("Evento añadido correctamente", 0, "gestionarEventos.php"); } else { salir2("Ha ocurrido un error con la imagen", -1, "gestionarEventos.php"); } } else { // No se ha subido la imagen mysqli_close($conexion); salir2("Ha ocurrido un error subiendo la imagen", -1, "gestionarEventos.php"); } } } else { // No hay imagen mysqli_close($conexion); salir2("Evento añadido correctamente", 0, "gestionarEventos.php"); } } else { // Fallo en INSERT mysqli_close($conexion); salir2("Error añadiendo el evento", -1, "gestionarEventos.php"); } } else { salir2("No se ha introducido correctamente el organizador", -1, "gestionarEventos.php"); } ?>
fblupi/grado_informatica-DIU
G-Tech/scripts/crearEvento.php
PHP
gpl-2.0
3,659
/* * This file is part of the OregonCore Project. See AUTHORS file for Copyright information * * 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 <https://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Moam SD%Complete: 100 SDComment: VERIFY SCRIPT AND SQL SDCategory: Ruins of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #define EMOTE_AGGRO -1509000 #define EMOTE_MANA_FULL -1509001 #define SPELL_TRAMPLE 15550 #define SPELL_DRAINMANA 27256 #define SPELL_ARCANEERUPTION 25672 #define SPELL_SUMMONMANA 25681 #define SPELL_GRDRSLEEP 24360 //Greater Dreamless Sleep struct boss_moamAI : public ScriptedAI { boss_moamAI(Creature* c) : ScriptedAI(c) {} Unit* pTarget; uint32 TRAMPLE_Timer; uint32 DRAINMANA_Timer; uint32 SUMMONMANA_Timer; uint32 i; uint32 j; void Reset() { i = 0; j = 0; pTarget = NULL; TRAMPLE_Timer = 30000; DRAINMANA_Timer = 30000; } void EnterCombat(Unit* who) { DoScriptText(EMOTE_AGGRO, me); pTarget = who; } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; //If we are 100%MANA cast Arcane Erruption //if (j == 1 && me->GetMana()*100 / me->GetMaxMana() == 100 && !me->IsNonMeleeSpellCast(false)) { DoCastVictim(SPELL_ARCANEERUPTION); DoScriptText(EMOTE_MANA_FULL, me); } //If we are <50%HP cast MANA FIEND (Summon Mana) and Sleep //if (i == 0 && me->GetHealth()*100 / me->GetMaxHealth() <= 50 && !me->IsNonMeleeSpellCast(false)) { i = 1; DoCastVictim(SPELL_SUMMONMANA); DoCastVictim(SPELL_GRDRSLEEP); } //SUMMONMANA_Timer if (i == 1 && SUMMONMANA_Timer <= diff) { DoCastVictim(SPELL_SUMMONMANA); SUMMONMANA_Timer = 90000; } else SUMMONMANA_Timer -= diff; //TRAMPLE_Timer if (TRAMPLE_Timer <= diff) { DoCastVictim(SPELL_TRAMPLE); j = 1; TRAMPLE_Timer = 30000; } else TRAMPLE_Timer -= diff; //DRAINMANA_Timer if (DRAINMANA_Timer <= diff) { DoCastVictim(SPELL_DRAINMANA); DRAINMANA_Timer = 30000; } else DRAINMANA_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_moam(Creature* pCreature) { return new boss_moamAI (pCreature); } void AddSC_boss_moam() { Script* newscript; newscript = new Script; newscript->Name = "boss_moam"; newscript->GetAI = &GetAI_boss_moam; newscript->RegisterSelf(); }
OregonCore/OregonCore
src/scripts/Kalimdor/RuinsOfAhnQiraj/boss_moam.cpp
C++
gpl-2.0
3,347
/* * Copyright (c) 2006 - 2012 LinogistiX GmbH * * www.linogistix.com * * Project myWMS-LOS */ package de.linogistix.los.reference.customization.common; import javax.ejb.Stateless; import de.linogistix.los.customization.LOSEventConsumerBean; import de.linogistix.los.util.event.LOSEventConsumer; /** * @author krane * */ @Stateless public class Ref_EventConsumerBean extends LOSEventConsumerBean implements LOSEventConsumer { }
Jacksson/mywmsnb
mywms.as/project-ejb/src/java/de/linogistix/los/reference/customization/common/Ref_EventConsumerBean.java
Java
gpl-2.0
446
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://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 "fix_nve.h" #include "atom.h" #include "error.h" #include "force.h" #include "respa.h" #include "update.h" using namespace LAMMPS_NS; using namespace FixConst; /* ---------------------------------------------------------------------- */ FixNVE::FixNVE(LAMMPS *lmp, int narg, char **arg) : Fix(lmp, narg, arg) { if (!utils::strmatch(style,"^nve/sphere") && narg < 3) error->all(FLERR,"Illegal fix nve command"); dynamic_group_allow = 1; time_integrate = 1; } /* ---------------------------------------------------------------------- */ int FixNVE::setmask() { int mask = 0; mask |= INITIAL_INTEGRATE; mask |= FINAL_INTEGRATE; mask |= INITIAL_INTEGRATE_RESPA; mask |= FINAL_INTEGRATE_RESPA; return mask; } /* ---------------------------------------------------------------------- */ void FixNVE::init() { dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; if (utils::strmatch(update->integrate_style,"^respa")) step_respa = ((Respa *) update->integrate)->step; } /* ---------------------------------------------------------------------- allow for both per-type and per-atom mass ------------------------------------------------------------------------- */ void FixNVE::initial_integrate(int /*vflag*/) { double dtfm; // update v and x of atoms in group double **x = atom->x; double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int *mask = atom->mask; int nlocal = atom->nlocal; if (igroup == atom->firstgroup) nlocal = atom->nfirst; if (rmass) { for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) { dtfm = dtf / rmass[i]; v[i][0] += dtfm * f[i][0]; v[i][1] += dtfm * f[i][1]; v[i][2] += dtfm * f[i][2]; x[i][0] += dtv * v[i][0]; x[i][1] += dtv * v[i][1]; x[i][2] += dtv * v[i][2]; } } else { for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) { dtfm = dtf / mass[type[i]]; v[i][0] += dtfm * f[i][0]; v[i][1] += dtfm * f[i][1]; v[i][2] += dtfm * f[i][2]; x[i][0] += dtv * v[i][0]; x[i][1] += dtv * v[i][1]; x[i][2] += dtv * v[i][2]; } } } /* ---------------------------------------------------------------------- */ void FixNVE::final_integrate() { double dtfm; // update v of atoms in group double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int *mask = atom->mask; int nlocal = atom->nlocal; if (igroup == atom->firstgroup) nlocal = atom->nfirst; if (rmass) { for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) { dtfm = dtf / rmass[i]; v[i][0] += dtfm * f[i][0]; v[i][1] += dtfm * f[i][1]; v[i][2] += dtfm * f[i][2]; } } else { for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) { dtfm = dtf / mass[type[i]]; v[i][0] += dtfm * f[i][0]; v[i][1] += dtfm * f[i][1]; v[i][2] += dtfm * f[i][2]; } } } /* ---------------------------------------------------------------------- */ void FixNVE::initial_integrate_respa(int vflag, int ilevel, int /*iloop*/) { dtv = step_respa[ilevel]; dtf = 0.5 * step_respa[ilevel] * force->ftm2v; // innermost level - NVE update of v and x // all other levels - NVE update of v if (ilevel == 0) initial_integrate(vflag); else final_integrate(); } /* ---------------------------------------------------------------------- */ void FixNVE::final_integrate_respa(int ilevel, int /*iloop*/) { dtf = 0.5 * step_respa[ilevel] * force->ftm2v; final_integrate(); } /* ---------------------------------------------------------------------- */ void FixNVE::reset_dt() { dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; }
rbberger/lammps
src/fix_nve.cpp
C++
gpl-2.0
4,538
<?php /** * @file * Zen theme's implementation for comments. * * Available variables: * - $author: Comment author. Can be link or plain text. * - $content: An array of comment items. Use render($content) to print them all, or * print a subset such as render($content['field_example']). Use * hide($content['field_example']) to temporarily suppress the printing of a * given element. * - $created: Formatted date and time for when the comment was created. * Preprocess functions can reformat it by calling format_date() with the * desired parameters on the $comment->created variable. * - $pubdate: Formatted date and time for when the comment was created wrapped * in a HTML5 time element. * - $changed: Formatted date and time for when the comment was last changed. * Preprocess functions can reformat it by calling format_date() with the * desired parameters on the $comment->changed variable. * - $new: New comment marker. * - $permalink: Comment permalink. * - $submitted: Submission information created from $author and $created during * template_preprocess_comment(). * - $picture: Authors picture. * - $signature: Authors signature. * - $status: Comment status. Possible values are: * comment-unpublished, comment-published or comment-preview. * - $title: Linked title. * - $classes: String of classes that can be used to style contextually through * CSS. It can be manipulated through the variable $classes_array from * preprocess functions. The default values can be one or more of the following: * - comment: The current template type, i.e., "theming hook". * - comment-by-anonymous: Comment by an unregistered user. * - comment-by-node-author: Comment by the author of the parent node. * - comment-preview: When previewing a new or edited comment. * - first: The first comment in the list of displayed comments. * - last: The last comment in the list of displayed comments. * - odd: An odd-numbered comment in the list of displayed comments. * - even: An even-numbered comment in the list of displayed comments. * The following applies only to viewers who are registered users: * - comment-unpublished: An unpublished comment visible only to administrators. * - comment-by-viewer: Comment by the user currently viewing the page. * - comment-new: New comment since the last visit. * - $title_prefix (array): An array containing additional output populated by * modules, intended to be displayed in front of the main title tag that * appears in the template. * - $title_suffix (array): An array containing additional output populated by * modules, intended to be displayed after the main title tag that appears in * the template. * * These two variables are provided for context: * - $comment: Full comment object. * - $node: Node object the comments are attached to. * * Other variables: * - $classes_array: Array of html class attribute values. It is flattened * into a string within the variable $classes. * * @see template_preprocess() * @see template_preprocess_comment() * @see zen_preprocess_comment() * @see template_process() * @see theme_comment() */ ?> <article class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>> <header> <p class="submitted"> <?php print 'Dodany przez '.$author.' <i>(dnia: '.format_date($node->created, 'custom', 'd.m.Y').')</i>'; ?> </p> <?php print render($title_prefix); ?> <?php if ($title): ?> <h3<?php print $title_attributes; ?>> <?php print $title; ?> <?php if ($new): ?> <mark class="new"><?php print $new; ?></mark> <?php endif; ?> </h3> <?php elseif ($new): ?> <mark class="new"><?php print $new; ?></mark> <?php endif; ?> <?php print render($title_suffix); ?> <?php if ($status == 'comment-unpublished'): ?> <p class="unpublished"><?php print t('Unpublished'); ?></p> <?php endif; ?> </header> <?php // We hide the comments and links now so that we can render them later. hide($content['links']); print render($content); ?> <?php if ($signature): ?> <footer class="user-signature clearfix"> <?php print $signature; ?> </footer> <?php endif; ?> <?php print render($content['links']) ?> </article><!-- /.comment -->
codialsoftware/hunting-project
themes/zen/zen/templates/comment.tpl.php
PHP
gpl-2.0
4,351
<?php namespace Drupal\commerce_order; use Drupal\commerce_price\Price; /** * Represents an adjustment. */ final class Adjustment { /** * The adjustment type. * * @var string */ protected $type; /** * The adjustment label. * * @var string */ protected $label; /** * The adjustment amount. * * @var \Drupal\commerce_price\Price */ protected $amount; /** * The adjustment percentage. * * @var string */ protected $percentage; /** * The source identifier of the adjustment. * * Points to the source object, if known. For example, a promotion entity for * a discount adjustment. * * @var string */ protected $sourceId; /** * Whether the adjustment is included in the base price. * * @var bool */ protected $included = FALSE; /** * Whether the adjustment is locked. * * @var bool */ protected $locked = FALSE; /** * Constructs a new Adjustment object. * * @param array $definition * The definition. */ public function __construct(array $definition) { foreach (['type', 'label', 'amount'] as $required_property) { if (empty($definition[$required_property])) { throw new \InvalidArgumentException(sprintf('Missing required property %s.', $required_property)); } } if (!$definition['amount'] instanceof Price) { throw new \InvalidArgumentException(sprintf('Property "amount" should be an instance of %s.', Price::class)); } $adjustment_type_manager = \Drupal::service('plugin.manager.commerce_adjustment_type'); $types = $adjustment_type_manager->getDefinitions(); if (empty($types[$definition['type']])) { throw new \InvalidArgumentException(sprintf('%s is an invalid adjustment type.', $definition['type'])); } if (!empty($definition['percentage'])) { if (is_float($definition['percentage'])) { throw new \InvalidArgumentException(sprintf('The provided percentage "%s" must be a string, not a float.', $definition['percentage'])); } if (!is_numeric($definition['percentage'])) { throw new \InvalidArgumentException(sprintf('The provided percentage "%s" is not a numeric value.', $definition['percentage'])); } } // Assume that 'custom' adjustments are always locked, for BC reasons. if ($definition['type'] == 'custom' && !isset($definition['locked'])) { $definition['locked'] = TRUE; } $this->type = $definition['type']; $this->label = (string) $definition['label']; $this->amount = $definition['amount']; $this->percentage = !empty($definition['percentage']) ? $definition['percentage'] : NULL; $this->sourceId = !empty($definition['source_id']) ? $definition['source_id'] : NULL; $this->included = !empty($definition['included']); $this->locked = !empty($definition['locked']); } /** * Gets the adjustment type. * * @return string * The adjustment type. */ public function getType() { return $this->type; } /** * Gets the adjustment label. * * @return string * The adjustment label. */ public function getLabel() { return $this->label; } /** * Gets the adjustment amount. * * @return \Drupal\commerce_price\Price * The adjustment amount. */ public function getAmount() { return $this->amount; } /** * Gets whether the adjustment is positive. * * @return bool * TRUE if the adjustment is positive, FALSE otherwise. */ public function isPositive() { return $this->amount->getNumber() >= 0; } /** * Gets whether the adjustment is negative. * * @return bool * TRUE if the adjustment is negative, FALSE otherwise. */ public function isNegative() { return $this->amount->getNumber() < 0; } /** * Gets the adjustment percentage. * * @return string|null * The percentage as a decimal. For example, "0.2" for a 20% adjustment. * Otherwise NULL, if the adjustment was not calculated from a percentage. */ public function getPercentage() { return $this->percentage; } /** * Get the source identifier. * * @return string * The source identifier. */ public function getSourceId() { return $this->sourceId; } /** * Gets whether the adjustment is included in the base price. * * @return bool * TRUE if the adjustment is included in the base price, FALSE otherwise. */ public function isIncluded() { return $this->included; } /** * Gets whether the adjustment is locked. * * Locked adjustments are not removed during the order refresh process. * * @return bool * TRUE if the adjustment is locked, FALSE otherwise. */ public function isLocked() { return $this->locked; } /** * Gets the array representation of the adjustment. * * @return array * The array representation of the adjustment. */ public function toArray() { return [ 'type' => $this->type, 'label' => $this->label, 'amount' => $this->amount, 'percentage' => $this->percentage, 'source_id' => $this->sourceId, 'included' => $this->included, 'locked' => $this->locked, ]; } /** * Adds the given adjustment to the current adjustment. * * @param \Drupal\commerce_order\Adjustment $adjustment * The adjustment. * * @return static * The resulting adjustment. */ public function add(Adjustment $adjustment) { $this->assertSameType($adjustment); $this->assertSameSourceId($adjustment); $definition = [ 'amount' => $this->amount->add($adjustment->getAmount()), ] + $this->toArray(); return new static($definition); } /** * Subtracts the given adjustment from the current adjustment. * * @param \Drupal\commerce_order\Adjustment $adjustment * The adjustment. * * @return static * The resulting adjustment. */ public function subtract(Adjustment $adjustment) { $this->assertSameType($adjustment); $this->assertSameSourceId($adjustment); $definition = [ 'amount' => $this->amount->subtract($adjustment->getAmount()), ] + $this->toArray(); return new static($definition); } /** * Multiplies the adjustment amount by the given number. * * @param string $number * The number. * * @return static * The resulting adjustment. */ public function multiply($number) { $definition = [ 'amount' => $this->amount->multiply($number), ] + $this->toArray(); return new static($definition); } /** * Divides the adjustment amount by the given number. * * @param string $number * The number. * * @return static * The resulting adjustment. */ public function divide($number) { $definition = [ 'amount' => $this->amount->divide($number), ] + $this->toArray(); return new static($definition); } /** * Asserts that the given adjustment's type matches the current one. * * @param \Drupal\commerce_order\Adjustment $adjustment * The adjustment to compare. * * @throws \InvalidArgumentException * Thrown when the adjustment type does not match the current one. */ protected function assertSameType(Adjustment $adjustment) { if ($this->type != $adjustment->getType()) { throw new \InvalidArgumentException(sprintf('Adjustment type "%s" does not match "%s".', $adjustment->getType(), $this->type)); } } /** * Asserts that the given adjustment's source ID matches the current one. * * @param \Drupal\commerce_order\Adjustment $adjustment * The adjustment to compare. * * @throws \InvalidArgumentException * Thrown when the adjustment source ID does not match the current one. */ protected function assertSameSourceId(Adjustment $adjustment) { if ($this->sourceId != $adjustment->getSourceId()) { throw new \InvalidArgumentException(sprintf('Adjustment source ID "%s" does not match "%s".', $adjustment->getSourceId(), $this->sourceId)); } } }
nmacd85/drupal-nicoledawn
modules/contrib/commerce/modules/order/src/Adjustment.php
PHP
gpl-2.0
8,130
/* * blockio.cc * * */ #define _LARGEFILE_SOURCE #define _FILE_OFFSET_BITS 64 #include "version.h" #include "blockio.h" #include "osutils.h" #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdint.h> __ID("@(#) $Id: blockio.cc 2069 2009-02-12 22:53:09Z lyonel $"); ssize_t readlogicalblocks(source & s, void * buffer, long long pos, long long count) { long long result = 0; memset(buffer, 0, count*s.blocksize); /* attempt to read past the end of the section */ if((s.size>0) && ((pos+count)*s.blocksize>s.size)) return 0; result = lseek(s.fd, s.offset + pos*s.blocksize, SEEK_SET); if(result == -1) return 0; result = read(s.fd, buffer, count*s.blocksize); if(result!=count*s.blocksize) return 0; else return count; }
kaseya/lshw
src/core/blockio.cc
C++
gpl-2.0
891
/* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2012 Ph.Waeber * * 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 only. * * 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. */ package net.pms.medialibrary.commons.dataobjects; import net.pms.medialibrary.commons.enumarations.ThumbnailPrioType; public class DOThumbnailPriority { private long id; private ThumbnailPrioType thumbnailPriorityType; private String picturePath; private int seekPosition; private int priorityIndex; public DOThumbnailPriority(){ this(-1, ThumbnailPrioType.THUMBNAIL, "", 0); } public DOThumbnailPriority(long id, ThumbnailPrioType thumbnailPriorityType, String picturePath, int priorityIndex){ this(id, thumbnailPriorityType, -1, picturePath, priorityIndex); } public DOThumbnailPriority(long id, ThumbnailPrioType thumbnailPriorityType, int seekPosition, int priorityIndex){ this(id, thumbnailPriorityType, seekPosition, "", priorityIndex); } public DOThumbnailPriority(long id, ThumbnailPrioType thumbnailPriorityType, int seekPosition, String picturePath, int priorityIndex){ setId(id); setThumbnailPriorityType(thumbnailPriorityType); setSeekPosition(seekPosition); setPicturePath(picturePath); setPriorityIndex(priorityIndex); } public void setThumbnailPriorityType(ThumbnailPrioType thumbnailPriorityType) { this.thumbnailPriorityType = thumbnailPriorityType; } public ThumbnailPrioType getThumbnailPriorityType() { return thumbnailPriorityType; } public void setPicturePath(String picturePath) { this.picturePath = picturePath; } public String getPicturePath() { return picturePath; } public void setSeekPosition(int seekPosition) { this.seekPosition = seekPosition; } public int getSeekPosition() { return seekPosition; } public void setPriorityIndex(int priorityIndex) { this.priorityIndex = priorityIndex; } public int getPriorityIndex() { return priorityIndex; } public void setId(long id) { this.id = id; } public long getId() { return id; } @Override public boolean equals(Object obj){ if(!(obj instanceof DOThumbnailPriority)){ return false; } DOThumbnailPriority compObj = (DOThumbnailPriority) obj; if(getId() == compObj.getId() && getThumbnailPriorityType() == compObj.getThumbnailPriorityType() && getPicturePath().equals(compObj.getPicturePath()) && getSeekPosition() == compObj.getSeekPosition() && getPriorityIndex() == compObj.getPriorityIndex()){ return true; } return false; } @Override public int hashCode(){ int hashCode = 24 + String.valueOf(getId()).hashCode(); hashCode *= 24 + getPicturePath().hashCode(); hashCode *= 24 + getSeekPosition(); hashCode *= 24 + getPriorityIndex(); return hashCode; } @Override public DOThumbnailPriority clone(){ return new DOThumbnailPriority(getId(), getThumbnailPriorityType(), getSeekPosition(), getPicturePath(), getPriorityIndex()); } @Override public String toString(){ return String.format("id=%s, prioIndex=%s, type=%s, seekPos=%s, picPath=%s", getId(), getPriorityIndex(), getThumbnailPriorityType(), getSeekPosition(), getPicturePath()); } }
taconaut/pms-mlx
core/src/main/java/net/pms/medialibrary/commons/dataobjects/DOThumbnailPriority.java
Java
gpl-2.0
3,813
package cmd import ( "github.com/spf13/cobra" ) // rotateCmd represents the shuffletips command var rotateCmd = &cobra.Command{ Use: "rotate", Short: "Rotates children of internal nodes", Long: `Rotates children of internal nodes by different means. Either randomly with "rand" subcommand, either sorting by number of tips with "sort" subcommand. It does not change the topology, but just the order of neighbors of all node and thus the newick representation. ------C ------A x |z x |z A---------*ROOT => B---------*ROOT |t |t ------B ------C Example of usage: gotree rotate rand -i t.nw gotree rotate sort -i t.nw `, } func init() { RootCmd.AddCommand(rotateCmd) rotateCmd.PersistentFlags().StringVarP(&intreefile, "input", "i", "stdin", "Input tree") rotateCmd.PersistentFlags().StringVarP(&outtreefile, "output", "o", "stdout", "Rotated tree output file") }
fredericlemoine/gotree
cmd/rotate.go
GO
gpl-2.0
1,028
<?php include_once('sites/all/themes/artonair/custom_functions/custom_variable.php'); /* mp3 folder path */ ?> <?php include_once('sites/all/themes/artonair/custom_functions/default_image.php'); /* function for displaying default images */ ?> <?php $listen_url = "/drupal/play/" . $node->nid . "/" . $node->path; ?> <?php global $base_url; $vgvr = views_get_view_result('archive_popular', 'default'); $node_status = ""; foreach($vgvr as $vresult) { if($vresult->nid == $node->nid) $node_status = "Popular!"; } ?> <div class="<?php print $node->type; ?>-body bodyview <?php foreach($node->taxonomy as $term) { $your_vocabulary_id = 108; if ($term->vid == $your_vocabulary_id) { print $term->name; } } ?>"> <div class="content-section"> <div class="left-column" id="header-info"> <div class="header"> <div class="info"> <?php // if($node->field_series[0]['view']) { ?> <!-- <h6 class="type"> <span><?php// print l("Radio Show", "radio"); ?></span>ABC</h6> <h6 class="dates"><?php //print $node->field_series[0]['view']; ?></h6>--> <?php // } ?> <?php // if($node->type == "series") { ?> <!-- <span><?php // print l("Radio Series", "radio/series"); ?></span><?php $view = views_get_view('series_contents'); $args = array($node->nid); $view->set_display('default', $args); // like 'block_1' $view->render(); ?> <div class="episode-count"><?php // print sizeof($view->result);?> Episodes</div> <?php // } ?> --> <?php // if($node->type == "news") { ?> <!-- <span><?php // print l("Radio", "radio"); ?></span>Featured Shows This Week --> <?php // } ?> <?php if($node->type == "blog") { ?> <h6 class="type"><span><?php print l("News", "news"); ?></span></h6> <h6 class="dates"> <?php foreach($node->taxonomy as $term) { $your_vocabulary_id = 108; if ($term->vid == $your_vocabulary_id) { print $term->name; } } ?></h6> <?php } ?> <?php if($node->type == "host") { ?> <span><?php print l("People", "radio/hosts"); ?></span><?php $view = views_get_view('series_contents'); $args = array($node->nid); $view->set_display('default', $args); // like 'block_1' $view->render(); ?> <div class="episode-count"><?php print sizeof($view->result);?> Programs</div> <?php } ?> </h6><!-- /.type --> <?php if($node->type != "news") { ?> <div class="title"> <h1><?php print $node->title; ?></h1> </div><!-- /.title --> <?php } ?> <?php if($node->field_host[0]['view']) { ?> <h6 class="hosts"> Hosted by <?php $hostno = 0; foreach ($node->field_host as $one_host) { ?> <?php if($hostno > 0) print "<span class='comma'>,</a>"; ?> <span class="host"><?php print $one_host['view']; ?></span> <?php $hostno++; } ?> </h6> <?php } ?> <?php if(!empty($node->field_host_type[0]['view'])) { ?> <h6 class="host-types"> <?php $hosttypesno = 0; foreach ($node->field_host_type as $one_host_type) { ?> <?php if($hosttypesno > 0) print "<span class='comma'>,</a>"; ?> <span class="host-type"><?php print $one_host_type['view']; ?></span> <?php $hosttypesno++; } ?> </h6> <?php } ?> </div> <!-- /.info --> </div><!-- /.header --> </div> <!-- left-column --> <?php if($node->type != "news") { ?> <?php if($node->field_image[0]['view']) { ?> <div class="right-column"> <div class="header-image"> <div class="image"><?php print $node->field_image[0]['view']; ?> </div> <div class="image-description"><?php print $node->field_image[0]['data']['description']; ?> </div> </div><!-- /.header-image --> </div><!-- /.right-column --> <div class="left-column" id="node-content"> <?php } else { ?> <div class="single-column" id="node-content"> <?php } ?> <?php } ?> <!--<div class="left-column" id="node-content">--> <?php if ($node->taxonomy[13701]) { ?> <?php if($node->field_media_embed[0]['view']) { ?> <div class="video"><?php print $node->field_media_embed[0]['view']; ?></div> <?php } ?> <?php } ?> <?php if($node->type == "series") { ?> <?php print views_embed_view('also_in_this_series', 'series_listen', $node->nid); ?> <!-- <div class="plus-button"><?php // print $_COOKIE["air-playlist"]; ?></div>--> <?php } ?> <?php if($node->type != "news") { ?> <div class="share listen"> <?php if($node->field_audio_path[0]['safe']) { ?> <div class="play"> <div class="listen-button"> <a href="<?php print $listen_url; ?>" onclick="popUpAIR(this.href,'fixed', 440, 570); return false;" target="artonair_music_popup"><img src="<?php print $base_url; ?>/sites/all/themes/artonair/images/triangle-white.png"></a> </div> <div class="listen-text"><a href="<?php print $listen_url; ?>" onclick="popUpAIR(this.href,'fixed', 440, 570); return false;" target="artonair_music_popup">Listen</a> </div> <!-- /.listen-button --> </div><!-- /.listen --> <div class="plus-button"><?php print $_COOKIE["air-playlist"]; ?></div> <?php } ?> <div class="social"> <div class="addthis_toolbox addthis_default_style facebook"><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a></div> <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=xa-520a6a3258c56e49"></script> <div class="twitter"> <a href="https://twitter.com/share" class="twitter-share-button" data-via="clocktower_nyc">Tweet</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> </div><!-- /.twitter --> </div> <!-- /.social --> </div><!-- /.share .listen --> <div class="content"> <?php print $node->content['body']['#value']; ?> <?php if($node->field_long_description[0]['view']) { ?> <?php print $node->field_long_description[0]['view']; ?> <?php } ?> <div class="content-foot"> <?php if($node->field_support[0]['view']) { ?> <em><?php print $node->field_support[0]['view']; ?></em> <?php } ?> <?php if($node->type == "blog") { ?> <h6 class="dates">Posted <?php print format_date($created, 'custom', 'F d, Y')?></h6> <?php } ?> <?php if($node->type == "show") { ?> <?php if($node->field_aired_date[0]['view']) { ?> <h6 class="aired_date">Originally aired <span class="aired_date_itself"><?php print $node->field_aired_date[0]['view']; ?></span></h6> <?php } ?> <div class="tags"> <h6 class="category"><?php print views_embed_view("radio_categories", "radio_tags", $node->nid); ?></h6> </div> <?php } ?> <?php if($node->type == "series") { ?> <h6 class="aired_date"><?php print views_embed_view('also_in_this_series', 'series_updated', $node->nid); ?></h6> <div class="tags"> <h6 class="category"><?php print views_embed_view("radio_categories", "radio_tags", $node->nid); ?></h6> </div> <?php } ?> <?php } ?> <?php if($node->type == "blog") { ?> <div class="tags"> <h6 class="category"><?php print views_embed_view("radio_categories", "radio_tags", $node->nid); ?></h6> </div> <?php } ?> </div><!-- /.content-foot --> </div><!-- /.content --> </div><!-- /.left-column --> <div class="right-column"> <div class="image-gallery"> <?php if($node->field_image[12]['view']) { ?> <div class="thumbnails three"> <?php print views_embed_view('exhibition_thumbnails_slider', 'default', $node->nid); ?> </div> <?php } else { ?> <?php if($node->field_image[1]['view']) { ?> <div class="thumbnails"> <?php print views_embed_view('exhibition_thumbnails_slider', 'default', $node->nid); ?> </div> <?php } ?> <?php } ?> </div><!-- /.image-gallery --> </div><!-- /.right-column --> </div><!-- /.bodyview --> <?php if($node->type == "news") { ?> <div class="in_this_news masonry"> <div class="news-body"> <?php print views_embed_view("new_this_week", "front_news_text", $node->nid); ?> </div> <div class="featured_projects" style="display:none;visibility:hidden;"> <?php print views_embed_view("in_this_news", "default", $node->nid); ?> </div> <div class="featured_radio" style="display:none;visibility:hidden;"> <?php print views_embed_view("in_this_news", "featured_radio", $node->nid); ?> </div> <div class="soundcloud item"> <?php $block = (object) module_invoke('block', 'block', 'view', "60"); print theme('block',$block); ?> </div> <div class="subscribe item"> <?php $block = (object) module_invoke('block', 'block', 'view', "42"); print theme('block',$block); ?> </div> </div><!-- /.in-this-news --> <?php } ?> <?php if($node->type != "news") { ?> <?php $tags_display = views_embed_view('tags_for_node', 'default', $node->nid); ?> <?php } ?> <?php if($node->type == "blog") { ?> <div class="also-list related"> <?php print views_embed_view('clocktower_related_radio', 'related_to_event', $node->nid); ?> </div> <!-- also-list --> <?php } ?> <?php if($node->type == "show" && $node->field_series[0]['view']) { ?> <div class="also-list masonry"> <div class="title item"> <h6>Other Episodes From</h6> <h1><?php print $node->field_series[0]['view']; ?></h1> </div> <div class="series-contents"> <?php print views_embed_view('also_in_this_series', 'grid_related_shows', $node->field_series[0]['nid'], $node->nid); ?> </div> </div><!-- also-list --> <div class="also-list"> <div class="block block-staffpicks"> <?php $view = views_get_view('staffpicks'); print $view->preview('block_2'); ?> </div><!-- block-staffpicks --> <div class="block block-popular"> <?php $view = views_get_view('most_viewed_sidebar'); print $view->preview('block_2'); ?> </div><!-- block-popular --> </div><!-- also-list --> <?php } ?> <?php if($node->type == "series") { ?> <div class="also-list masonry"> <div class="series-contents"> <?php print views_embed_view('series_contents', 'grid_related_shows', $node->nid); ?> </div> </div><!-- also-list --> <?php } ?> <?php if($node->type == "host") { ?> <div class="also-list masonry"> <div class="title item"><h1>Radio Featuring <?php print $node->title; ?></h1></div> <div class="by-this-host-browse smallgrid listview gridlist-choice-apply"> <!-- the gridlist choice applies to this div --> <?php print views_embed_view('by_this_host', 'of_this_host', $node->nid); ?> <?php print views_embed_view('by_this_host', 'block_2', $node->nid); ?> </div> </div> <?php } ?> </div> <!-- for addthis analytics --> <div id="nid-for-javascript" style="display:none;"><?php print $node->nid; ?></div>
artonair/clocktower
sites/all/node-blog-body.tpl.php
PHP
gpl-2.0
11,545
<?php get_header(); ?> <div id="content" class="clearfix"> <div id="main" class="col620 clearfix" role="main"> <article id="post-0" class="post error404 not-found"> <header class="entry-header"> <h1 class="entry-title"><?php _e( 'Error 404 - Page Not Found', 'newschannel' ); ?></h1> </header> <div class="entry-content post_content"> <h4><?php _e( 'It seems we can&rsquo;t find what you&rsquo;re looking for. Perhaps searching, or one of the links below, can help.', 'newschannel' ); ?></h4> <div style="margin-bottom: 25px"><?php get_search_form(); ?></div> <?php the_widget( 'WP_Widget_Recent_Posts' ); ?> <div class="widget"> <h2 class="widgettitle"><?php _e( 'Most Used Categories', 'newschannel' ); ?></h2> <ul> <?php wp_list_categories( array( 'orderby' => 'count', 'order' => 'DESC', 'show_count' => 1, 'title_li' => '', 'number' => 10 ) ); ?> </ul> </div> <?php /* translators: %1$s: smilie */ $archive_content = '<p>' . sprintf( __( 'Try looking in the monthly archives. %1$s', 'newschannel' ), convert_smilies( ':)' ) ) . '</p>'; the_widget( 'WP_Widget_Archives', 'dropdown=1', "after_title=</h2>$archive_content" ); ?> <?php the_widget( 'WP_Widget_Tag_Cloud' ); ?> </div><!-- .entry-content --> </article><!-- #post-0 --> </div> <!-- end #main --> <?php get_sidebar(); ?> </div> <!-- end #content --> <?php get_footer(); ?>
mxr1027/Xinrui-Ma
wp-content/themes/newschannel/404.php
PHP
gpl-2.0
1,539
package scatterbox.utils; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.HashMap; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class ImportVanKasteren { String dataFileName = "/Users/knoxs/Documents/datasets/kasterenDataset/kasterenSenseData.txt"; String annotationFileName = "/Users/knoxs/Documents/datasets/kasterenDataset/kasterenActData.txt"; File dataFile = new File(dataFileName); File annotationFile = new File(annotationFileName); BufferedReader dataFileReader; BufferedReader annotationFileReader; Connection conn = null; String insertDataCommand = "insert into events (start_time, end_time, id, java_type) values (\"START\", \"END\", \"OBJECT\", \"scatterbox.event.KasterenEvent\")"; String insertAnnotationCommand = "insert into annotations (start_time, end_time, annotation) values (\"START\", \"END\", \"ANNOTATION\")"; HashMap<Integer, String> objects = new HashMap<Integer, String>(); HashMap<Integer, String> annotations = new HashMap<Integer, String>(); //String[] annotations = {"leavehouse", "usetoilet", "takeshower", "gotobed", "preparebreakfast", "preparedinner", "getdrink"}; /** * Format of the sql timestamp. Allows easy conversion to date format */ final DateTimeFormatter dateTimeFormatter = DateTimeFormat .forPattern("dd-MMM-yyyy HH:mm:ss"); public static void main(String[] args) throws FileNotFoundException { ImportVanKasteren ivk = new ImportVanKasteren(); ivk.connectToDatabase(); ivk.dataFileReader = new BufferedReader(new InputStreamReader( new DataInputStream(new FileInputStream(ivk.dataFileName)))); ivk.annotationFileReader = new BufferedReader(new InputStreamReader( new DataInputStream(new FileInputStream(ivk.annotationFileName)))); ivk.setUpAnnotations(); ivk.setUpObjects(); ivk.getData(); ivk.getAnnotations(); } private void getData() { String line; try { while ((line = dataFileReader.readLine()) != null) { String[] readingArray = line.split("\t"); DateTime startTime = dateTimeFormatter .parseDateTime(readingArray[0]); Timestamp startTimestamp = new Timestamp(startTime.getMillis()); DateTime endTime = dateTimeFormatter.parseDateTime(readingArray[1]); Timestamp endTimestamp = new Timestamp(endTime.getMillis()); int id = Integer.parseInt(readingArray[2]); //The reason for -1 is because, kasteren starts id names at 1, not 0, but the array starts at 0. String object = objects.get(id); insertStatement(insertDataCommand.replace("START", startTimestamp.toString()).replace("END", endTimestamp.toString()).replace("OBJECT", object)); } } catch (Exception ioe) { ioe.printStackTrace(); } } private void getAnnotations() { String line; try { while ((line = annotationFileReader.readLine()) != null) { String[] readingArray = line.split("\t"); DateTime startTime = dateTimeFormatter .parseDateTime(readingArray[0]); Timestamp startTimestamp = new Timestamp(startTime.getMillis()); DateTime endTime = dateTimeFormatter.parseDateTime(readingArray[1]); Timestamp endTimestamp = new Timestamp(endTime.getMillis()); int id = Integer.parseInt(readingArray[2]); //The reason for -1 is because, kasteren starts id names at 1, not 0, but the array starts at 0. String annotation = annotations.get(id); insertStatement(insertAnnotationCommand.replace("START", startTimestamp.toString()).replace("END", endTimestamp.toString()).replace("ANNOTATION", annotation)); } } catch (Exception ioe) { ioe.printStackTrace(); } } public boolean insertStatement(String an_sql_statement) { System.out.println(an_sql_statement); boolean success = false; //System.out.println(an_sql_statement); Statement statement; try { statement = conn.createStatement(); if (conn != null) { success = statement.execute(an_sql_statement); statement.close(); } else { System.err.println("No database connection!!!"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return success; } public boolean connectToDatabase() { boolean connected = false; String userName = "root"; String password = ""; String url = "jdbc:mysql://localhost:3306/tvk"; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection(url, userName, password); if (conn != null) { connected = true; } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return connected; } private void setUpObjects() { objects.put(1, "microwave"); objects.put(5, "halltoiletdoor"); objects.put(6, "hallbathroomdoor"); objects.put(7, "cupscupboard"); objects.put(8, "fridge"); objects.put(9, "platescupboard"); objects.put(12, "frontdoor"); objects.put(13, "dishwasher"); objects.put(14, "toiletflush"); objects.put(17, "freezer"); objects.put(18, "panscupboard"); objects.put(20, "washingmachine"); objects.put(23, "groceriescupboard"); objects.put(24, "hallbedroomdoor"); } private void setUpAnnotations() { annotations.put(1, "leavehouse"); annotations.put(4, "usetoilet"); annotations.put(5, "takeshower"); annotations.put(10, "gotobed"); annotations.put(13, "preparebreakfast"); annotations.put(15, "preparedinner"); annotations.put(17, "getdrink"); } }
knoxsp/Concept
src/scatterbox/utils/ImportVanKasteren.java
Java
gpl-2.0
6,596
<?php /* * @version $Id: preference.php 20129 2013-02-04 16:53:59Z moyo $ ------------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2013 by the INDEPNET Development Team. http://indepnet.net/ http://glpi-project.org ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI 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. GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include ('../inc/includes.php'); $user = new User(); // Manage lost password if (isset($_GET['lostpassword'])) { Html::nullHeader(); if (isset($_GET['password_forget_token'])) { User::showPasswordForgetChangeForm($_GET['password_forget_token']); } else { User::showPasswordForgetRequestForm(); } Html::nullFooter(); exit(); } Session::checkLoginUser(); if (isset($_POST["update"]) && ($_POST["id"] === Session::getLoginUserID())) { $user->update($_POST); Event::log($_POST["id"], "users", 5, "setup", //TRANS: %s is the user login sprintf(__('%s updates an item'), $_SESSION["glpiname"])); Html::back(); } else { if ($_SESSION["glpiactiveprofile"]["interface"] == "central") { Html::header(Preference::getTypeName(1), $_SERVER['PHP_SELF'],'preference'); } else { Html::helpHeader(Preference::getTypeName(1), $_SERVER['PHP_SELF']); } $pref = new Preference(); $pref->show(); if ($_SESSION["glpiactiveprofile"]["interface"] == "central") { Html::footer(); } else { Html::helpFooter(); } } ?>
opusappteam/PLGLPI0842
front/preference.php
PHP
gpl-2.0
2,239
<?php /** * @package Joomla.Administrator * @subpackage com_templates * * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; // Include the component HTML helpers. JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html'); JHtml::_('bootstrap.tooltip'); JHtml::_('behavior.formvalidator'); JHtml::_('behavior.keepalive'); JHtml::_('behavior.tabstate'); $input = JFactory::getApplication()->input; // No access if not global SuperUser if (!JFactory::getUser()->authorise('core.admin')) { JFactory::getApplication()->enqueueMessage(JText::_('JERROR_ALERTNOAUTHOR'), 'danger'); } if ($this->type == 'image') { JHtml::_('script', 'vendor/cropperjs/cropper.min.js', array('version' => 'auto', 'relative' => true)); JHtml::_('stylesheet', 'vendor/cropperjs/cropper.min.css', array('version' => 'auto', 'relative' => true)); } JFactory::getDocument()->addScriptDeclaration(" jQuery(document).ready(function($){ // Hide all the folder when the page loads $('.folder ul, .component-folder ul').hide(); // Display the tree after loading $('.directory-tree').removeClass('directory-tree'); // Show all the lists in the path of an open file $('.show > ul').show(); // Stop the default action of anchor tag on a click event $('.folder-url, .component-folder-url').click(function(event){ event.preventDefault(); }); // Prevent the click event from proliferating $('.file, .component-file-url').bind('click',function(e){ e.stopPropagation(); }); // Toggle the child indented list on a click event $('.folder, .component-folder').bind('click',function(e){ $(this).children('ul').toggle(); e.stopPropagation(); }); // New file tree $('#fileModal .folder-url').bind('click',function(e){ $('.folder-url').removeClass('selected'); e.stopPropagation(); $('#fileModal input.address').val($(this).attr('data-id')); $(this).addClass('selected'); }); // Folder manager tree $('#folderModal .folder-url').bind('click',function(e){ $('.folder-url').removeClass('selected'); e.stopPropagation(); $('#folderModal input.address').val($(this).attr('data-id')); $(this).addClass('selected'); }); var containerDiv = document.querySelector('.span3.tree-holder'), treeContainer = containerDiv.querySelector('.nav.nav-list'), liEls = treeContainer.querySelectorAll('.folder.show'), filePathEl = document.querySelector('p.lead.hidden.path'); if(filePathEl) var filePathTmp = document.querySelector('p.lead.hidden.path').innerText; if(filePathTmp && filePathTmp.charAt( 0 ) === '/' ) { filePathTmp = filePathTmp.slice( 1 ); filePathTmp = filePathTmp.split('/'); filePathTmp = filePathTmp[filePathTmp.length - 1]; var re = new RegExp( filePathTmp ); for (var i = 0, l = liEls.length; i < l; i++) { liEls[i].querySelector('a').classList.add('active'); if (i === liEls.length - 1) { var parentUl = liEls[i].querySelector('ul'), allLi = parentUl.querySelectorAll('li'); for (var i = 0, l = allLi.length; i < l; i++) { aEl = allLi[i].querySelector('a'), spanEl = aEl.querySelector('span'); if (spanEl && re.test(spanEl.innerText)) { aEl.classList.add('active'); } } } } } });"); if ($this->type == 'image') { JFactory::getDocument()->addScriptDeclaration(" document.addEventListener('DOMContentLoaded', function() { // Configuration for image cropping var image = document.getElementById('image-crop'); var cropper = new Cropper(image, { viewMode: 0, scalable: true, zoomable: true, minCanvasWidth: " . $this->image['width'] . ", minCanvasHeight: " . $this->image['height'] . ", }); image.addEventListener('crop', function (e) { document.getElementById('x').value = e.detail.x; document.getElementById('y').value = e.detail.y; document.getElementById('w').value = e.detail.width; document.getElementById('h').value = e.detail.height; }); // Function for clearing the coordinates function clearCoords() { var inputs = querySelectorAll('#adminForm input'); for(i=0, l=inputs.length; l>i; i++) { inputs[i].value = ''; }; } });"); } JFactory::getDocument()->addStyleDeclaration(' /* Styles for modals */ .selected { background: #08c; color: #fff; } .selected:hover { background: #08c !important; color: #fff; } .modal-body .column-left { float: left; max-height: 70vh; overflow-y: auto; } .modal-body .column-right { float: right; } @media (max-width: 767px) { .modal-body .column-right { float: left; } } #deleteFolder { margin: 0; } #image-crop { max-width: 100% !important; width: auto; height: auto; } .directory-tree { display: none; } .tree-holder { overflow-x: auto; } '); if ($this->type == 'font') { JFactory::getDocument()->addStyleDeclaration( "/* Styles for font preview */ @font-face { font-family: previewFont; src: url('" . $this->font['address'] . "') } .font-preview{ font-family: previewFont !important; }" ); } ?> <?php echo JHtml::_('bootstrap.startTabSet', 'myTab', array('active' => 'editor')); ?> <?php echo JHtml::_('bootstrap.addTab', 'myTab', 'editor', JText::_('COM_TEMPLATES_TAB_EDITOR')); ?> <div class="row"> <div class="col-md-12"> <?php if($this->type == 'file') : ?> <p class="lead"><?php echo JText::sprintf('COM_TEMPLATES_TEMPLATE_FILENAME', $this->source->filename, $this->template->element); ?></p> <p class="lead path hidden"><?php echo $this->source->filename; ?></p> <?php endif; ?> <?php if($this->type == 'image') : ?> <p class="lead"><?php echo JText::sprintf('COM_TEMPLATES_TEMPLATE_FILENAME', $this->image['path'], $this->template->element); ?></p> <p class="lead path hidden"><?php echo $this->image['path']; ?></p> <?php endif; ?> <?php if($this->type == 'font') : ?> <p class="lead"><?php echo JText::sprintf('COM_TEMPLATES_TEMPLATE_FILENAME', $this->font['rel_path'], $this->template->element); ?></p> <p class="lead path hidden"><?php echo $this->font['rel_path']; ?></p> <?php endif; ?> </div> </div> <div class="row"> <div class="col-md-3 tree-holder"> <?php echo $this->loadTemplate('tree'); ?> </div> <div class="col-md-9"> <?php if ($this->type == 'home') : ?> <form action="<?php echo JRoute::_('index.php?option=com_templates&view=template&id=' . $input->getInt('id') . '&file=' . $this->file); ?>" method="post" name="adminForm" id="adminForm"> <input type="hidden" name="task" value=""> <?php echo JHtml::_('form.token'); ?> <h2><?php echo JText::_('COM_TEMPLATES_HOME_HEADING'); ?></h2> <p><?php echo JText::_('COM_TEMPLATES_HOME_TEXT'); ?></p> <p> <a href="https://docs.joomla.org/J3.x:How_to_use_the_Template_Manager" target="_blank" class="btn btn-primary btn-lg"> <?php echo JText::_('COM_TEMPLATES_HOME_BUTTON'); ?> </a> </p> </form> <?php endif; ?> <?php if ($this->type == 'file') : ?> <form action="<?php echo JRoute::_('index.php?option=com_templates&view=template&id=' . $input->getInt('id') . '&file=' . $this->file); ?>" method="post" name="adminForm" id="adminForm"> <div class="editor-border"> <?php echo $this->form->getInput('source'); ?> </div> <input type="hidden" name="task" value="" /> <?php echo JHtml::_('form.token'); ?> <?php echo $this->form->getInput('extension_id'); ?> <?php echo $this->form->getInput('filename'); ?> </form> <?php endif; ?> <?php if ($this->type == 'archive') : ?> <legend><?php echo JText::_('COM_TEMPLATES_FILE_CONTENT_PREVIEW'); ?></legend> <form action="<?php echo JRoute::_('index.php?option=com_templates&view=template&id=' . $input->getInt('id') . '&file=' . $this->file); ?>" method="post" name="adminForm" id="adminForm"> <ul class="nav flex-column well"> <?php foreach ($this->archive as $file) : ?> <li> <?php if (substr($file, -1) === DIRECTORY_SEPARATOR) : ?> <i class="fa-fw fa fa-folder"></i>&nbsp;<?php echo $file; ?> <?php endif; ?> <?php if (substr($file, -1) != DIRECTORY_SEPARATOR) : ?> <i class="fa-fw fa fa-file-o"></i>&nbsp;<?php echo $file; ?> <?php endif; ?> </li> <?php endforeach; ?> </ul> <input type="hidden" name="task" value=""> <?php echo JHtml::_('form.token'); ?> </form> <?php endif; ?> <?php if ($this->type == 'image') : ?> <img id="image-crop" src="<?php echo $this->image['address'] . '?' . time(); ?>"> <form action="<?php echo JRoute::_('index.php?option=com_templates&view=template&id=' . $input->getInt('id') . '&file=' . $this->file); ?>" method="post" name="adminForm" id="adminForm"> <fieldset class="adminform"> <input type ="hidden" id="x" name="x"> <input type ="hidden" id="y" name="y"> <input type ="hidden" id="h" name="h"> <input type ="hidden" id="w" name="w"> <input type="hidden" name="task" value=""> <?php echo JHtml::_('form.token'); ?> </fieldset> </form> <?php endif; ?> <?php if ($this->type == 'font') : ?> <div class="font-preview"> <form action="<?php echo JRoute::_('index.php?option=com_templates&view=template&id=' . $input->getInt('id') . '&file=' . $this->file); ?>" method="post" name="adminForm" id="adminForm"> <fieldset class="adminform"> <h1>H1. Quickly gaze at Joomla! views from HTML, CSS, JavaScript and XML</h1> <h2>H2. Quickly gaze at Joomla! views from HTML, CSS, JavaScript and XML</h2> <h3>H3. Quickly gaze at Joomla! views from HTML, CSS, JavaScript and XML</h3> <h4>H4. Quickly gaze at Joomla! views from HTML, CSS, JavaScript and XML</h4> <h5>H5. Quickly gaze at Joomla! views from HTML, CSS, JavaScript and XML</h5> <h6>H6. Quickly gaze at Joomla! views from HTML, CSS, JavaScript and XML</h6> <p><b>Bold. Quickly gaze at Joomla! views from HTML, CSS, JavaScript and XML</b></p> <p><i>Italics. Quickly gaze at Joomla! views from HTML, CSS, JavaScript and XML</i></p> <p>Unordered List</p> <ul> <li>Item</li> <li>Item</li> <li>Item<br> <ul> <li>Item</li> <li>Item</li> <li>Item<br> <ul> <li>Item</li> <li>Item</li> <li>Item</li> </ul> </li> </ul> </li> </ul> <p class="lead">Ordered List</p> <ol> <li>Item</li> <li>Item</li> <li>Item<br> <ul> <li>Item</li> <li>Item</li> <li>Item<br> <ul> <li>Item</li> <li>Item</li> <li>Item</li> </ul> </li> </ul> </li> </ol> <input type="hidden" name="task" value=""> <?php echo JHtml::_('form.token'); ?> </fieldset> </form> </div> <?php endif; ?> </div> </div> <?php echo JHtml::_('bootstrap.endTab'); ?> <?php echo JHtml::_('bootstrap.addTab', 'myTab', 'overrides', JText::_('COM_TEMPLATES_TAB_OVERRIDES')); ?> <div class="row"> <div class="col-md-4"> <legend><?php echo JText::_('COM_TEMPLATES_OVERRIDES_MODULES'); ?></legend> <ul class="list-unstyled"> <?php $token = JSession::getFormToken() . '=' . 1; ?> <?php foreach ($this->overridesList['modules'] as $module) : ?> <li> <?php $overrideLinkUrl = 'index.php?option=com_templates&view=template&task=template.overrides&folder=' . $module->path . '&id=' . $input->getInt('id') . '&file=' . $this->file . '&' . $token; ?> <a href="<?php echo JRoute::_($overrideLinkUrl); ?>"> <i class="fa fa-files-o"></i>&nbsp;<?php echo $module->name; ?> </a> </li> <?php endforeach; ?> </ul> </div> <div class="col-md-4"> <legend><?php echo JText::_('COM_TEMPLATES_OVERRIDES_COMPONENTS'); ?></legend> <ul class="list-unstyled"> <?php $token = JSession::getFormToken() . '=' . 1; ?> <?php foreach ($this->overridesList['components'] as $key => $value) : ?> <li class="component-folder"> <a href="#" class="component-folder-url"> <i class="fa fa-folder"></i>&nbsp;<?php echo $key; ?> </a> <ul class="list-unstyled"> <?php foreach ($value as $view) : ?> <li> <?php $overrideLinkUrl = 'index.php?option=com_templates&view=template&task=template.overrides&folder=' . $view->path . '&id=' . $input->getInt('id') . '&file=' . $this->file . '&' . $token; ?> <a class="component-file-url" href="<?php echo JRoute::_($overrideLinkUrl); ?>"> <i class="fa fa-files-o"></i>&nbsp;<?php echo $view->name; ?> </a> </li> <?php endforeach; ?> </ul> </li> <?php endforeach; ?> </ul> </div> <div class="col-md-4"> <legend><?php echo JText::_('COM_TEMPLATES_OVERRIDES_LAYOUTS'); ?></legend> <ul class="nav flex-column"> <?php $token = JSession::getFormToken() . '=' . 1; ?> <?php foreach ($this->overridesList['layouts'] as $layout) : ?> <li> <?php $overrideLinkUrl = 'index.php?option=com_templates&view=template&task=template.overrides&folder=' . $layout->path . '&id=' . $input->getInt('id') . '&file=' . $this->file . '&' . $token; ?> <a href="<?php echo JRoute::_($overrideLinkUrl); ?>"> <i class="fa fa-files-o"></i>&nbsp;<?php echo $layout->name; ?> </a> </li> <?php endforeach; ?> </ul> </div> </div> <?php echo JHtml::_('bootstrap.endTab'); ?> <?php echo JHtml::_('bootstrap.addTab', 'myTab', 'description', JText::_('COM_TEMPLATES_TAB_DESCRIPTION')); ?> <?php echo $this->loadTemplate('description'); ?> <?php echo JHtml::_('bootstrap.endTab'); ?> <?php echo JHtml::_('bootstrap.endTabSet'); ?> <?php // Collapse Modal $copyModalData = array( 'selector' => 'copyModal', 'params' => array( 'title' => JText::_('COM_TEMPLATES_TEMPLATE_COPY'), 'footer' => $this->loadTemplate('modal_copy_footer') ), 'body' => $this->loadTemplate('modal_copy_body') ); ?> <form action="<?php echo JRoute::_('index.php?option=com_templates&task=template.copy&id=' . $input->getInt('id') . '&file=' . $this->file); ?>" method="post" name="adminForm" id="adminForm"> <?php echo JLayoutHelper::render('joomla.modal.main', $copyModalData); ?> <?php echo JHtml::_('form.token'); ?> </form> <?php if ($this->type != 'home') : ?> <?php // Rename Modal $renameModalData = array( 'selector' => 'renameModal', 'params' => array( 'title' => JText::sprintf('COM_TEMPLATES_RENAME_FILE', $this->fileName), 'footer' => $this->loadTemplate('modal_rename_footer') ), 'body' => $this->loadTemplate('modal_rename_body') ); ?> <form action="<?php echo JRoute::_('index.php?option=com_templates&task=template.renameFile&id=' . $input->getInt('id') . '&file=' . $this->file); ?>" method="post"> <?php echo JLayoutHelper::render('joomla.modal.main', $renameModalData); ?> <?php echo JHtml::_('form.token'); ?> </form> <?php endif; ?> <?php if ($this->type != 'home') : ?> <?php // Delete Modal $deleteModalData = array( 'selector' => 'deleteModal', 'params' => array( 'title' => JText::_('COM_TEMPLATES_ARE_YOU_SURE'), 'footer' => $this->loadTemplate('modal_delete_footer') ), 'body' => $this->loadTemplate('modal_delete_body') ); ?> <?php echo JLayoutHelper::render('joomla.modal.main', $deleteModalData); ?> <?php endif; ?> <?php // File Modal $fileModalData = array( 'selector' => 'fileModal', 'params' => array( 'title' => JText::_('COM_TEMPLATES_NEW_FILE_HEADER'), 'footer' => $this->loadTemplate('modal_file_footer') ), 'body' => $this->loadTemplate('modal_file_body') ); ?> <?php echo JLayoutHelper::render('joomla.modal.main', $fileModalData); ?> <?php // Folder Modal $folderModalData = array( 'selector' => 'folderModal', 'params' => array( 'title' => JText::_('COM_TEMPLATES_MANAGE_FOLDERS'), 'footer' => $this->loadTemplate('modal_folder_footer') ), 'body' => $this->loadTemplate('modal_folder_body') ); ?> <?php echo JLayoutHelper::render('joomla.modal.main', $folderModalData); ?> <?php if ($this->type != 'home') : ?> <?php // Resize Modal $resizeModalData = array( 'selector' => 'resizeModal', 'params' => array( 'title' => JText::_('COM_TEMPLATES_RESIZE_IMAGE'), 'footer' => $this->loadTemplate('modal_resize_footer') ), 'body' => $this->loadTemplate('modal_resize_body') ); ?> <form action="<?php echo JRoute::_('index.php?option=com_templates&task=template.resizeImage&id=' . $input->getInt('id') . '&file=' . $this->file); ?>" method="post"> <?php echo JLayoutHelper::render('joomla.modal.main', $resizeModalData); ?> <?php echo JHtml::_('form.token'); ?> </form> <?php endif; ?>
ylahav/joomla-cms
administrator/components/com_templates/views/template/tmpl/default.php
PHP
gpl-2.0
16,786
/* * MATRIX COMPUTATION FOR RESERVATION BASED SYSTEMS * * Copyright (C) 2013, University of Trento * Authors: Luigi Palopoli <palopoli@disi.unitn.it> * * 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. */ #ifndef MATRIX_HPP #define MATRIX_HPP double matrix_prob_ts(int i, int j, int q, const cdf &p, const pmf &u); double matrix_prob_ts_compressed(int i, int j, int q, const cdf &p, const pmf &u); void compute_matrixes(const MatrixXd & mat, int dim, MatrixXd & B, MatrixXd & A0, MatrixXd & A1, MatrixXd & A2); #endif
luigipalopoli/PROSIT
tool/matrix.hpp
C++
gpl-2.0
693
from __future__ import print_function """ Deprecated. Use ``update-tld-names`` command instead. """ __title__ = 'tld.update' __author__ = 'Artur Barseghyan' __copyright__ = '2013-2015 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' from tld.utils import update_tld_names _ = lambda x: x if __name__ == '__main__': update_tld_names() print(_("Local TLD names file has been successfully updated!"))
underdogio/tld
src/tld/update.py
Python
gpl-2.0
414
<?php /** * PESCMS for PHP 5.6+ * * Copyright (c) 2015 PESCMS (http://www.pescms.com) * * For the full copyright and license information, please view * the file LICENSE.md that was distributed with this source code. */ namespace App\Team\GET; class Project extends Content{ /** * 项目数据分析 */ public function analyze(){ $param = []; if(empty($_GET['begin']) && empty($_GET['end']) ){ $param['begin'] = time() - 86400 * 30; $param['end'] = time(); }else{ $param['begin'] = strtotime(self::g('begin'). '00:00:00'); $param['end'] = strtotime(self::g('end'). '23:59:59'); } $result = self::db('project AS p') ->field('p.project_id AS id, p.project_title AS name, t.task_status, COUNT(t.task_status) AS total ') ->join("{$this->prefix}task AS t ON t.task_project_id = p.project_id") ->where("t.task_submit_time BETWEEN :begin AND :end") ->group('p.project_id, t.task_status') ->select($param); $list = []; $project = \Model\Content::listContent(['table' => 'project', 'order' => 'project_listsort ASC, project_id DESC']); foreach ($project as $item){ $list[$item['project_id']]['name'] = $item['project_title']; } if(!empty($result)){ foreach ($result as $value){ if(empty($list[$value['id']]['total'])){ $list[$value['id']]['total'] = 0; } $list[$value['id']]['total'] += $value['total']; $list[$value['id']]['task_status'][$value['task_status']] = $value['total']; } } $this->assign('title', '项目数据分析'); $this->assign('list', $list); $this->layout('User/User_analyze'); } }
lazyphp/PESCMS-TEAM
App/Team/GET/Project.php
PHP
gpl-2.0
1,870
<?php /** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2017 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI 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. * * GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ /** @file * @brief */ include ('../inc/includes.php'); Session::checkRight("sla", READ); Html::header(SLA::getTypeName(Session::getPluralNumber()), $_SERVER['PHP_SELF'], "config", "sla"); Search::show('SLA'); Html::footer();
eltharin/glpi
front/sla.php
PHP
gpl-2.0
1,394
<ul class="tw"> <?php foreach ($rows as $id => $row) { ?> <li><?php print $row; ?></li> <?php } ?> </ul>
allen12345/miqa
sites/all/themes/questionsanswers/views-view-unformatted--tweets--block.tpl.php
PHP
gpl-2.0
104
(function($) { function ACFTableField() { var t = this; t.version = '1.3.4'; t.param = {}; // DIFFERENT IN ACF VERSION 4 and 5 { t.param.classes = { btn_small: 'acf-icon small', // "acf-icon-plus" becomes "-plus" since ACF Pro Version 5.3.2 btn_add_row: 'acf-icon-plus -plus', btn_add_col: 'acf-icon-plus -plus', btn_remove_row: 'acf-icon-minus -minus', btn_remove_col: 'acf-icon-minus -minus', }; t.param.htmlbuttons = { add_row: '<a href="#" class="acf-table-add-row ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_add_row + '"></a>', remove_row: '<a href="#" class="acf-table-remove-row ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_remove_row + '"></a>', add_col: '<a href="#" class="acf-table-add-col ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_add_col + '"></a>', remove_col: '<a href="#" class="acf-table-remove-col ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_remove_row + '"></a>', }; // } t.param.htmltable = { body_row: '<div class="acf-table-body-row">' + '<div class="acf-table-body-left">' + t.param.htmlbuttons.add_row + '<div class="acf-table-body-cont"><!--ph--></div>' + '</div>' + '<div class="acf-table-body-right">' + t.param.htmlbuttons.remove_row + '</div>' + '</div>', top_cell: '<div class="acf-table-top-cell" data-colparam="">' + t.param.htmlbuttons.add_col + '<div class="acf-table-top-cont"><!--ph--></div>' + '</div>', header_cell: '<div class="acf-table-header-cell">' + '<div class="acf-table-header-cont"><!--ph--></div>' + '</div>', body_cell: '<div class="acf-table-body-cell">' + '<div class="acf-table-body-cont"><!--ph--></div>' + '</div>', bottom_cell: '<div class="acf-table-bottom-cell">' + t.param.htmlbuttons.remove_col + '</div>', table: '<div class="acf-table-wrap">' + '<div class="acf-table-table">' + // acf-table-hide-header acf-table-hide-left acf-table-hide-top '<div class="acf-table-top-row">' + '<div class="acf-table-top-left">' + t.param.htmlbuttons.add_col + '</div>' + '<div class="acf-table-top-right"></div>' + '</div>' + '<div class="acf-table-header-row acf-table-header-hide-off">' + '<div class="acf-table-header-left">' + t.param.htmlbuttons.add_row + '</div>' + '<div class="acf-table-header-right"></div>' + '</div>' + '<div class="acf-table-bottom-row">' + '<div class="acf-table-bottom-left"></div>' + '<div class="acf-table-bottom-right"></div>' + '</div>' + '</div>' + '</div>', }; t.param.htmleditor = '<div class="acf-table-cell-editor">' + '<textarea name="acf-table-cell-editor-textarea" class="acf-table-cell-editor-textarea"></textarea>' + '</div>'; t.obj = { body: $( 'body' ), }; t.var = { ajax: false, }; t.state = { 'current_cell_obj': false, 'cell_editor_cell': false, 'cell_editor_last_keycode': false }; t.init = function() { t.init_workflow(); }; t.init_workflow = function() { t.each_table(); t.table_add_col_event(); t.table_remove_col(); t.table_add_row_event(); t.table_remove_row(); t.cell_editor(); t.cell_editor_tab_navigation(); t.prevent_cell_links(); t.sortable_row(); t.sortable_col(); t.ui_event_use_header(); t.ui_event_caption(); t.ui_event_new_flex_field(); t.ui_event_change_location_rule(); t.ui_event_ajax(); }; t.ui_event_ajax = function() { $( document ).ajaxComplete( function( event ) { t.each_table(); }); } t.ui_event_change_location_rule = function() { t.obj.body.on( 'change', '[name="post_category[]"], [name="post_format"], [name="page_template"], [name="parent_id"], [name="role"], [name^="tax_input"]', function() { var interval = setInterval( function() { var table_fields = $( '.field_type-table' ); if ( table_fields.length > 0 ) { t.each_table(); clearInterval( interval ); } }, 100 ); } ); }; t.each_table = function( ) { $( '.acf-field-table .acf-table-root' ).not( '.acf-table-rendered' ).each( function() { var p = {}; p.obj_root = $( this ), table = p.obj_root.find( '.acf-table-wrap' ); if ( table.length > 0 ) { return; } p.obj_root.addClass( 'acf-table-rendered' ); t.data_get( p ); t.data_default( p ); t.field_options_get( p ); t.table_render( p ); t.misc_render( p ); if ( typeof p.data.b[ 1 ] === 'undefined' && typeof p.data.b[ 0 ][ 1 ] === 'undefined' && p.data.b[ 0 ][ 0 ].c === '' ) { p.obj_root.find( '.acf-table-remove-col' ).hide(), p.obj_root.find( '.acf-table-remove-row' ).hide(); } } ); }; t.field_options_get = function( p ) { try { p.field_options = $.parseJSON( decodeURIComponent( p.obj_root.find( '[data-field-options]' ).data( 'field-options' ) ) ); } catch (e) { p.field_options = { use_header: 2 }; console.log( 'The tablefield options value is not a valid JSON string:', decodeURIComponent( p.obj_root.find( '[data-field-options]' ).data( 'field-options' ) ) ); console.log( 'The parsing error:', e ); } }; t.ui_event_use_header = function() { // HEADER: SELECT FIELD ACTIONS { t.obj.body.on( 'change', '.acf-table-fc-opt-use-header', function() { var that = $( this ), p = {}; p.obj_root = that.parents( '.acf-table-root' ); p.obj_table = p.obj_root.find( '.acf-table-table' ); t.data_get( p ); t.data_default( p ); if ( that.val() === '1' ) { p.obj_table.removeClass( 'acf-table-hide-header' ); p.data.p.o.uh = 1; t.update_table_data_field( p ); } else { p.obj_table.addClass( 'acf-table-hide-header' ); p.data.p.o.uh = 0; t.update_table_data_field( p ); } } ); // } }; t.ui_event_caption = function() { // CAPTION: INPUT FIELD ACTIONS { t.obj.body.on( 'change', '.acf-table-fc-opt-caption', function() { var that = $( this ), p = {}; p.obj_root = that.parents( '.acf-table-root' ); p.obj_table = p.obj_root.find( '.acf-table-table' ); t.data_get( p ); t.data_default( p ); p.data.p.ca = that.val(); t.update_table_data_field( p ); } ); // } }; t.ui_event_new_flex_field = function() { t.obj.body.on( 'click', '.acf-fc-popup', function() { // SORTABLE { $( '.acf-table-table' ) .sortable('destroy') .unbind(); window.setTimeout( function() { t.sortable_row(); }, 300 ); // } } ); }; t.data_get = function( p ) { // DATA FROM FIELD { var val = p.obj_root.find( 'input.table' ).val(); p.data = false; // CHECK FIELD CONTEXT { if ( p.obj_root.closest( '.acf-fields' ).hasClass( 'acf-block-fields' ) ) { p.field_context = 'block'; } else { p.field_context = 'box'; } // } if ( val !== '' ) { try { if ( p.field_context === 'box' ) { p.data = $.parseJSON( decodeURIComponent( val.replace(/\+/g, '%20') ) ); } if ( p.field_context === 'block' ) { p.data = $.parseJSON( decodeURIComponent( decodeURIComponent( val.replace(/\+/g, '%20') ) ) ); } } catch (e) { if ( p.field_context === 'box' ) { console.log( 'The tablefield value is not a valid JSON string:', decodeURIComponent( val.replace(/\+/g, '%20') ) ); console.log( 'The parsing error:', e ); } if ( p.field_context === 'block' ) { console.log( 'The tablefield value is not a valid JSON string:', decodeURIComponent( decodeURIComponent( val.replace(/\+/g, '%20') ) ) ); console.log( 'The tablefield value is not a valid JSON string:', decodeURIComponent( decodeURIComponent( decodeURIComponent( val.replace(/\+/g, '%20') ) ) ) ); console.log( 'The parsing error:', e ); } } } return p.data; // } }; t.data_default = function( p ) { // DEFINE DEFAULT DATA { p.data_defaults = { acftf: { v: t.version, }, p: { o: { uh: 0, // use header }, ca: '', // caption content }, // from data-colparam c: [ { c: '', }, ], // header h: [ { c: '', }, ], // body b: [ [ { c: '', }, ], ], }; // } // MERGE DEFAULT DATA { if ( p.data ) { if ( typeof p.data.b === 'array' ) { $.extend( true, p.data, p.data_defaults ); } } else { p.data = p.data_defaults; } // } }; t.table_render = function( p ) { // TABLE HTML MAIN { p.obj_root.find( '.acf-table-wrap' ).remove(); p.obj_root.append( t.param.htmltable.table ); // } // TABLE GET OBJECTS { p.obj_table = p.obj_root.find( '.acf-table-table' ); p.obj_top_row = p.obj_root.find( '.acf-table-top-row' ), p.obj_top_insert = p.obj_top_row.find( '.acf-table-top-right' ), p.obj_header_row = p.obj_root.find( '.acf-table-header-row' ), p.obj_header_insert = p.obj_header_row.find( '.acf-table-header-right' ), p.obj_bottom_row = p.obj_root.find( '.acf-table-bottom-row' ), p.obj_bottom_insert = p.obj_bottom_row.find( '.acf-table-bottom-right' ); // } // TOP CELLS { if ( p.data.c ) { for ( i in p.data.c ) { p.obj_top_insert.before( t.param.htmltable.top_cell ); } } t.table_top_labels( p ); // } // HEADER CELLS { if ( p.data.h ) { for ( i in p.data.h ) { p.obj_header_insert.before( t.param.htmltable.header_cell.replace( '<!--ph-->', p.data.h[ i ].c.replace( /xxx&quot/g, '"' ) ) ); } } // } // BODY ROWS { if ( p.data.b ) { for ( i in p.data.b ) { p.obj_bottom_row.before( t.param.htmltable.body_row.replace( '<!--ph-->', parseInt(i) + 1 ) ); } } // } // BODY ROWS CELLS { var body_rows = p.obj_root.find( '.acf-table-body-row'), row_i = 0; if ( body_rows ) { body_rows.each( function() { var body_row = $( this ), row_insert = body_row.find( '.acf-table-body-right' ); for( i in p.data.b[ row_i ] ) { row_insert.before( t.param.htmltable.body_cell.replace( '<!--ph-->', p.data.b[ row_i ][ i ].c.replace( /xxx&quot/g, '"' ) ) ); } row_i = row_i + 1 } ); } // } // TABLE BOTTOM { if ( p.data.c ) { for ( i in p.data.c ) { p.obj_bottom_insert.before( t.param.htmltable.bottom_cell ); } } // } }; t.misc_render = function( p ) { t.init_option_use_header( p ); t.init_option_caption( p ); }; t.init_option_use_header = function( p ) { // VARS { var v = {}; v.obj_use_header = p.obj_root.find( '.acf-table-fc-opt-use-header' ); // } // HEADER { // HEADER: FIELD OPTIONS, THAT AFFECTS DATA { // HEADER IS NOT ALLOWED if ( p.field_options.use_header === 2 ) { p.obj_table.addClass( 'acf-table-hide-header' ); p.data.p.o.uh = 0; t.update_table_data_field( p ); } // HEADER IS REQUIRED if ( p.field_options.use_header === 1 ) { p.data.p.o.uh = 1; t.update_table_data_field( p ); } // } // HEADER: SET CHECKBOX STATUS { if ( p.data.p.o.uh === 1 ) { v.obj_use_header.val( '1' ); } if ( p.data.p.o.uh === 0 ) { v.obj_use_header.val( '0' ); } // } // HEADER: SET HEADER VISIBILITY { if ( p.data.p.o.uh === 1 ) { p.obj_table.removeClass( 'acf-table-hide-header' ); } if ( p.data.p.o.uh === 0 ) { p.obj_table.addClass( 'acf-table-hide-header' ); } // } // } }; t.init_option_caption = function( p ) { if ( typeof p.field_options.use_caption !== 'number' || p.field_options.use_caption === 2 ) { return; } // VARS { var v = {}; v.obj_caption = p.obj_root.find( '.acf-table-fc-opt-caption' ); // } // SET CAPTION VALUE { v.obj_caption.val( p.data.p.ca ); // } }; t.table_add_col_event = function() { t.obj.body.on( 'click', '.acf-table-add-col', function( e ) { e.preventDefault(); var that = $( this ), p = {}; p.obj_col = that.parent(); t.table_add_col( p ); } ); }; t.table_add_col = function( p ) { // requires // p.obj_col var that_index = p.obj_col.index(); p.obj_root = p.obj_col.parents( '.acf-table-root' ); p.obj_table = p.obj_root.find( '.acf-table-table' ); $( p.obj_table.find( '.acf-table-top-row' ).children()[ that_index ] ).after( t.param.htmltable.top_cell.replace( '<!--ph-->', '' ) ); $( p.obj_table.find( '.acf-table-header-row' ).children()[ that_index ] ).after( t.param.htmltable.header_cell.replace( '<!--ph-->', '' ) ); p.obj_table.find( '.acf-table-body-row' ).each( function() { $( $( this ).children()[ that_index ] ).after( t.param.htmltable.body_cell.replace( '<!--ph-->', '' ) ); } ); $( p.obj_table.find( '.acf-table-bottom-row' ).children()[ that_index ] ).after( t.param.htmltable.bottom_cell.replace( '<!--ph-->', '' ) ); t.table_top_labels( p ); p.obj_table.find( '.acf-table-remove-col' ).show(); p.obj_table.find( '.acf-table-remove-row' ).show(); t.table_build_json( p ); }; t.table_remove_col = function() { t.obj.body.on( 'click', '.acf-table-remove-col', function( e ) { e.preventDefault(); var p = {}, that = $( this ), that_index = that.parent().index(), obj_rows = undefined, cols_count = false; p.obj_root = that.parents( '.acf-table-root' ); p.obj_table = p.obj_root.find( '.acf-table-table' ); p.obj_top = p.obj_root.find( '.acf-table-top-row' ); obj_rows = p.obj_table.find( '.acf-table-body-row' ); cols_count = p.obj_top.find( '.acf-table-top-cell' ).length; $( p.obj_table.find( '.acf-table-top-row' ).children()[ that_index ] ).remove(); $( p.obj_table.find( '.acf-table-header-row' ).children()[ that_index ] ).remove(); if ( cols_count == 1 ) { obj_rows.remove(); t.table_add_col( { obj_col: p.obj_table.find( '.acf-table-top-left' ) } ); t.table_add_row( { obj_row: p.obj_table.find( '.acf-table-header-row' ) } ); p.obj_table.find( '.acf-table-remove-col' ).hide(); p.obj_table.find( '.acf-table-remove-row' ).hide(); } else { obj_rows.each( function() { $( $( this ).children()[ that_index ] ).remove(); } ); } $( p.obj_table.find( '.acf-table-bottom-row' ).children()[ that_index ] ).remove(); t.table_top_labels( p ); t.table_build_json( p ); } ); }; t.table_add_row_event = function() { t.obj.body.on( 'click', '.acf-table-add-row', function( e ) { e.preventDefault(); var that = $( this ), p = {}; p.obj_row = that.parent().parent(); t.table_add_row( p ); }); }; t.table_add_row = function( p ) { // requires // p.obj_row var that_index = 0, col_amount = 0, body_cells_html = ''; p.obj_root = p.obj_row.parents( '.acf-table-root' ); p.obj_table = p.obj_root.find( '.acf-table-table' ); p.obj_table_rows = p.obj_table.children(); col_amount = p.obj_table.find( '.acf-table-top-cell' ).size(); that_index = p.obj_row.index(); for ( i = 0; i < col_amount; i++ ) { body_cells_html = body_cells_html + t.param.htmltable.body_cell.replace( '<!--ph-->', '' ); } $( p.obj_table_rows[ that_index ] ) .after( t.param.htmltable.body_row ) .next() .find('.acf-table-body-left') .after( body_cells_html ); t.table_left_labels( p ); p.obj_table.find( '.acf-table-remove-col' ).show(); p.obj_table.find( '.acf-table-remove-row' ).show(); t.table_build_json( p ); }; t.table_remove_row = function() { t.obj.body.on( 'click', '.acf-table-remove-row', function( e ) { e.preventDefault(); var p = {}, that = $( this ), rows_count = false; p.obj_root = that.parents( '.acf-table-root' ); p.obj_table = p.obj_root.find( '.acf-table-table' ); p.obj_rows = p.obj_root.find( '.acf-table-body-row' ); rows_count = p.obj_rows.length; that.parent().parent().remove(); if ( rows_count == 1 ) { t.table_add_row( { obj_row: p.obj_table.find( '.acf-table-header-row' ) } ); p.obj_table.find( '.acf-table-remove-row' ).hide(); } t.table_left_labels( p ); t.table_build_json( p ); } ); }; t.table_top_labels = function( p ) { var letter_i_1 = 'A'.charCodeAt( 0 ), letter_i_2 = 'A'.charCodeAt( 0 ), use_2 = false; p.obj_table.find( '.acf-table-top-cont' ).each( function() { var string = ''; if ( !use_2 ) { string = String.fromCharCode( letter_i_1 ); if ( letter_i_1 === 'Z'.charCodeAt( 0 ) ) { letter_i_1 = 'A'.charCodeAt( 0 ); use_2 = true; } else { letter_i_1 = letter_i_1 + 1; } } else { string = String.fromCharCode( letter_i_1 ) + String.fromCharCode( letter_i_2 ); if ( letter_i_2 === 'Z'.charCodeAt( 0 ) ) { letter_i_1 = letter_i_1 + 1; letter_i_2 = 'A'.charCodeAt( 0 ); } else { letter_i_2 = letter_i_2 + 1; } } $( this ).text( string ); } ); }; t.table_left_labels = function( p ) { var i = 0; p.obj_table.find( '.acf-table-body-left' ).each( function() { i = i + 1; $( this ).find( '.acf-table-body-cont' ).text( i ); } ); }; t.table_build_json = function( p ) { var i = 0, i2 = 0; p.data = t.data_get( p ); t.data_default( p ); p.data.c = []; p.data.h = []; p.data.b = []; // TOP { i = 0; p.obj_table.find( '.acf-table-top-cont' ).each( function() { p.data.c[ i ] = {}; p.data.c[ i ].p = $( this ).parent().data( 'colparam' ); i = i + 1; } ); // } // HEADER { i = 0; p.obj_table.find( '.acf-table-header-cont' ).each( function() { p.data.h[ i ] = {}; p.data.h[ i ].c = $( this ).html(); i = i + 1; } ); // } // BODY { i = 0; i2 = 0; p.obj_table.find( '.acf-table-body-row' ).each( function() { p.data.b[ i ] = []; $( this ).find( '.acf-table-body-cell .acf-table-body-cont' ).each( function() { p.data.b[ i ][ i2 ] = {}; p.data.b[ i ][ i2 ].c = $( this ).html(); i2 = i2 + 1; } ); i2 = 0; i = i + 1; } ); // } // UPDATE INPUT WITH NEW DATA { t.update_table_data_field( p ); // } }; t.update_table_data_field = function( p ) { // UPDATE INPUT WITH NEW DATA { p.data = t.update_table_data_version( p.data ); // makes json string from data object var data = JSON.stringify( p.data ); // adds backslash to all \" in JSON string because encodeURIComponent() strippes backslashes data.replace( /\\"/g, '\\"' ); // encodes the JSON string to URI component, the format, the JSON string is saved to the database data = encodeURIComponent( data ) p.obj_root.find( 'input.table' ).val( data ); t.field_changed( p ); // } }; t.update_table_data_version = function( data ) { if ( typeof data.acftf === 'undefined' ) { data.acftf = {}; } data.acftf.v = t.version; return data; } t.cell_editor = function() { t.obj.body.on( 'click', '.acf-table-body-cell, .acf-table-header-cell', function( e ) { e.stopImmediatePropagation(); t.cell_editor_save(); var that = $( this ); t.cell_editor_add_editor({ 'that': that }); } ); t.obj.body.on( 'click', '.acf-table-cell-editor-textarea', function( e ) { e.stopImmediatePropagation(); } ); t.obj.body.on( 'click', function( e ) { t.cell_editor_save(); } ); }; t.cell_editor_add_editor = function( p ) { var defaults = { 'that': false }; p = $.extend( true, defaults, p ); if ( p['that'] ) { var that_val = p['that'].find( '.acf-table-body-cont, .acf-table-header-cont' ).html(); t.state.current_cell_obj = p['that']; t.state.cell_editor_is_open = true; p['that'].prepend( t.param.htmleditor ).find( '.acf-table-cell-editor-textarea' ).html( that_val ).focus(); } }; t.get_next_table_cell = function( p ) { var defaults = { 'key': false }; p = $.extend( true, defaults, p ); // next cell of current row var next_cell = t.state.current_cell_obj .next( '.acf-table-body-cell, .acf-table-header-cell' ); // else if get next row if ( next_cell.length === 0 ) { next_cell = t.state.current_cell_obj .parent() .next( '.acf-table-body-row' ) .find( '.acf-table-body-cell') .first(); } // if next row, get first cell of that row if ( next_cell.length !== 0 ) { t.state.current_cell_obj = next_cell; } else { t.state.current_cell_obj = false; } }; t.get_prev_table_cell = function( p ) { var defaults = { 'key': false }; p = $.extend( true, defaults, p ); // prev cell of current row var table_obj = t.state.current_cell_obj.closest( '.acf-table-table' ), no_header = table_obj.hasClass( 'acf-table-hide-header' ); prev_cell = t.state.current_cell_obj .prev( '.acf-table-body-cell, .acf-table-header-cell' ); // else if get prev row if ( prev_cell.length === 0 ) { var row_selectors = [ '.acf-table-body-row' ]; // prevents going to header cell if table header is hidden if ( no_header === false ) { row_selectors.push( '.acf-table-header-row' ); } prev_cell = t.state.current_cell_obj .parent() .prev( row_selectors.join( ',' ) ) .find( '.acf-table-body-cell, .acf-table-header-cell' ) .last(); } // if next row, get first cell of that row if ( prev_cell.length !== 0 ) { t.state.current_cell_obj = prev_cell; } else { t.state.current_cell_obj = false; } }; t.cell_editor_save = function() { var cell_editor = t.obj.body.find( '.acf-table-cell-editor' ), cell_editor_textarea = cell_editor.find( '.acf-table-cell-editor-textarea' ), p = {}, cell_editor_val = ''; if ( typeof cell_editor_textarea.val() !== 'undefined' ) { p.obj_root = cell_editor.parents( '.acf-table-root' ); p.obj_table = p.obj_root.find( '.acf-table-table' ); var cell_editor_val = cell_editor_textarea.val(); // prevent XSS injection cell_editor_val = cell_editor_val.replace( /\<(script)/ig, '&#060;$1' ); cell_editor_val = cell_editor_val.replace( /\<\/(script)/ig, '&#060;/$1' ); cell_editor.next().html( cell_editor_val ); t.table_build_json( p ); cell_editor.remove(); t.state.cell_editor_is_open = false; p.obj_root.find( '.acf-table-remove-col' ).show(), p.obj_root.find( '.acf-table-remove-row' ).show(); } }; t.cell_editor_tab_navigation = function() { t.obj.body.on( 'keydown', '.acf-table-cell-editor', function( e ) { var keyCode = e.keyCode || e.which; if ( keyCode == 9 ) { e.preventDefault(); t.cell_editor_save(); if ( t.state.cell_editor_last_keycode === 16 ) { t.get_prev_table_cell(); } else { t.get_next_table_cell(); } t.cell_editor_add_editor({ 'that': t.state.current_cell_obj }); } t.state.cell_editor_last_keycode = keyCode; }); }; t.prevent_cell_links = function() { t.obj.body.on( 'click', '.acf-table-body-cont a, .acf-table-header-cont a', function( e ) { e.preventDefault(); } ); }; t.sortable_fix_width = function(e, ui) { ui.children().each( function() { var that = $( this ); that.width( that.width() ); } ); return ui; }; t.sortable_row = function() { var param = { axis: 'y', items: '> .acf-table-body-row', containment: 'parent', handle: '.acf-table-body-left', helper: t.sortable_fix_width, update: function( event, ui ) { var p = {}; p.obj_root = ui.item.parents( '.acf-table-root' ); p.obj_table = p.obj_root.find( '.acf-table-table' ); t.table_left_labels( p ); t.table_build_json( p ); }, }; $( '.acf-table-table' ).sortable( param ); }; t.sortable_col = function() { var p = {}; p.start_index = 0; p.end_index = 0; var param = { axis: 'x', items: '> .acf-table-top-cell', containment: 'parent', helper: t.sortable_fix_width, start: function(event, ui) { p.start_index = ui.item.index(); }, update: function( event, ui ) { p.end_index = ui.item.index(); p.obj_root = ui.item.parents( '.acf-table-root' ); p.obj_table = p.obj_root.find( '.acf-table-table' ); t.table_top_labels( p ); t.sort_cols( p ); t.table_build_json( p ); }, }; $( '.acf-table-top-row' ).sortable( param ); t.obj.body.on( 'click', '.acf-fc-popup', function() { $( '.acf-table-top-row' ) .sortable('destroy') .unbind(); window.setTimeout( function() { $( '.acf-table-top-row' ).sortable( param ); }, 300 ); } ); }; t.field_changed = function( p ) { if ( p.field_context === 'block' ) { p.obj_root.change(); } }; t.sort_cols = function( p ) { p.obj_table.find('.acf-table-header-row').each( function() { p.header_row = $(this), p.header_row_children = p.header_row.children(); if ( p.end_index < p.start_index ) { $( p.header_row_children[ p.end_index ] ).before( $( p.header_row_children[ p.start_index ] ) ); } if ( p.end_index > p.start_index ) { $( p.header_row_children[ p.end_index ] ).after( $( p.header_row_children[ p.start_index ] ) ); } } ); p.obj_table.find('.acf-table-body-row').each( function() { p.body_row = $(this), p.body_row_children = p.body_row.children(); if ( p.end_index < p.start_index ) { $( p.body_row_children[ p.end_index ] ).before( $( p.body_row_children[ p.start_index ] ) ); } if ( p.end_index > p.start_index ) { $( p.body_row_children[ p.end_index ] ).after( $( p.body_row_children[ p.start_index ] ) ); } } ); }; t.helper = { getLength: function( o ) { var len = o.length ? --o.length : -1; for (var k in o) { len++; } return len; }, }; }; var acf_table_field = new ACFTableField(); acf_table_field.init(); })( jQuery );
johannheyne/acf-table
advanced-custom-fields-table-field/tags/1.3.4/js/input-v5.js
JavaScript
gpl-2.0
26,869
/* * Rasengan - Manga and Comic Downloader * Copyright (C) 2013 Sauriel * * 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 de.sauriel.rasengan.ui; import java.awt.BorderLayout; import javax.swing.JDialog; import javax.swing.JProgressBar; import javax.swing.JLabel; import java.util.Observable; import java.util.Observer; public class DownloadDialog extends JDialog implements Observer { private static final long serialVersionUID = 4251447351437107605L; JProgressBar progressBar; public DownloadDialog() { // Configure Dialog setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); setAlwaysOnTop(true); setModal(true); setModalityType(ModalityType.MODELESS); setResizable(false); setTitle("Downloading: " + RasenganMainFrame.comic.getName()); setBounds(100, 100, 300, 60); setLayout(new BorderLayout(0, 0)); // Set Content JLabel labelDownload = new JLabel("Downloading: " + RasenganMainFrame.comic.getName()); add(labelDownload, BorderLayout.NORTH); progressBar = new JProgressBar(); add(progressBar, BorderLayout.CENTER); } @Override public void update(Observable comicService, Object imagesCount) { int[] newImagesCount= (int[]) imagesCount; progressBar.setMaximum(newImagesCount[1]); progressBar.setValue(newImagesCount[0]); if (newImagesCount[0] == newImagesCount[1]) { dispose(); } } }
Sauriel/rasengan
src/de/sauriel/rasengan/ui/DownloadDialog.java
Java
gpl-2.0
2,082