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
class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ width,height = len(matrix[0]),len(matrix) for i in xrange(height): foundzero = False for j in xrange(width): if matrix[i][j] == 0: foundzero = True matrix[i][j] = float("inf") if not foundzero: continue for j in xrange(width): if matrix[i][j] != float("inf"): matrix[i][j] = 0 for i in xrange(width): foundtarget = False for j in xrange(height): if matrix[j][i] == float("inf"): foundtarget = True break if not foundtarget: continue for j in xrange(height): matrix[j][i] = 0
hufeiya/leetcode
python/73_Set_Matrix_Zeroes.py
Python
gpl-2.0
1,004
<?php /* Copyright (C) 2002-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004-2005 Laurent Destailleur <eldy@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. */ /** * \file htdocs/cactioncomm.class.php * \ingroup commercial * \brief Fichier de la classe des types d'actions commerciales * \version $Id$ */ /** * \class CActionComm * \brief Class to manage different types of events */ class CActionComm { var $db; var $id; var $code; var $type; var $libelle; var $active; var $error; var $type_actions=array(); /** * \brief Constructeur * \param DB Handler d'acces base de donnee */ function CActionComm($DB) { $this->db = $DB; } /** * \brief Charge l'objet type d'action depuis la base * \param id id ou code du type d'action a recuperer * \return int 1=ok, 0=aucune action, -1=erreur */ function fetch($id) { $sql = "SELECT id, code, type, libelle, active"; $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm"; if (is_numeric($id)) $sql.= " WHERE id=".$id; else $sql.= " WHERE code='".$id."'"; $resql=$this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->id; $this->code = $obj->code; $this->type = $obj->type; $this->libelle = $obj->libelle; $this->active = $obj->active; return 1; } else { return 0; } $this->db->free($resql); } else { $this->error=$this->db->error(); return -1; } } /* * \brief Renvoi la liste des types d'actions existant * \param active 1 ou 0 pour un filtre sur l'etat actif ou non ('' par defaut = pas de filtre) * \return array Tableau des types d'actions actifs si ok, <0 si erreur */ function liste_array($active='',$idorcode='id') { global $langs,$conf; $langs->load("commercial"); $repid = array(); $repcode = array(); $sql = "SELECT id, code, libelle, module"; $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm"; if ($active != '') { $sql.=" WHERE active=".$active; } dol_syslog("CActionComm::liste_array sql=".$sql); $resql=$this->db->query($sql); if ($resql) { $nump = $this->db->num_rows($resql); if ($nump) { $i = 0; while ($i < $nump) { $obj = $this->db->fetch_object($resql); $qualified=1; if ($obj->module) { if ($obj->module == 'invoice' && ! $conf->facture->enabled) $qualified=0; if ($obj->module == 'order' && ! $conf->commande->enabled) $qualified=0; if ($obj->module == 'propal' && ! $conf->propal->enabled) $qualified=0; } if ($qualified) { $transcode=$langs->trans("Action".$obj->code); $repid[$obj->id] = ($transcode!="Action".$obj->code?$transcode:$obj->libelle); $repcode[$obj->code] = ($transcode!="Action".$obj->code?$transcode:$obj->libelle); } $i++; } } if ($idorcode == 'id') $this->liste_array=$repid; if ($idorcode == 'code') $this->liste_array=$repcode; return $this->liste_array; } else { return -1; } } /** * \brief Renvoie le nom sous forme d'un libelle traduit d'un type d'action * \param withpicto 0=Pas de picto, 1=Inclut le picto dans le lien, 2=Picto seul * \param option Sur quoi pointe le lien * \return string Libelle du type d'action */ function getNomUrl($withpicto=0) { global $langs; // Check if translation available $transcode=$langs->trans("Action".$this->code); if ($transcode != "Action".$this->code) return $transcode; } } ?>
philazerty/dolibarr
htdocs/cactioncomm.class.php
PHP
gpl-2.0
4,684
package com.github.ivanmarban.movies; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class MovieRestController { @Autowired private MovieRepository repo; @RequestMapping(value = "api/v1/movies", method = RequestMethod.GET) public List<Movie> getAll() { return repo.findAll(); } @RequestMapping(value = "api/v1/movie/{id}", method = RequestMethod.GET) public Movie get(@PathVariable String id) { return repo.findOne(id); } @RequestMapping(value = "api/v1/movie", method = RequestMethod.POST) public Movie create(@RequestBody Movie movie) { return repo.save(movie); } @RequestMapping(value = "api/v1/movie/{id}", method = RequestMethod.DELETE) public void delete(@PathVariable String id) { repo.delete(id); } @RequestMapping(value = "api/v1/movie/{id}", method = RequestMethod.PUT) public Movie update(@PathVariable String id, @RequestBody Movie movie) { Movie update = repo.findOne(id); update.setDirector(movie.getDirector()); update.setGenre(movie.getGenre()); update.setRated(movie.getRated()); update.setRuntime(movie.getRuntime()); update.setTitle(movie.getTitle()); update.setYear(movie.getYear()); return repo.save(update); } }
ivanmarban/spring-boot-movies-restful
src/main/java/com/github/ivanmarban/movies/MovieRestController.java
Java
gpl-2.0
1,466
<?php // // phpCAS proxy client with PGT storage to database // // import phpCAS lib include_once('CAS/CAS.php'); // set debug mode phpCAS::setDebug(); // initialize phpCAS phpCAS::proxy(CAS_VERSION_2_0,'sso-cas.univ-rennes1.fr',443,''); // set PGT storage to file in XML format in the same directory as session files phpCAS::setPGTStorageDB('user', 'password', '',// database_type defaults to `mysql' '',// hostname defaults to `localhost' 0,// use default port '',// database defaults to phpCAS '' // table defaults to `pgt' ); // force CAS authentication phpCAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server // and the user's login name can be read with phpCAS::getUser(). // moreover, a PGT was retrieved from the CAS server that will // permit to gain accesses to new services. $service = 'http://phpcas-test.univ-rennes1.fr/examples/example_service.php'; ?> <html> <head> <title>phpCAS proxy example with PGT storage to database</title> </head> <body> <h1>phpCAS proxy example with PGT storage to database</h1> <p>the user's login is <b><?php echo phpCAS::getUser(); ?></b>.</p> <h2>Response from service <?php echo $service; ?></h2><ul><hr> <?php flush(); // call a service and change the color depending on the result if ( phpCAS::serviceWeb($service,$err_code,$output) ) { echo '<font color="#00FF00">'; } else { echo '<font color="#FF0000">'; } echo $output; echo '</font><hr></ul>'; ?> </body> </html>
coz787/conges4ac
INCLUDE.EXTERNAL/esup-phpcas-0.5.1-1/source/examples/example_db.php
PHP
gpl-2.0
1,535
#include "convection.h" #include "sem.h" using namespace mnl; using namespace std; deformedConvectionEvaluator::deformedConvectionEvaluator(const basics::matrixStack& G, const basics::Matrix& D, const basics::Vector& weight, const basics::Field2<basics::Matrix>& u, basics::Matrix& buffer, basics::Matrix& buffer2) : m_weight(weight), m_D(D), m_buffer(buffer), m_buffer2(buffer2), m_G(G), m_u(u) { } void deformedConvectionEvaluator::evaluate(basics::Matrix& result, const basics::Matrix& u) const { /* ux */ basics::multTranspose(m_buffer, m_D,u,'N','N'); basics::multPointwise(m_buffer2,m_buffer,m_G[3]); basics::multTranspose(m_buffer,u,m_D,'N','T'); basics::multPointwise(m_buffer2,m_buffer,m_G[2],1,-1); basics::multPointwise(result,m_buffer2,m_u.X()); /* uy */ basics::multTranspose(m_buffer, u,m_D,'N','T'); basics::multPointwise(m_buffer2,m_buffer,m_G[0]); basics::multTranspose(m_buffer,m_D,u,'N','N'); basics::multPointwise(m_buffer2,m_buffer,m_G[1],1,-1); basics::multPointwise(result,m_buffer2,m_u.Y(),1,1); result *= -1; massReference(result,m_weight); } deformed3DConvectionEvaluator:: deformed3DConvectionEvaluator(const basics::matricesStack& G, const basics::Matrix& D, const basics::Vector& weight, const basics::Field3<basics::Matrices>& u, basics::Matrices& buffer, basics::Matrices& buffer2) : m_weight(weight), m_D(D), m_buffer(buffer), m_buffer2(buffer2), m_G(G), m_u(u) { } void deformed3DConvectionEvaluator::evaluate(basics::Matrices& res, const basics::Matrices& u) const { evaluateComponent(res,u,0); basics::multPointwise(res,m_u.X()); evaluateComponent(m_buffer2,u,1); basics::multPointwise(m_buffer2,m_u.Y()); res += m_buffer2; evaluateComponent(m_buffer2,u,2); basics::multPointwise(m_buffer2,m_u.Z()); res += m_buffer2; res *= -1; massReference(res,m_weight); } void deformed3DConvectionEvaluator::evaluateComponent(basics::Matrices& res, const basics::Matrices& field, int index) const { for( int l=0;l<field.matrices();++l ) basics::multTranspose(m_buffer[l],m_D,field[l],'N','N'); basics::multPointwise(res,m_buffer,m_G[index]); for( int l=0;l<field.matrices();++l ) basics::multTranspose(m_buffer[l],field[l],m_D,'N','T'); basics::multPointwise(m_buffer,m_G[index+3]); res += m_buffer; basics::applyLocalGlobal(m_buffer,field,m_D,'N','T'); basics::multPointwise(m_buffer,m_G[index+6]); res += m_buffer; } convectionEvaluator::convectionEvaluator(const basics::geometryStack& geometry, const basics::Matrix& D, const basics::Vector& weight, int rank, int size, const basics::geometryStack3D* geometry3D) : m_geometry(geometry), m_weight(weight), m_D(D), m_rank(rank), m_size(size), m_view(NULL), m_geometry3D(NULL), m_deformed(false), m_order(1) { if( geometry3D ) { m_grid = geometry3D->getDivisionInfo(size); m_geometry3D = geometry3D; m_deformed = true; m_view = new basics::componentView<basics::Matrices,basics::matricesStack>(m_geometry3D->getReferenceGeometryDerivatives()); } else m_grid = geometry.getDivisionInfo(size); m_buffer = utilities::g_manager.aquireMatrixStack("convection buffer",D.rows(),D.cols(),m_grid[m_rank].elements.size()); m_buffer2 = utilities::g_manager.clone(*m_buffer); m_buffer3 = utilities::g_manager.aquireMatricesStack("convection buffer3D",D.rows(),D.cols(),D.rows(),m_grid[m_rank].elements.size()); m_buffer4 = utilities::g_manager.clone(*m_buffer3); } convectionEvaluator::~convectionEvaluator() { delete m_view; utilities::g_manager.unlock(m_buffer); utilities::g_manager.unlock(m_buffer2); utilities::g_manager.unlock(m_buffer3); utilities::g_manager.unlock(m_buffer4); } void convectionEvaluator::evaluate(basics::matrixStack& res, const basics::matrixStack& u) const { basics::Field2<basics::matrixStack>* field = (basics::Field2<basics::matrixStack>*)m_interp; int max=u.size(); #pragma omp parallel for schedule(static) for( int i=0;i<max;++i ) { basics::Field2<basics::Matrix> foo(&field->X()[i],&field->Y()[i]); deformedConvectionEvaluator eval(m_geometry[i].getGH().getGeometryDerivatives(), m_D,m_weight,foo,(*m_buffer)[i],(*m_buffer2)[i]); eval.evaluate(res[i],u[i]); } if( m_bc == SEMLaplacianEvaluator::PERIODIC ) { m_geometry.periodicDssum(res); m_geometry.invMassP(res); } else { m_geometry.dssum(res); m_geometry.invMass(res); m_geometry.mask(res); } } void convectionEvaluator::evaluate(basics::matricesStack& res, const basics::matricesStack& u) { if( m_deformed ) { evaluateDeformed(res,u); return; } /* extruded */ basics::Field3<basics::matricesStack>* field = (basics::Field3<basics::matricesStack>*)m_interp; /* z */ int max=u.size(); #pragma omp parallel for schedule(static) for( int n=0;n<max;++n ) { basics::applyLocalGlobal((*m_buffer3)[n],u[n],m_D,'N','T',0,-Real(2)/m_geometry.m_Lz); basics::multPointwise(res[n],(*m_buffer3)[n],field->Z()[n]); } m_geometry.mass(res,m_grid[m_rank].elements); /* x and y */ for( int l=0;l<u[0].matrices();++l ) { #pragma omp parallel for schedule(static) for( int i=0;i<max;++i ) { basics::Field2<basics::Matrix> foo(&field->X().at(l)[i],&field->Y().at(l)[i]); deformedConvectionEvaluator eval(m_geometry[m_grid[m_rank].elements[i]].getGH().getGeometryDerivatives(), m_D,m_weight,foo,(*m_buffer)[i],(*m_buffer2)[i]); eval.evaluate(m_buffer3->at(l)[i],u.at(l)[i]); } res.at(l).axpy(m_weight[l]*m_geometry.m_Lz/2,m_buffer3->at(l)); } if( m_bc == SEMLaplacianEvaluator::PERIODIC ) { m_geometry.periodicDssum(res); m_geometry.invMassP(res); } else { dssum(res,m_geometry,m_rank,m_size); m_geometry.invMass(res,m_grid[m_rank].elements); mask(res,m_geometry,m_rank,m_size,m_bc); } } void convectionEvaluator::evaluateDeformed(basics::matricesStack& res, const basics::matricesStack& u) { basics::Field3<basics::matricesStack>* field = (basics::Field3<basics::matricesStack>*)m_interp; int max=m_grid[m_rank].elements.size(); #pragma omp parallel for schedule(static) for( int i=0;i<max;++i ) { int elem=m_grid[m_rank].elements[i]; basics::Field3<basics::Matrices> foo(&field->X()[i],&field->Y()[i],&field->Z()[i]); deformed3DConvectionEvaluator eval((*m_view)[elem],m_D,m_weight,foo,(*m_buffer3)[i],(*m_buffer4)[i]); eval.evaluate(res[i],u[i]); } dssum(res,*m_geometry3D,m_rank,m_size); m_geometry3D->invMass(res,m_grid[m_rank].elements); mask(res,*m_geometry3D,m_rank,m_size,m_bc); }
akva2/benard-marangoni
bm/convection.cpp
C++
gpl-2.0
6,649
<?php /** * @package jCart * @copyright Copyright (C) 2009 - 2016 softPHP,http://www.soft-php.com * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); // Text $_['text_title'] = 'Credit or Debit Card (Processed securely by Perpetual Payments)'; $_['text_credit_card'] = 'Credit Card Details'; $_['text_transaction'] = 'Transaction ID:'; $_['text_avs'] = 'AVS/CVV:'; $_['text_avs_full_match'] = 'Full match'; $_['text_avs_not_match'] = 'Not matched'; $_['text_authorisation'] = 'Authorisation code:'; // Entry $_['entry_cc_number'] = 'Card Number'; $_['entry_cc_start_date'] = 'Card Valid From Date'; $_['entry_cc_expire_date'] = 'Card Expiry Date'; $_['entry_cc_cvv2'] = 'Card Security Code (CVV2)'; $_['entry_cc_issue'] = 'Card Issue Number'; // Help $_['help_start_date'] = '(if available)'; $_['help_issue'] = '(for Maestro and Solo cards only)';
reparosemlagrima/producao
components/com_jcart/catalog/language/en-gb/payment/perpetual_payments.php
PHP
gpl-2.0
962
<?php /** * File containing the ConfiguredFileService class * * @copyright Copyright (C) 1999-2014 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version //autogentag// */ namespace eZ\Publish\Core\MVC\Symfony; use eZ\Publish\Core\FieldType\FileService\LegacyFileService as BaseFileService; use eZ\Publish\Core\MVC\ConfigResolverInterface; /** * Configuration aware local file service for BinaryBase FieldTypes storage */ class ConfiguredFileService extends BaseFileService { /** * Builds the file service based on the dynamic configuration provided by * the config resolver * * @param callable $kernelClosure * @param ConfigResolverInterface $resolver * @param string $installDir */ public function __construct( \Closure $kernelClosure, ConfigResolverInterface $resolver, $installDir ) { parent::__construct( $kernelClosure, $installDir, sprintf( '%s/%s/%s', $resolver->getParameter( 'var_dir' ), $resolver->getParameter( 'storage_dir' ), $resolver->getParameter( 'binary_dir' ) ) ); } }
glye/ezpublish-kernel
eZ/Publish/Core/MVC/Symfony/ConfiguredFileService.php
PHP
gpl-2.0
1,285
<?php /** * * BoldR Lite WordPress Theme by Iceable Themes | http://www.iceablethemes.com * * Copyright 2013-2014 Mathieu Sarrasin - Iceable Media * * Theme's Function * */ /* * Set default $content_width */ if ( ! isset( $content_width ) ) $content_width = 590; /* Adjust $content_width depending on the page being displayed */ function boldr_content_width() { global $content_width; if ( is_singular() && !is_page() ) $content_width = 595; if ( is_page() ) $content_width = 680; if ( is_page_template( 'page-full-width.php' ) ) $content_width = 920; } add_action( 'template_redirect', 'boldr_content_width' ); /* * Setup and registration functions */ function boldr_setup(){ /* Translation support * Translations can be added to the /languages directory. * A .pot template file is included to get you started */ load_theme_textdomain('boldr', get_template_directory() . '/languages'); /* Feed links support */ add_theme_support( 'automatic-feed-links' ); /* Register menus */ register_nav_menu( 'primary', 'Navigation menu' ); register_nav_menu( 'footer-menu', 'Footer menu' ); /* Post Thumbnails Support */ add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 260, 260, true ); /* Custom header support */ add_theme_support( 'custom-header', array( 'header-text' => false, 'width' => 920, 'height' => 370, 'flex-height' => true, ) ); /* Custom background support */ add_theme_support( 'custom-background', array( 'default-color' => '333333', 'default-image' => get_template_directory_uri() . '/img/black-leather.png', ) ); } add_action('after_setup_theme', 'boldr_setup'); /* * Page title */ function boldr_wp_title( $title, $sep ) { global $paged, $page; if ( is_feed() ) return $title; // Add the site name. $title .= get_bloginfo( 'name' ); // Add the site description for the home/front page. $site_description = get_bloginfo( 'description', 'display' ); if ( $site_description && ( is_home() || is_front_page() ) ) $title = "$title $sep $site_description"; // Add a page number if necessary. if ( $paged >= 2 || $page >= 2 ) $title = "$title $sep " . sprintf( __( 'Page %s', 'boldr' ), max( $paged, $page ) ); return $title; } add_filter( 'wp_title', 'boldr_wp_title', 10, 2 ); /* * Add a home link to wp_page_menu() ( wp_nav_menu() fallback ) */ function boldr_page_menu_args( $args ) { if ( ! isset( $args['show_home'] ) ) $args['show_home'] = true; return $args; } add_filter( 'wp_page_menu_args', 'boldr_page_menu_args' ); /* * Add parent Class to parent menu items */ function boldr_add_menu_parent_class( $items ) { $parents = array(); foreach ( $items as $item ) { if ( $item->menu_item_parent && $item->menu_item_parent > 0 ) { $parents[] = $item->menu_item_parent; } } foreach ( $items as $item ) { if ( in_array( $item->ID, $parents ) ) { $item->classes[] = 'menu-parent-item'; } } return $items; } add_filter( 'wp_nav_menu_objects', 'boldr_add_menu_parent_class' ); /* * The automatically generated fallback menu is not responsive. * Add an admin notice to warn users who did not set a primary menu * and make this notice dismissable so it is less intrusive. */ function boldr_admin_notice(){ global $current_user; $user_id = $current_user->ID; /* Display notice if primary menu is not set and user did not dismiss the notice */ if ( !has_nav_menu( 'primary' ) && !get_user_meta($user_id, 'boldr_ignore_notice' ) ): echo '<div class="updated"><p><strong>BoldR Lite Notice:</strong> you have not set your primary menu yet, and your site is currently using a fallback menu which is not responsive. Please take a minute to <a href="'.admin_url('nav-menus.php').'">set your menu now</a>!'; printf(__('<a href="%1$s" style="float:right">Dismiss</a>'), '?boldr_notice_ignore=0'); echo '</p></div>'; endif; } add_action('admin_notices', 'boldr_admin_notice'); function boldr_notice_ignore() { global $current_user; $user_id = $current_user->ID; /* If user clicks to ignore the notice, add that to their user meta */ if ( isset($_GET['boldr_notice_ignore']) && '0' == $_GET['boldr_notice_ignore'] ): add_user_meta($user_id, 'boldr_ignore_notice', true, true); endif; } add_action('admin_init', 'boldr_notice_ignore'); /* * Register Sidebar and Footer widgetized areas */ function boldr_widgets_init() { register_sidebar( array( 'name' => __( 'Default Sidebar', 'boldr' ), 'id' => 'sidebar', 'description' => '', 'class' => '', 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => '</li>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); register_sidebar( array( 'name' => __( 'Footer', 'boldr' ), 'id' => 'footer-sidebar', 'description' => '', 'class' => '', 'before_widget' => '<li id="%1$s" class="one-fourth widget %2$s">', 'after_widget' => '</li>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'boldr_widgets_init' ); /* * Enqueue CSS styles */ function boldr_styles() { $template_directory_uri = get_template_directory_uri(); // Parent theme URI $stylesheet_directory = get_stylesheet_directory(); // Current theme directory $stylesheet_directory_uri = get_stylesheet_directory_uri(); // Current theme URI $responsive_mode = boldr_get_option('responsive_mode'); if ($responsive_mode != 'off'): $stylesheet = '/css/boldr.min.css'; else: $stylesheet = '/css/boldr-unresponsive.min.css'; endif; /* Child theme support: * Enqueue child-theme's versions of stylesheet in /css if they exist, * or the parent theme's version otherwise */ if ( @file_exists( $stylesheet_directory . $stylesheet ) ) wp_register_style( 'boldr', $stylesheet_directory_uri . $stylesheet ); else wp_register_style( 'boldr', $template_directory_uri . $stylesheet ); // Always enqueue style.css from the current theme wp_register_style( 'style', $stylesheet_directory_uri . '/style.css'); wp_enqueue_style( 'boldr' ); wp_enqueue_style( 'style' ); // Google Webfonts wp_enqueue_style( 'Oswald-webfonts', "//fonts.googleapis.com/css?family=Oswald:400italic,700italic,400,700&subset=latin,latin-ext", array(), null ); wp_enqueue_style( 'PTSans-webfonts', "//fonts.googleapis.com/css?family=PT+Sans:400italic,700italic,400,700&subset=latin,latin-ext", array(), null ); } add_action('wp_enqueue_scripts', 'boldr_styles'); /* * Register editor style */ function boldr_editor_styles() { add_editor_style(); } add_action( 'init', 'boldr_editor_styles' ); /* * Enqueue Javascripts */ function boldr_scripts() { wp_enqueue_script('boldr', get_template_directory_uri() . '/js/boldr.min.js', array('jquery')); /* Threaded comments support */ if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) wp_enqueue_script( 'comment-reply' ); } add_action('wp_enqueue_scripts', 'boldr_scripts'); /* * Remove "rel" tags in category links (HTML5 invalid) */ function boldr_remove_rel_cat( $text ) { $text = str_replace(' rel="category"', "", $text); return $text; } add_filter( 'the_category', 'boldr_remove_rel_cat' ); /* * Fix for a known issue with enclosing shortcodes and wpautop * (wpautop tends to add empty <p> or <br> tags before and/or after enclosing shortcodes) * Thanks to Johann Heyne */ function boldr_shortcode_empty_paragraph_fix($content) { $array = array ( '<p>[' => '[', ']</p>' => ']', ']<br />' => ']', ); $content = strtr($content, $array); return $content; } add_filter('the_content', 'boldr_shortcode_empty_paragraph_fix'); /* * Improved version of clean_pre * Based on a work by Emrah Gunduz */ function boldr_protect_pre($pee) { $pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'boldr_eg_clean_pre', $pee ); return $pee; } function boldr_eg_clean_pre($matches) { if ( is_array($matches) ) $text = $matches[1] . $matches[2] . "</pre>"; else $text = $matches; $text = str_replace('<br />', '', $text); return $text; } add_filter( 'the_content', 'boldr_protect_pre' ); /* * Customize "read more" links on index view */ function boldr_excerpt_more( $more ) { global $post; return '<div class="read-more"><a href="'. get_permalink( get_the_ID() ) . '">'. __("Read More", 'boldr') .'</a></div>'; } add_filter( 'excerpt_more', 'boldr_excerpt_more' ); /* * Rewrite and replace wp_trim_excerpt() so it adds a relevant read more link * when the <!--more--> or <!--nextpage--> quicktags are used * This new function preserves every features and filters from the original wp_trim_excerpt */ function boldr_trim_excerpt($text = '') { global $post; $raw_excerpt = $text; if ( '' == $text ) { $text = get_the_content(''); $text = strip_shortcodes( $text ); $text = apply_filters('the_content', $text); $text = str_replace(']]>', ']]&gt;', $text); $excerpt_length = apply_filters('excerpt_length', 55); $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]'); $text = wp_trim_words( $text, $excerpt_length, $excerpt_more ); /* If the post_content contains a <!--more--> OR a <!--nextpage--> quicktag * AND the more link has not been added already * then we add it now */ if ( ( preg_match('/<!--more(.*?)?-->/', $post->post_content ) || preg_match('/<!--nextpage-->/', $post->post_content ) ) && strpos($text,$excerpt_more) === false ) { $text .= $excerpt_more; } } return apply_filters('boldr_trim_excerpt', $text, $raw_excerpt); } remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' ); add_filter( 'get_the_excerpt', 'boldr_trim_excerpt' ); /* * Create dropdown menu (used in responsive mode) * Requires a custom menu to be set (won't work with fallback menu) */ function boldr_dropdown_nav_menu () { $menu_name = 'primary'; if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) { if ($menu = wp_get_nav_menu_object( $locations[ $menu_name ] ) ) { $menu_items = wp_get_nav_menu_items($menu->term_id); $menu_list = '<select id="dropdown-menu">'; $menu_list .= '<option value="">Menu</option>'; foreach ( (array) $menu_items as $key => $menu_item ) { $title = $menu_item->title; $url = $menu_item->url; if($url != "#" ) $menu_list .= '<option value="' . $url . '">' . $title . '</option>'; } $menu_list .= '</select>'; // $menu_list now ready to output echo $menu_list; } } } /* * Find whether post page needs comments pagination links (used in comments.php) */ function boldr_page_has_comments_nav() { global $wp_query; return ($wp_query->max_num_comment_pages > 1); } function boldr_page_has_next_comments_link() { global $wp_query; $max_cpage = $wp_query->max_num_comment_pages; $cpage = get_query_var( 'cpage' ); return ( $max_cpage > $cpage ); } function boldr_page_has_previous_comments_link() { $cpage = get_query_var( 'cpage' ); return ($cpage > 1); } /* * Find whether attachement page needs navigation links (used in single.php) */ function boldr_adjacent_image_link($prev = true) { global $post; $post = get_post($post); $attachments = array_values(get_children("post_parent=$post->post_parent&post_type=attachment&post_mime_type=image&orderby=\"menu_order ASC, ID ASC\"")); foreach ( $attachments as $k => $attachment ) if ( $attachment->ID == $post->ID ) break; $k = $prev ? $k - 1 : $k + 1; if ( isset($attachments[$k]) ) return true; else return false; } /* * Framework Elements */ include_once('functions/icefit-options/settings.php'); // Admin Settings Panel ?>
delfintrinidadIV/firstproject
wp-content/themes/boldr-lite/functions.php
PHP
gpl-2.0
11,779
<?php include('koneksi.php'); session_start(); if(!isset($_SESSION['user'])){header("location:index.php");} if(isset($_SESSION['user'])) { unset($_SESSION); session_destroy(); echo ("<SCRIPT LANGUAGE='JavaScript'>alert('Anda Berhasil Logout') window.location.href='index.php';</SCRIPT>"); } ?>
wawakaka/basdat
www/logout.php
PHP
gpl-2.0
294
<?php namespace FluidTYPO3\Vhs\ViewHelpers\Math; /* * This file is part of the FluidTYPO3/Vhs project under GPLv2 or later. * * For the full copyright and license information, please read the * LICENSE.md file that was distributed with this source code. */ use FluidTYPO3\Vhs\Traits\ArrayConsumingViewHelperTrait; use TYPO3\CMS\Fluid\Core\ViewHelper\Exception; /** * Base class: Math ViewHelpers operating on one number or an * array of numbers. */ abstract class AbstractMultipleMathViewHelper extends AbstractSingleMathViewHelper { use ArrayConsumingViewHelperTrait; /** * @return void */ public function initializeArguments() { parent::initializeArguments(); $this->registerArgument('b', 'mixed', 'Second number or Iterator/Traversable/Array for calculation', true); } /** * @return mixed * @throw Exception */ public function render() { $a = $this->getInlineArgument(); $b = $this->arguments['b']; return $this->calculate($a, $b); } /** * @param mixed $a * @param mixed $b * @return mixed * @throws Exception */ protected function calculate($a, $b = null) { if ($b === null) { throw new Exception('Required argument "b" was not supplied', 1237823699); } $aIsIterable = $this->assertIsArrayOrIterator($a); $bIsIterable = $this->assertIsArrayOrIterator($b); if (true === $aIsIterable) { $a = $this->arrayFromArrayOrTraversableOrCSV($a); foreach ($a as $index => $value) { $bSideValue = true === $bIsIterable ? $b[$index] : $b; $a[$index] = $this->calculateAction($value, $bSideValue); } return $a; } elseif (true === $bIsIterable) { // condition matched if $a is not iterable but $b is. throw new Exception( 'Math operation attempted using an iterator $b against a numeric value $a. Either both $a and $b, ' . 'or only $a, must be array/Iterator', 1351890876 ); } return $this->calculateAction($a, $b); } }
ahmedRguei/job
typo3conf/ext/vhs/Classes/ViewHelpers/Math/AbstractMultipleMathViewHelper.php
PHP
gpl-2.0
2,206
var events = {}; function showEvent(e) { eid = e.getAttribute('data-event-id'); fid = e.getAttribute('data-frame-id'); var url = '?view=event&eid='+eid+'&fid='+fid; url += filterQuery; window.location.href = url; //video element is blocking video elements elsewhere in chrome possible interaction with mouseover event? //FIXME unless an exact cause can be determined should store all video controls and do something to the other controls when we want to load a new video seek etc or whatever may block /*var vid= $('preview'); vid.oncanplay=null; // vid.currentTime=vid.currentTime-0.1; vid.pause();*/ } function createEventHtml(zm_event, frame) { var eventHtml = new Element('div'); if ( zm_event.Archived > 0 ) { eventHtml.addClass('archived'); } new Element('p').inject(eventHtml).set('text', monitors[zm_event.MonitorId].Name); new Element('p').inject(eventHtml).set('text', zm_event.Name+(frame?('('+frame.FrameId+')'):'')); new Element('p').inject(eventHtml).set('text', zm_event.StartTime+' - '+zm_event.Length+'s'); new Element('p').inject(eventHtml).set('text', zm_event.Cause); if ( event.Notes ) { new Element('p').inject(eventHtml).set('text', event.Notes); } if ( event.Archived > 0 ) { new Element('p').inject(eventHtml).set( 'text', archivedString); } return eventHtml; } function showEventDetail( eventHtml ) { $('instruction').addClass( 'hidden' ); $('eventData').empty(); $('eventData').adopt( eventHtml ); $('eventData').removeClass( 'hidden' ); } function eventDataResponse( respObj, respText ) { var zm_event = respObj.event; if ( !zm_event ) { console.log('Null event'); return; } events[zm_event.Id] = zm_event; if ( respObj.loopback ) { requestFrameData(zm_event.Id, respObj.loopback); } } function frameDataResponse( respObj, respText ) { var frame = respObj.frameimage; if ( !frame.FrameId ) { console.log('Null frame'); return; } var zm_event = events[frame.EventId]; if ( !zm_event ) { console.error('No event '+frame.eventId+' found'); return; } if ( !zm_event['frames'] ) { console.log("No frames data in event response"); console.log(zm_event); console.log(respObj); zm_event['frames'] = {}; } zm_event['frames'][frame.FrameId] = frame; zm_event['frames'][frame.FrameId]['html'] = createEventHtml( zm_event, frame ); showEventData(frame.EventId, frame.FrameId); } function showEventData(eventId, frameId) { if ( events[eventId] ) { var zm_event = events[eventId]; if ( zm_event['frames'] ) { if ( zm_event['frames'][frameId] ) { showEventDetail( zm_event['frames'][frameId]['html'] ); var imagePath = 'index.php?view=image&eid='+eventId+'&fid='+frameId; var videoName = zm_event.DefaultVideo; loadEventImage( imagePath, eventId, frameId, zm_event.Width, zm_event.Height, zm_event.Frames/zm_event.Length, videoName, zm_event.Length, zm_event.StartTime, monitors[zm_event.MonitorId]); return; } else { console.log('No frames for ' + frameId); } } else { console.log('No frames'); } } else { console.log('No event for ' + eventId); } } var eventQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: eventDataResponse }); var frameQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: frameDataResponse }); function requestFrameData( eventId, frameId ) { if ( !events[eventId] ) { eventQuery.options.data = "view=request&request=status&entity=event&id="+eventId+"&loopback="+frameId; eventQuery.send(); } else { frameQuery.options.data = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId; frameQuery.send(); } } function previewEvent(slot) { eventId = slot.getAttribute('data-event-id'); frameId = slot.getAttribute('data-frame-id'); if ( events[eventId] ) { showEventData(eventId, frameId); } else { requestFrameData(eventId, frameId); } } function loadEventImage( imagePath, eid, fid, width, height, fps, videoName, duration, startTime, Monitor ) { var vid = $('preview'); var imageSrc = $('imageSrc'); if ( videoName && vid ) { vid.show(); imageSrc.hide(); var newsource=imagePath.slice(0, imagePath.lastIndexOf('/'))+'/'+videoName; //console.log(newsource); //console.log(sources[0].src.slice(-newsource.length)); if ( newsource != vid.currentSrc.slice(-newsource.length) || vid.readyState == 0 ) { //console.log("loading new"); //it is possible to set a long source list here will that be unworkable? var sources = vid.getElementsByTagName('source'); sources[0].src = newsource; var tracks = vid.getElementsByTagName('track'); if (tracks.length) { tracks[0].parentNode.removeChild(tracks[0]); } vid.load(); addVideoTimingTrack(vid, Monitor.LabelFormat, Monitor.Name, duration, startTime); vid.currentTime = fid/fps; } else { if ( ! vid.seeking ) { vid.currentTime=fid/fps; } } } else { if ( vid ) vid.hide(); imageSrc.show(); imageSrc.setProperty('src', imagePath); imageSrc.setAttribute('data-event-id', eid); imageSrc.setAttribute('data-frame-id', fid); imageSrc.onclick=window['showEvent'].bind(imageSrc, imageSrc); } var eventData = $('eventData'); eventData.removeEvent('click'); eventData.addEvent('click', showEvent.pass()); } function tlZoomBounds( minTime, maxTime ) { location.replace('?view='+currentView+filterQuery+'&minTime='+minTime+'&maxTime='+maxTime); } function tlZoomOut() { location.replace('?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+zoom_range); } function tlPanLeft() { location.replace('?view='+currentView+filterQuery+'&midTime='+minTime+'&range='+range); } function tlPanRight() { location.replace('?view='+currentView+filterQuery+'&midTime='+maxTime+'&range='+range); } window.addEventListener("DOMContentLoaded", function() { document.querySelectorAll("div.event").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); document.querySelectorAll("div.activity").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); });
Simpler1/ZoneMinder
web/skins/classic/views/js/timeline.js
JavaScript
gpl-2.0
6,613
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Indexer\Model\Config; use Magento\Framework\Exception\ConfigurationMismatchException; class ConverterTest extends \PHPUnit\Framework\TestCase { /** * @var \Magento\Framework\Indexer\Config\Converter */ protected $model; protected function setUp() { $this->model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->create(\Magento\Framework\Indexer\Config\Converter::class); } public function testConverter() { $pathFiles = __DIR__ . '/_files'; $expectedResult = require $pathFiles . '/result.php'; $path = $pathFiles . '/indexer.xml'; $domDocument = new \DOMDocument(); $domDocument->load($path); $result = $this->model->convert($domDocument); $this->assertEquals($expectedResult, $result); } /** * @return void */ public function testConverterWithCircularDependency() { $pathFiles = __DIR__ . '/_files'; $path = $pathFiles . '/indexer_with_circular_dependency.xml'; $domDocument = new \DOMDocument(); $domDocument->load($path); $this->expectException(ConfigurationMismatchException::class); $this->expectExceptionMessage('Circular dependency references from'); $this->model->convert($domDocument); } /** * @return void */ public function testConverterWithDependencyOnNotExistingIndexer() { $pathFiles = __DIR__ . '/_files'; $path = $pathFiles . '/dependency_on_not_existing_indexer.xml'; $domDocument = new \DOMDocument(); $domDocument->load($path); $this->expectException(ConfigurationMismatchException::class); $this->expectExceptionMessage("Dependency declaration 'indexer_4' in 'indexer_2' to the non-existing indexer."); $this->model->convert($domDocument); } }
kunj1988/Magento2
dev/tests/integration/testsuite/Magento/Indexer/Model/Config/ConverterTest.php
PHP
gpl-2.0
1,991
<?php /** * @package Advanced Module Manager * @version 4.4.6 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2012 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ /** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; /** * HTML View class for the Modules component * * @package Joomla.Administrator * @subpackage com_advancedmodules * @since 1.6 */ class AdvancedModulesViewSelect extends JViewLegacy { protected $state; protected $items; /** * Display the view */ public function display($tpl = null) { $state = $this->get('State'); $items = $this->get('Items'); // Check for errors. if (count($errors = $this->get('Errors'))) { JError::raiseError(500, implode("\n", $errors)); return false; } $this->state = & $state; $this->items = & $items; $this->addToolbar(); parent::display($tpl); } /** * Add the page title and toolbar. * * @since 3.0 */ protected function addToolbar() { // Add page title JToolbarHelper::title(JText::_('COM_MODULES_MANAGER_MODULES'), 'module.png'); // Get the toolbar object instance $bar = JToolBar::getInstance('toolbar'); // Cancel $title = JText::_('JTOOLBAR_CANCEL'); $dhtml = "<button onClick=\"location.href='index.php?option=com_modules'\" class=\"btn\"> <i class=\"icon-remove\" title=\"$title\"></i> $title</button>"; $bar->appendButton('Custom', $dhtml, 'new'); } }
lau-ibarra/ETISIGChacoJoomla
administrator/components/com_advancedmodules/views/select/view.html.php
PHP
gpl-2.0
1,717
<?php /** * The sidebar containing the main widget area. * * @package smoothie */ if ( ! is_active_sidebar( 'sidebar-1' ) ) { return; } ?> <div id="secondary" class="widget-area" role="complementary"> <?php dynamic_sidebar( 'sidebar-1' ); ?> </div><!-- #secondary -->
ashwinmt/wp-ny
wp-content/themes/smoothie/sidebar.php
PHP
gpl-2.0
276
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Opensips_form{ function __construct() { $this->CI = & get_instance(); } function get_opensips_form_fields() { $form['forms'] = array(base_url() . 'opensips/opensips_save/',array("id"=>"opensips_form","name"=>"opensips_form")); $form['Opensips Device'] = array( array('', 'HIDDEN', array('name'=>'id'),'', '', '', ''), array('Username', 'INPUT', array('name' => 'username','size' => '20', 'maxlength' => '15', 'class' => "text field medium"), 'trim|required', 'tOOL TIP', ''), array('password', 'PASSWORD', array('name' => 'password','size' => '20', 'maxlength' => '15', 'class' => "text field medium"), 'trim|required', 'tOOL TIP', ''), array('Account', 'accountcode', 'SELECT', '', '', 'tOOL TIP', 'Please Enter account number', 'number', 'number', 'accounts', 'build_dropdown', 'where_arr', array("reseller_id" => "0","type"=>"0", "deleted" => "0")), array('Rate Group', 'pricelist_id', 'SELECT', '', '', 'tOOL TIP', 'Please Enter account number', 'id', 'name', 'pricelists', 'build_dropdown', 'reseller_id', '0'), array('Domain', 'INPUT', array('name' => 'domain','size' => '20', 'maxlength' => '15', 'class' => "text field medium"), '', 'tOOL TIP', '') ); $form['button_save'] = array('name' => 'action', 'content' =>'Save' , 'value' => 'save', 'type' => 'button','id'=>'submit', 'class' => 'ui-state-default float-right ui-corner-all ui-button'); $form['button_cancel'] = array('name' => 'action', 'content' => 'Cancel', 'value' => 'cancel', 'type' => 'button', 'class' => 'ui-state-default float-right ui-corner-all ui-button', 'onclick' => 'return redirect_page(\'NULL\')'); return $form; } function get_dispatcher_form_fields() { $form['forms'] = array(base_url() . 'opensips/dispatcher_save/',array("id"=>"opensips_dispatcher_form","name"=>"opensips_dispatcher_form")); $form['Dispatcher Information'] = array( array('', 'HIDDEN', array('name'=>'id'),'', '', '', ''), array('Setid', 'INPUT', array('name' => 'setid','size' => '20', 'maxlength' => '15', 'class' => "text field medium"), '', 'tOOL TIP', ''), array('Destination', 'INPUT', array('name' => 'destination','size' => '20', 'maxlength' => '15', 'class' => "text field medium"), 'trim|required', 'tOOL TIP', ''), array('Flags', 'INPUT', array('name' => 'flags','size' => '20', 'maxlength' => '15', 'class' => "text field medium"), '', 'tOOL TIP', ''), array('Weight', 'INPUT', array('name' => 'weight','size' => '20', 'maxlength' => '15', 'class' => "text field medium"), '', 'tOOL TIP', ''), array('Attrs', 'INPUT', array('name' => 'attrs','size' => '20', 'maxlength' => '15', 'class' => "text field medium"), '', 'tOOL TIP', ''), array('Description', 'INPUT', array('name' => 'description','size' => '100', 'maxlength' => '100', 'class' => "text field medium"), '', 'tOOL TIP', ''), ); $form['button_save'] = array('name' => 'action', 'content' =>'Save' , 'value' => 'save', 'type' => 'button','id'=>'submit', 'class' => 'ui-state-default float-right ui-corner-all ui-button'); $form['button_cancel'] = array('name' => 'action', 'content' => 'Cancel', 'value' => 'cancel', 'type' => 'button', 'class' => 'ui-state-default float-right ui-corner-all ui-button', 'onclick' => 'return redirect_page(\'/opensips/dispatcher_list/\')'); return $form; } function get_search_opensips_form() { $form['forms'] = array("",array('id'=>"device_search")); $form['Search Devices'] = array( array('', 'HIDDEN', 'ajax_search','1', '', '', ''), array('', 'HIDDEN', 'advance_search','1', '', '', ''), array('Username', 'INPUT', array('name' => 'username[username]','','size' => '20','maxlength' => '15', 'class' => "text field "), '', 'tOOL TIP', '1', 'username[username-string]', '', '','', 'search_string_type', ''), ); $form['button_search'] = array('name' => 'action', 'id'=>"opensipsdevice_search_btn",'content' => 'Search', 'value' => 'save', 'type' => 'button', 'class' => 'ui-state-default float-right ui-corner-all ui-button'); $form['button_reset'] = array('name' => 'action','id'=>"id_reset", 'content' => 'Clear Search Filter', 'value' => 'cancel', 'type' => 'reset', 'class' => 'ui-state-default float-right ui-corner-all ui-button'); return $form; } function get_search_dispatcher_form() { $form['forms'] = array("",array('id'=>"dispatcher_search")); $form['Search Dispatcher'] = array( array('', 'HIDDEN', 'ajax_search','1', '', '', ''), array('', 'HIDDEN', 'advance_search','1', '', '', ''), array('Username', 'INPUT', array('name' => 'username[username]','','size' => '20','maxlength' => '15', 'class' => "text field "), '', 'tOOL TIP', '1', 'username[username-string]', '', '','', 'search_string_type', ''), ); $form['button_search'] = array('name' => 'action', 'id'=>"opensipsdispatcher_search_btn",'content' => 'Search', 'value' => 'save', 'type' => 'button', 'class' => 'ui-state-default float-right ui-corner-all ui-button'); $form['button_reset'] = array('name' => 'action','id'=>"id_reset", 'content' => 'Clear Search Filter', 'value' => 'cancel', 'type' => 'reset', 'class' => 'ui-state-default float-right ui-corner-all ui-button'); return $form; } function build_opensips_list(){ // array(display name, width, db_field_parent_table,feidname, db_field_child_table,function name); $grid_field_arr = json_encode(array( array("Username","130","username","","",""), array("Password","130","password","","",""), array("Domain","130","domain","","",""), array("Action", "120", "", "", "", array("EDIT" => array("url" => "/opensips/opensips_edit/", "mode" => "popup"), "DELETE" => array("url" => "/opensips/opensips_remove/", "mode" => "single"))) )); return $grid_field_arr; } function build_opensipsdispatcher_list(){ // array(display name, width, db_field_parent_table,feidname, db_field_child_table,function name); $grid_field_arr = json_encode(array( array("Set id","130","setid","","",""), array("Destination","130","destination","","",""), array("Flags","130","flags","","",""), array("Weight","130","weight","","",""), array("Attrs","130","attrs","","",""), array("Description","130","description","","",""), array("Action", "120", "", "", "", array("EDIT" => array("url" => "/opensips/dispatcher_edit/", "mode" => "popup"), "DELETE" => array("url" => "/opensips/dispatcher_remove/", "mode" => "single"))) )); return $grid_field_arr; } function build_grid_buttons(){ $buttons_json = json_encode(array(array("Add Devices","add","button_action","/opensips/opensips_add/",'popup'), array("Refresh","reload","/accounts/clearsearchfilter/"))); return $buttons_json; } function build_grid_dispatcherbuttons(){ $buttons_json = json_encode(array(array("Add Dispatcher","add","button_action","/opensips/dispatcher_add/","popup"), array("Refresh","reload","/accounts/clearsearchfilter/"))); return $buttons_json; } function get_opensips_form_fields_for_customer($accountid){ // echo $this->CI->session->userdata("logintype"); if($this->CI->session->userdata("logintype")== '0' || $this->CI->session->userdata("logintype") == '1'){ $link = base_url().'opensips/customer_opensips_save/true'; }else{ $link = base_url().'opensips/opensips_save/true'; } $form['forms'] = array($link,array("id"=>"opensips_form","name"=>"opensips_form")); $form['Opensips Device'] = array( array('', 'HIDDEN', array('name'=>'id'),'', '', '', ''), array('', 'HIDDEN', array('name' => 'accountcode','value'=>$this->CI->common->get_field_name('number','accounts',array('id'=>$accountid))), '', '', '', ''), array('Username', 'INPUT', array('name' => 'username','size' => '20', 'maxlength' => '15', 'class' => "text field medium"), 'trim|required', 'tOOL TIP', 'Please Enter account number'), array('password', 'PASSWORD', array('name' => 'password','size' => '20', 'maxlength' => '15', 'class' => "text field medium"), 'trim|required', 'tOOL TIP', 'Please Enter account number'), array('Rate Group', 'pricelist_id', 'SELECT', '', '', 'tOOL TIP', 'Please Enter account number', 'id', 'name', 'pricelists', 'build_dropdown', 'reseller_id', '0'), array('Domain', 'INPUT', array('name' => 'domain','size' => '20', 'maxlength' => '15', 'class' => "text field medium"), '', 'tOOL TIP', 'Please Enter account number') ); $form['button_save'] = array('name' => 'action', 'content' =>'Save' , 'value' => 'save', 'type' => 'button','id'=>'submit', 'class' => 'ui-state-default float-right ui-corner-all ui-button'); $form['button_cancel'] = array('name' => 'action', 'content' => 'Cancel', 'value' => 'cancel', 'type' => 'button', 'class' => 'ui-state-default float-right ui-corner-all ui-button', 'onclick' => 'return redirect_page(\'NULL\')'); return $form; } function opensips_customer_build_grid_buttons($accountid) { $buttons_json = json_encode(array(array("Add Devices", "add", "button_action", "/opensips/customer_opensips_add/$accountid/","popup"), array("Refresh", "reload", "/accounts/clearsearchfilter/"))); return $buttons_json; } function opensips_customer_build_opensips_list($accountid){ // array(display name, width, db_field_parent_table,feidname, db_field_child_table,function name); $grid_field_arr = json_encode(array( array("Username","130","username","","",""), array("Password","130","password","","",""), array("Domain","130","domain","","",""), array("Action", "120", "", "", "", array("EDIT" => array("url" => '/accounts/customer_opensips_action/edit/'.$accountid.'/', "mode" => "popup"), "DELETE" => array("url" => '/accounts/customer_opensips_action/delete/'.$accountid."/", "mode" => "popup"))) )); return $grid_field_arr; } } ?>
mayank19882001/ASTPP
web_interface/astpp/application/modules/opensips/libraries/opensips_form.php
PHP
gpl-2.0
11,170
#include <QString> #include <QtGlobal> #include <QFileInfo> #include <QtXml> #include "meshmodel.h" #include "meshlabdocumentxml.h" #include <wrap/qt/shot_qt.h> bool MeshDocumentToXMLFile(MeshDocument &md, QString filename, bool onlyVisibleLayers) { md.setFileName(filename); QFileInfo fi(filename); QDir tmpDir = QDir::current(); QDir::setCurrent(fi.absoluteDir().absolutePath()); QDomDocument doc = MeshDocumentToXML(md, onlyVisibleLayers); QFile file(filename); file.open(QIODevice::WriteOnly); QTextStream qstream(&file); doc.save(qstream,1); file.close(); QDir::setCurrent(tmpDir.absolutePath()); return true; } QDomElement Matrix44fToXML(vcg::Matrix44f &m, QDomDocument &doc) { QDomElement matrixElem = doc.createElement("MLMatrix44"); QString Row[4]; for(int i=0;i<4;++i) Row[i] =QString("%1 %2 %3 %4 \n").arg(m[i][0]).arg(m[i][1]).arg(m[i][2]).arg(m[i][3]); QDomText nd = doc.createTextNode("\n"+Row[0]+Row[1]+Row[2]+Row[3]); matrixElem.appendChild(nd); return matrixElem; } bool MeshDocumentFromXML(MeshDocument &md, QString filename) { QFile qf(filename); QFileInfo qfInfo(filename); QDir tmpDir = QDir::current(); QDir::setCurrent(qfInfo.absoluteDir().absolutePath()); if( !qf.open(QIODevice::ReadOnly ) ) return false; QString project_path = qfInfo.absoluteFilePath(); QDomDocument doc("MeshLabDocument"); //It represents the XML document if(!doc.setContent( &qf )) return false; QDomElement root = doc.documentElement(); QDomNode node; node = root.firstChild(); //Devices while(!node.isNull()){ if(QString::compare(node.nodeName(),"MeshGroup")==0) { QDomNode mesh; QString filen, label; mesh = node.firstChild(); while(!mesh.isNull()){ //return true; filen=mesh.attributes().namedItem("filename").nodeValue(); label=mesh.attributes().namedItem("label").nodeValue(); /*MeshModel* mm = */md.addNewMesh(filen,label); QDomNode tr=mesh.firstChild(); if(!tr.isNull() && QString::compare(tr.nodeName(),"MLMatrix44")==0) { vcg::Matrix44f trm; if (tr.childNodes().size() == 1) { QStringList values = tr.firstChild().nodeValue().split(" ", QString::SkipEmptyParts); for(int y = 0; y < 4; y++) for(int x = 0; x < 4; x++) md.mm()->cm.Tr[y][x] = values[x + 4*y].toFloat(); } } mesh=mesh.nextSibling(); } } // READ IN POINT CORRESPONDECES INCOMPLETO!! else if(QString::compare(node.nodeName(),"RasterGroup")==0) { QDomNode raster; QString filen, label; raster = node.firstChild(); while(!raster.isNull()) { //return true; md.addNewRaster(); QString labelRaster=raster.attributes().namedItem("label").nodeValue(); md.rm()->setLabel(labelRaster); QDomNode sh=raster.firstChild(); ReadShotFromQDomNode(md.rm()->shot,sh); QDomElement el = raster.firstChildElement("Plane"); while(!el.isNull()) { QString filen = el.attribute("fileName"); QFileInfo fi(filen); QString sem = el.attribute("semantic"); QString nm = fi.absoluteFilePath(); md.rm()->addPlane(new Plane(fi.absoluteFilePath(),sem)); el = node.nextSiblingElement("Plane"); } raster=raster.nextSibling(); } } node = node.nextSibling(); } QDir::setCurrent(tmpDir.absolutePath()); qf.close(); return true; } QDomElement MeshModelToXML(MeshModel *mp, QDomDocument &doc) { QDomElement meshElem = doc.createElement("MLMesh"); meshElem.setAttribute("label",mp->label()); meshElem.setAttribute("filename",mp->relativePathName()); meshElem.appendChild(Matrix44fToXML(mp->cm.Tr,doc)); return meshElem; } QDomElement RasterModelToXML(RasterModel *mp,QDomDocument &doc) { QDomElement rasterElem = doc.createElement("MLRaster"); rasterElem.setAttribute("label",mp->label()); rasterElem.appendChild(WriteShotToQDomNode(mp->shot,doc)); for(int ii = 0;ii < mp->planeList.size();++ii) rasterElem.appendChild(PlaneToXML(mp->planeList[ii],mp->par->pathName(),doc)); return rasterElem; } QDomElement PlaneToXML(Plane* pl,const QString& basePath,QDomDocument& doc) { QDomElement planeElem = doc.createElement("Plane"); QDir dir(basePath); planeElem.setAttribute("fileName",dir.relativeFilePath(pl->fullPathFileName)); planeElem.setAttribute("semantic",pl->semantic); return planeElem; } QDomDocument MeshDocumentToXML(MeshDocument &md, bool onlyVisibleLayers) { QDomDocument ddoc("MeshLabDocument"); QDomElement root = ddoc.createElement("MeshLabProject"); ddoc.appendChild( root ); QDomElement mgroot = ddoc.createElement("MeshGroup"); foreach(MeshModel *mmp, md.meshList) { if((!onlyVisibleLayers) || (mmp->visible)) { QDomElement meshElem = MeshModelToXML(mmp, ddoc); mgroot.appendChild(meshElem); } } root.appendChild(mgroot); QDomElement rgroot = ddoc.createElement("RasterGroup"); foreach(RasterModel *rmp, md.rasterList) { QDomElement rasterElem = RasterModelToXML(rmp, ddoc); rgroot.appendChild(rasterElem); } root.appendChild(rgroot); // tag.setAttribute(QString("name"),(*ii).first); // RichParameterSet &par=(*ii).second; // QList<RichParameter*>::iterator jj; // RichParameterXMLVisitor v(doc); // for(jj=par.paramList.begin();jj!=par.paramList.end();++jj) // { // (*jj)->accept(v); // tag.appendChild(v.parElem); // } // root.appendChild(tag); // } // return ddoc; }
guerrerocarlos/meshlab
src/common/meshlabdocumentxml.cpp
C++
gpl-2.0
5,491
package org.mo.logic.process; import org.mo.com.xml.IXmlObject; import org.mo.eng.store.IXmlConfigConsole; public interface ILogicProcessConsole extends IXmlConfigConsole<IXmlObject> { }
favedit/MoPlatform
mo-3-logic/src/logic-java/org/mo/logic/process/ILogicProcessConsole.java
Java
gpl-2.0
204
/* * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Common.h" #include "PlayerDump.h" #include "Database/DatabaseEnv.h" #include "Database/SQLStorage.h" #include "UpdateFields.h" #include "ObjectMgr.h" // Character Dump tables #define DUMP_TABLE_COUNT 21 struct DumpTable { char const* name; DumpTableType type; }; static DumpTable dumpTables[DUMP_TABLE_COUNT] = { { "characters", DTT_CHARACTER }, { "character_achievement", DTT_CHAR_TABLE }, { "character_achievement_progress", DTT_CHAR_TABLE }, { "character_queststatus", DTT_CHAR_TABLE }, { "character_reputation", DTT_CHAR_TABLE }, { "character_spell", DTT_CHAR_TABLE }, { "character_spell_cooldown", DTT_CHAR_TABLE }, { "character_action", DTT_CHAR_TABLE }, { "character_aura", DTT_CHAR_TABLE }, { "character_homebind", DTT_CHAR_TABLE }, { "character_ticket", DTT_CHAR_TABLE }, { "character_inventory", DTT_INVENTORY }, { "mail", DTT_MAIL }, { "mail_items", DTT_MAIL_ITEM }, { "item_instance", DTT_ITEM }, { "character_gifts", DTT_ITEM_GIFT }, { "item_text", DTT_ITEM_TEXT }, { "character_pet", DTT_PET }, { "pet_aura", DTT_PET_TABLE }, { "pet_spell", DTT_PET_TABLE }, { "pet_spell_cooldown", DTT_PET_TABLE }, }; // Low level functions static bool findtoknth(std::string &str, int n, std::string::size_type &s, std::string::size_type &e) { int i; s = e = 0; std::string::size_type size = str.size(); for(i = 1; s < size && i < n; s++) if(str[s] == ' ') ++i; if (i < n) return false; e = str.find(' ', s); return e != std::string::npos; } std::string gettoknth(std::string &str, int n) { std::string::size_type s = 0, e = 0; if(!findtoknth(str, n, s, e)) return ""; return str.substr(s, e-s); } bool findnth(std::string &str, int n, std::string::size_type &s, std::string::size_type &e) { s = str.find("VALUES ('")+9; if (s == std::string::npos) return false; do { e = str.find("'",s); if (e == std::string::npos) return false; } while(str[e-1] == '\\'); for(int i = 1; i < n; ++i) { do { s = e+4; e = str.find("'",s); if (e == std::string::npos) return false; } while (str[e-1] == '\\'); } return true; } std::string gettablename(std::string &str) { std::string::size_type s = 13; std::string::size_type e = str.find(_TABLE_SIM_, s); if (e == std::string::npos) return ""; return str.substr(s, e-s); } bool changenth(std::string &str, int n, const char *with, bool insert = false, bool nonzero = false) { std::string::size_type s, e; if(!findnth(str,n,s,e)) return false; if(nonzero && str.substr(s,e-s) == "0") return true; // not an error if(!insert) str.replace(s,e-s, with); else str.insert(s, with); return true; } std::string getnth(std::string &str, int n) { std::string::size_type s, e; if(!findnth(str,n,s,e)) return ""; return str.substr(s, e-s); } bool changetoknth(std::string &str, int n, const char *with, bool insert = false, bool nonzero = false) { std::string::size_type s = 0, e = 0; if(!findtoknth(str, n, s, e)) return false; if(nonzero && str.substr(s,e-s) == "0") return true; // not an error if(!insert) str.replace(s, e-s, with); else str.insert(s, with); return true; } uint32 registerNewGuid(uint32 oldGuid, std::map<uint32, uint32> &guidMap, uint32 hiGuid) { std::map<uint32, uint32>::const_iterator itr = guidMap.find(oldGuid); if(itr != guidMap.end()) return itr->second; uint32 newguid = hiGuid + guidMap.size(); guidMap[oldGuid] = newguid; return newguid; } bool changeGuid(std::string &str, int n, std::map<uint32, uint32> &guidMap, uint32 hiGuid, bool nonzero = false) { char chritem[20]; uint32 oldGuid = atoi(getnth(str, n).c_str()); if (nonzero && oldGuid == 0) return true; // not an error uint32 newGuid = registerNewGuid(oldGuid, guidMap, hiGuid); snprintf(chritem, 20, "%d", newGuid); return changenth(str, n, chritem, false, nonzero); } bool changetokGuid(std::string &str, int n, std::map<uint32, uint32> &guidMap, uint32 hiGuid, bool nonzero = false) { char chritem[20]; uint32 oldGuid = atoi(gettoknth(str, n).c_str()); if (nonzero && oldGuid == 0) return true; // not an error uint32 newGuid = registerNewGuid(oldGuid, guidMap, hiGuid); snprintf(chritem, 20, "%d", newGuid); return changetoknth(str, n, chritem, false, nonzero); } std::string CreateDumpString(char const* tableName, QueryResult *result) { if(!tableName || !result) return ""; std::ostringstream ss; ss << "INSERT INTO "<< _TABLE_SIM_ << tableName << _TABLE_SIM_ << " VALUES ("; Field *fields = result->Fetch(); for(uint32 i = 0; i < result->GetFieldCount(); ++i) { if (i == 0) ss << "'"; else ss << ", '"; std::string s = fields[i].GetCppString(); CharacterDatabase.escape_string(s); ss << s; ss << "'"; } ss << ");"; return ss.str(); } std::string PlayerDumpWriter::GenerateWhereStr(char const* field, uint32 guid) { std::ostringstream wherestr; wherestr << field << " = '" << guid << "'"; return wherestr.str(); } std::string PlayerDumpWriter::GenerateWhereStr(char const* field, GUIDs const& guids, GUIDs::const_iterator& itr) { std::ostringstream wherestr; wherestr << field << " IN ('"; for(; itr != guids.end(); ++itr) { wherestr << *itr; if(wherestr.str().size() > MAX_QUERY_LEN - 50) // near to max query { ++itr; break; } GUIDs::const_iterator itr2 = itr; if(++itr2 != guids.end()) wherestr << "','"; } wherestr << "')"; return wherestr.str(); } void StoreGUID(QueryResult *result,uint32 field,std::set<uint32>& guids) { Field* fields = result->Fetch(); uint32 guid = fields[field].GetUInt32(); if(guid) guids.insert(guid); } void StoreGUID(QueryResult *result,uint32 data,uint32 field, std::set<uint32>& guids) { Field* fields = result->Fetch(); std::string dataStr = fields[data].GetCppString(); uint32 guid = atoi(gettoknth(dataStr, field).c_str()); if(guid) guids.insert(guid); } // Writing - High-level functions void PlayerDumpWriter::DumpTable(std::string& dump, uint32 guid, char const*tableFrom, char const*tableTo, DumpTableType type) { GUIDs const* guids = NULL; char const* fieldname = NULL; switch ( type ) { case DTT_ITEM: fieldname = "guid"; guids = &items; break; case DTT_ITEM_GIFT: fieldname = "item_guid"; guids = &items; break; case DTT_PET: fieldname = "owner"; break; case DTT_PET_TABLE: fieldname = "guid"; guids = &pets; break; case DTT_MAIL: fieldname = "receiver"; break; case DTT_MAIL_ITEM: fieldname = "mail_id"; guids = &mails; break; case DTT_ITEM_TEXT: fieldname = "id"; guids = &texts; break; default: fieldname = "guid"; break; } // for guid set stop if set is empty if(guids && guids->empty()) return; // nothing to do // setup for guids case start position GUIDs::const_iterator guids_itr; if(guids) guids_itr = guids->begin(); do { std::string wherestr; if(guids) // set case, get next guids string wherestr = GenerateWhereStr(fieldname,*guids,guids_itr); else // not set case, get single guid string wherestr = GenerateWhereStr(fieldname,guid); QueryResult *result = CharacterDatabase.PQuery("SELECT * FROM %s WHERE %s", tableFrom, wherestr.c_str()); if(!result) return; do { // collect guids switch ( type ) { case DTT_INVENTORY: StoreGUID(result,3,items); break; // item guid collection case DTT_ITEM: StoreGUID(result,0,ITEM_FIELD_ITEM_TEXT_ID,texts); break; // item text id collection case DTT_PET: StoreGUID(result,0,pets); break; // pet guid collection case DTT_MAIL: StoreGUID(result,0,mails); // mail id collection StoreGUID(result,7,texts); break; // item text id collection case DTT_MAIL_ITEM: StoreGUID(result,1,items); break; // item guid collection default: break; } dump += CreateDumpString(tableTo, result); dump += "\n"; } while (result->NextRow()); delete result; } while(guids && guids_itr != guids->end()); // not set case iterate single time, set case iterate for all guids } std::string PlayerDumpWriter::GetDump(uint32 guid) { std::string dump; dump += "IMPORTANT NOTE: This sql queries not created for apply directly, use '.pdump load' command in console or client chat instead.\n"; dump += "IMPORTANT NOTE: NOT APPLY ITS DIRECTLY to character DB or you will DAMAGE and CORRUPT character DB\n\n"; // revision check guard QueryNamedResult* result = CharacterDatabase.QueryNamed("SELECT * FROM character_db_version LIMIT 1"); if(result) { QueryFieldNames const& namesMap = result->GetFieldNames(); std::string reqName; for(QueryFieldNames::const_iterator itr = namesMap.begin(); itr != namesMap.end(); ++itr) { if(itr->substr(0,9)=="required_") { reqName = *itr; break; } } if(!reqName.empty()) { // this will fail at wrong character DB version dump += "UPDATE character_db_version SET "+reqName+" = 1 WHERE FALSE;\n\n"; } else sLog.outError("Table 'character_db_version' not have revision guard field, revision guard query not added to pdump."); delete result; } else sLog.outError("Character DB not have 'character_db_version' table, revision guard query not added to pdump."); for(int i = 0; i < DUMP_TABLE_COUNT; ++i) DumpTable(dump, guid, dumpTables[i].name, dumpTables[i].name, dumpTables[i].type); // TODO: Add instance/group.. // TODO: Add a dump level option to skip some non-important tables return dump; } DumpReturn PlayerDumpWriter::WriteDump(const std::string& file, uint32 guid) { FILE *fout = fopen(file.c_str(), "w"); if (!fout) return DUMP_FILE_OPEN_ERROR; std::string dump = GetDump(guid); fprintf(fout,"%s\n",dump.c_str()); fclose(fout); return DUMP_SUCCESS; } // Reading - High-level functions #define ROLLBACK(DR) {CharacterDatabase.RollbackTransaction(); fclose(fin); return (DR);} DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, std::string name, uint32 guid) { // check character count { QueryResult *result = CharacterDatabase.PQuery("SELECT COUNT(guid) FROM characters WHERE account = '%d'", account); uint8 charcount = 0; if (result) { Field *fields=result->Fetch(); charcount = fields[0].GetUInt8(); delete result; if (charcount >= 10) return DUMP_TOO_MANY_CHARS; } } FILE *fin = fopen(file.c_str(), "r"); if (!fin) return DUMP_FILE_OPEN_ERROR; QueryResult * result = NULL; char newguid[20], chraccount[20], newpetid[20], currpetid[20], lastpetid[20]; // make sure the same guid doesn't already exist and is safe to use bool incHighest = true; if (guid != 0 && guid < sObjectMgr.m_hiCharGuid) { result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE guid = '%d'", guid); if (result) { guid = sObjectMgr.m_hiCharGuid; // use first free if exists delete result; } else incHighest = false; } else guid = sObjectMgr.m_hiCharGuid; // normalize the name if specified and check if it exists if (!normalizePlayerName(name)) name = ""; if (ObjectMgr::CheckPlayerName(name,true) == CHAR_NAME_SUCCESS) { CharacterDatabase.escape_string(name); // for safe, we use name only for sql quearies anyway result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str()); if (result) { name = ""; // use the one from the dump delete result; } } else name = ""; // name encoded or empty snprintf(newguid, 20, "%d", guid); snprintf(chraccount, 20, "%d", account); snprintf(newpetid, 20, "%d", sObjectMgr.GeneratePetNumber()); snprintf(lastpetid, 20, "%s", ""); std::map<uint32,uint32> items; std::map<uint32,uint32> mails; std::map<uint32,uint32> itemTexts; char buf[32000] = ""; typedef std::map<uint32, uint32> PetIds; // old->new petid relation typedef PetIds::value_type PetIdsPair; PetIds petids; CharacterDatabase.BeginTransaction(); while(!feof(fin)) { if(!fgets(buf, 32000, fin)) { if(feof(fin)) break; ROLLBACK(DUMP_FILE_BROKEN); } std::string line; line.assign(buf); // skip empty strings size_t nw_pos = line.find_first_not_of(" \t\n\r\7"); if(nw_pos==std::string::npos) continue; // skip NOTE if(line.substr(nw_pos,15)=="IMPORTANT NOTE:") continue; // add required_ check if(line.substr(nw_pos,41)=="UPDATE character_db_version SET required_") { if(!CharacterDatabase.Execute(line.c_str())) ROLLBACK(DUMP_FILE_BROKEN); continue; } // determine table name and load type std::string tn = gettablename(line); if(tn.empty()) { sLog.outError("LoadPlayerDump: Can't extract table name from line: '%s'!", line.c_str()); ROLLBACK(DUMP_FILE_BROKEN); } DumpTableType type; uint8 i; for(i = 0; i < DUMP_TABLE_COUNT; ++i) { if (tn == dumpTables[i].name) { type = dumpTables[i].type; break; } } if (i == DUMP_TABLE_COUNT) { sLog.outError("LoadPlayerDump: Unknown table: '%s'!", tn.c_str()); ROLLBACK(DUMP_FILE_BROKEN); } // change the data to server values switch(type) { case DTT_CHAR_TABLE: if(!changenth(line, 1, newguid)) ROLLBACK(DUMP_FILE_BROKEN); break; case DTT_CHARACTER: // character t. { if(!changenth(line, 1, newguid)) ROLLBACK(DUMP_FILE_BROKEN); // guid, data field:guid, items if(!changenth(line, 2, chraccount)) ROLLBACK(DUMP_FILE_BROKEN); std::string vals = getnth(line, 3); if(!changetoknth(vals, OBJECT_FIELD_GUID+1, newguid)) ROLLBACK(DUMP_FILE_BROKEN); for(uint16 field = PLAYER_FIELD_INV_SLOT_HEAD; field < PLAYER_FARSIGHT; field++) if(!changetokGuid(vals, field+1, items, sObjectMgr.m_hiItemGuid, true)) ROLLBACK(DUMP_FILE_BROKEN); if(!changenth(line, 3, vals.c_str())) ROLLBACK(DUMP_FILE_BROKEN); if (name == "") { // check if the original name already exists name = getnth(line, 4); CharacterDatabase.escape_string(name); result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str()); if (result) { delete result; if(!changenth(line, 37, "1")) // rename on login: `at_login` field 37 in raw field list ROLLBACK(DUMP_FILE_BROKEN); } } else if(!changenth(line, 4, name.c_str())) ROLLBACK(DUMP_FILE_BROKEN); break; } case DTT_INVENTORY: // character_inventory t. { if(!changenth(line, 1, newguid)) ROLLBACK(DUMP_FILE_BROKEN); // bag, item if(!changeGuid(line, 2, items, sObjectMgr.m_hiItemGuid, true)) ROLLBACK(DUMP_FILE_BROKEN); if(!changeGuid(line, 4, items, sObjectMgr.m_hiItemGuid)) ROLLBACK(DUMP_FILE_BROKEN); break; } case DTT_ITEM: // item_instance t. { // item, owner, data field:item, owner guid if(!changeGuid(line, 1, items, sObjectMgr.m_hiItemGuid)) ROLLBACK(DUMP_FILE_BROKEN); if(!changenth(line, 2, newguid)) ROLLBACK(DUMP_FILE_BROKEN); std::string vals = getnth(line,3); if(!changetokGuid(vals, OBJECT_FIELD_GUID+1, items, sObjectMgr.m_hiItemGuid)) ROLLBACK(DUMP_FILE_BROKEN); if(!changetoknth(vals, ITEM_FIELD_OWNER+1, newguid)) ROLLBACK(DUMP_FILE_BROKEN); if(!changetokGuid(vals, ITEM_FIELD_ITEM_TEXT_ID+1, itemTexts, sObjectMgr.m_ItemTextId,true)) ROLLBACK(DUMP_FILE_BROKEN); if(!changenth(line, 3, vals.c_str())) ROLLBACK(DUMP_FILE_BROKEN); break; } case DTT_ITEM_GIFT: // character_gift { // guid,item_guid, if(!changenth(line, 1, newguid)) ROLLBACK(DUMP_FILE_BROKEN); if(!changeGuid(line, 2, items, sObjectMgr.m_hiItemGuid)) ROLLBACK(DUMP_FILE_BROKEN); break; } case DTT_PET: // character_pet t { //store a map of old pet id to new inserted pet id for use by type 5 tables snprintf(currpetid, 20, "%s", getnth(line, 1).c_str()); if(strlen(lastpetid)==0) snprintf(lastpetid, 20, "%s", currpetid); if(strcmp(lastpetid,currpetid)!=0) { snprintf(newpetid, 20, "%d", sObjectMgr.GeneratePetNumber()); snprintf(lastpetid, 20, "%s", currpetid); } std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid)); if(petids_iter == petids.end()) { petids.insert(PetIdsPair(atoi(currpetid), atoi(newpetid))); } // item, entry, owner, ... if(!changenth(line, 1, newpetid)) ROLLBACK(DUMP_FILE_BROKEN); if(!changenth(line, 3, newguid)) ROLLBACK(DUMP_FILE_BROKEN); break; } case DTT_PET_TABLE: // pet_aura, pet_spell, pet_spell_cooldown t { snprintf(currpetid, 20, "%s", getnth(line, 1).c_str()); // lookup currpetid and match to new inserted pet id std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid)); if(petids_iter == petids.end()) // couldn't find new inserted id ROLLBACK(DUMP_FILE_BROKEN); snprintf(newpetid, 20, "%d", petids_iter->second); if(!changenth(line, 1, newpetid)) ROLLBACK(DUMP_FILE_BROKEN); break; } case DTT_MAIL: // mail { // id,messageType,stationery,mailtemplate,sender,receiver,subject,itemText if(!changeGuid(line, 1, mails, sObjectMgr.m_mailid)) ROLLBACK(DUMP_FILE_BROKEN); if(!changenth(line, 6, newguid)) ROLLBACK(DUMP_FILE_BROKEN); if(!changeGuid(line, 8, itemTexts, sObjectMgr.m_ItemTextId)) ROLLBACK(DUMP_FILE_BROKEN); break; } case DTT_MAIL_ITEM: // mail_items { // mail_id,item_guid,item_template,receiver if(!changeGuid(line, 1, mails, sObjectMgr.m_mailid)) ROLLBACK(DUMP_FILE_BROKEN); if(!changeGuid(line, 2, items, sObjectMgr.m_hiItemGuid)) ROLLBACK(DUMP_FILE_BROKEN); if(!changenth(line, 4, newguid)) ROLLBACK(DUMP_FILE_BROKEN); break; } case DTT_ITEM_TEXT: // item_text { // id if(!changeGuid(line, 1, itemTexts, sObjectMgr.m_ItemTextId)) ROLLBACK(DUMP_FILE_BROKEN); // add it to cache uint32 id= atoi(getnth(line,1).c_str()); std::string text = getnth(line,2); sObjectMgr.AddItemText(id,text); break; } default: sLog.outError("Unknown dump table type: %u",type); break; } if(!CharacterDatabase.Execute(line.c_str())) ROLLBACK(DUMP_FILE_BROKEN); } CharacterDatabase.CommitTransaction(); sObjectMgr.m_hiItemGuid += items.size(); sObjectMgr.m_mailid += mails.size(); sObjectMgr.m_ItemTextId += itemTexts.size(); if(incHighest) ++sObjectMgr.m_hiCharGuid; fclose(fin); return DUMP_SUCCESS; }
kicho/Ebon-Hold-Converted
src/game/PlayerDump.cpp
C++
gpl-2.0
24,000
<?php /*----------------------------------------------------------------------------------- Plugin Name: BYT Company Address -----------------------------------------------------------------------------------*/ // Add function to widgets_init that'll load our widget. add_action( 'widgets_init', 'byt_address_widgets' ); // Register widget. function byt_address_widgets() { register_widget( 'byt_Address_Widget' ); } // Widget class. class byt_address_widget extends WP_Widget { /*-----------------------------------------------------------------------------------*/ /* Widget Setup /*-----------------------------------------------------------------------------------*/ function byt_Address_Widget() { /* Widget settings. */ $widget_ops = array( 'classname' => 'byt_address_widget', 'description' => __('BookYourTravel: Address Widget', 'bookyourtravel') ); /* Widget control settings. */ $control_ops = array( 'width' => 300, 'height' => 550, 'id_base' => 'byt_address_widget' ); /* Create the widget. */ $this->WP_Widget( 'byt_address_widget', __('BookYourTravel: Address Widget', 'bookyourtravel'), $widget_ops, $control_ops ); } /*-----------------------------------------------------------------------------------*/ /* Display Widget /*-----------------------------------------------------------------------------------*/ function widget( $args, $instance ) { extract( $args ); /* Our variables from the widget settings. */ $title = apply_filters('widget_title', $instance['title'] ); $company_name = $instance['company_name']; $company_address = $instance['company_address']; $company_phone = $instance['company_phone']; $company_email = $instance['company_email']; /* Before widget (defined by themes). */ echo $before_widget; /* Display Widget */ /* Display the widget title if one was input (before and after defined by themes). */ if ( $title ) echo $before_title . $title . $after_title; ?> <article class="byt_address_widget one-fourth"> <h3><?php echo $company_name; ?></h3> <p><?php echo $company_address; ?></p> <p><em>P:</em> <?php _e('24/7 customer support', 'bookyourtravel'); ?>: <?php echo $company_phone; ?></p> <p><em>E:</em> <a href="#" title="<?php echo esc_attr( $company_email ); ?>"><?php echo $company_email; ?></a></p> </article> <?php /* After widget (defined by themes). */ echo $after_widget; } /*-----------------------------------------------------------------------------------*/ /* Update Widget /*-----------------------------------------------------------------------------------*/ function update( $new_instance, $old_instance ) { $instance = $old_instance; /* Strip tags to remove HTML (important for text inputs). */ $instance['title'] = strip_tags( $new_instance['title'] ); $instance['company_name'] = strip_tags( $new_instance['company_name'] ); $instance['company_address'] = strip_tags( $new_instance['company_address'] ); $instance['company_phone'] = strip_tags( $new_instance['company_phone'] ); $instance['company_email'] = strip_tags( $new_instance['company_email'] ); return $instance; } /*-----------------------------------------------------------------------------------*/ /* Widget Settings /*-----------------------------------------------------------------------------------*/ function form( $instance ) { /* Set up some default widget settings. */ $defaults = array( 'title' => '', 'company_name' => 'Book Your Travel LLC', 'company_address' => '1400 Pennsylvania Ave. Washington, DC', 'company_phone' => '1-555-555-5555', 'company_email' => 'info@bookyourtravel.com' ); $instance = wp_parse_args( (array) $instance, $defaults ); ?> <!-- Widget Title: Text Input --> <p> <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php _e('Title:', 'bookyourtravel') ?></label> <input type="text" class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" value="<?php echo esc_attr( $instance['title'] ); ?>" /> </p> <p> <label for="<?php echo esc_attr( $this->get_field_id( 'company_name' ) ); ?>"><?php _e('Company name:', 'bookyourtravel') ?></label> <input type="text" class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'company_name' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'company_name' ) ); ?>" value="<?php echo esc_attr( $instance['company_name']); ?>" /> </p> <p> <label for="<?php echo esc_attr( $this->get_field_id( 'company_address' ) ); ?>"><?php _e('Company address:', 'bookyourtravel') ?></label> <input type="text" class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'company_address' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'company_address' ) ); ?>" value="<?php echo esc_attr( $instance['company_address'] ); ?>" /> </p> <p> <label for="<?php echo esc_attr( $this->get_field_id( 'company_phone' ) ); ?>"><?php _e('Company phone:', 'bookyourtravel') ?></label> <input type="text" class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'company_phone' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'company_phone' ) ); ?>" value="<?php echo esc_attr( $instance['company_phone'] ); ?>" /> </p> <p> <label for="<?php echo esc_attr( $this->get_field_id( 'company_email' ) ); ?>"><?php _e('Company email:', 'bookyourtravel') ?></label> <input type="text" class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'company_email' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'company_email' ) ); ?>" value="<?php echo esc_attr( $instance['company_email'] ); ?>" /> </p> <?php } } ?>
maskcodex/xecuatoi
wp-content/themes/BookYourTravel/includes/plugins/widgets/widget-address.php
PHP
gpl-2.0
5,774
// OF-extend Revision: $Id$ /*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright held by original author \\/ M anipulation | ------------------------------------------------------------------------------- License This file is based on OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \*---------------------------------------------------------------------------*/ #include "createSampledSetFunctionObject.H" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace Foam { defineNamedTemplateTypeNameAndDebug(createSampledSetFunctionObject, 0); addToRunTimeSelectionTable ( functionObject, createSampledSetFunctionObject, dictionary ); } // ************************************************************************* //
alexey4petrov/swak4Foam
Libraries/swakFunctionObjects/createSampledSetFunctionObject.C
C++
gpl-2.0
1,678
//===-- Function.cpp - Implement the Global object classes ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Function class for the VMCore library. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "llvm/IntrinsicInst.h" #include "llvm/LLVMContext.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/LeakDetector.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/StringPool.h" #include "llvm/Support/RWMutex.h" #include "llvm/Support/Threading.h" #include "SymbolTableListTraitsImpl.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/StringExtras.h" using namespace llvm; // Explicit instantiations of SymbolTableListTraits since some of the methods // are not in the public header file... template class llvm::SymbolTableListTraits<Argument, Function>; template class llvm::SymbolTableListTraits<BasicBlock, Function>; //===----------------------------------------------------------------------===// // Argument Implementation //===----------------------------------------------------------------------===// Argument::Argument(const Type *Ty, const Twine &Name, Function *Par) : Value(Ty, Value::ArgumentVal) { Parent = 0; // Make sure that we get added to a function LeakDetector::addGarbageObject(this); if (Par) Par->getArgumentList().push_back(this); setName(Name); } void Argument::setParent(Function *parent) { if (getParent()) LeakDetector::addGarbageObject(this); Parent = parent; if (getParent()) LeakDetector::removeGarbageObject(this); } /// getArgNo - Return the index of this formal argument in its containing /// function. For example in "void foo(int a, float b)" a is 0 and b is 1. unsigned Argument::getArgNo() const { const Function *F = getParent(); assert(F && "Argument is not in a function"); Function::const_arg_iterator AI = F->arg_begin(); unsigned ArgIdx = 0; for (; &*AI != this; ++AI) ++ArgIdx; return ArgIdx; } /// hasByValAttr - Return true if this argument has the byval attribute on it /// in its containing function. bool Argument::hasByValAttr() const { if (!getType()->isPointerTy()) return false; return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal); } /// hasNestAttr - Return true if this argument has the nest attribute on /// it in its containing function. bool Argument::hasNestAttr() const { if (!getType()->isPointerTy()) return false; return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest); } /// hasNoAliasAttr - Return true if this argument has the noalias attribute on /// it in its containing function. bool Argument::hasNoAliasAttr() const { if (!getType()->isPointerTy()) return false; return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias); } /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute /// on it in its containing function. bool Argument::hasNoCaptureAttr() const { if (!getType()->isPointerTy()) return false; return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture); } /// hasSRetAttr - Return true if this argument has the sret attribute on /// it in its containing function. bool Argument::hasStructRetAttr() const { if (!getType()->isPointerTy()) return false; if (this != getParent()->arg_begin()) return false; // StructRet param must be first param return getParent()->paramHasAttr(1, Attribute::StructRet); } /// addAttr - Add a Attribute to an argument void Argument::addAttr(Attributes attr) { getParent()->addAttribute(getArgNo() + 1, attr); } /// removeAttr - Remove a Attribute from an argument void Argument::removeAttr(Attributes attr) { getParent()->removeAttribute(getArgNo() + 1, attr); } //===----------------------------------------------------------------------===// // Helper Methods in Function //===----------------------------------------------------------------------===// LLVMContext &Function::getContext() const { return getType()->getContext(); } const FunctionType *Function::getFunctionType() const { return cast<FunctionType>(getType()->getElementType()); } bool Function::isVarArg() const { return getFunctionType()->isVarArg(); } const Type *Function::getReturnType() const { return getFunctionType()->getReturnType(); } void Function::removeFromParent() { getParent()->getFunctionList().remove(this); } void Function::eraseFromParent() { getParent()->getFunctionList().erase(this); } //===----------------------------------------------------------------------===// // Function Implementation //===----------------------------------------------------------------------===// Function::Function(const FunctionType *Ty, LinkageTypes Linkage, const Twine &name, Module *ParentModule) : GlobalValue(PointerType::getUnqual(Ty), Value::FunctionVal, 0, 0, Linkage, name) { assert(FunctionType::isValidReturnType(getReturnType()) && !getReturnType()->isOpaqueTy() && "invalid return type"); SymTab = new ValueSymbolTable(); // If the function has arguments, mark them as lazily built. if (Ty->getNumParams()) setValueSubclassData(1); // Set the "has lazy arguments" bit. // Make sure that we get added to a function LeakDetector::addGarbageObject(this); if (ParentModule) ParentModule->getFunctionList().push_back(this); // Ensure intrinsics have the right parameter attributes. if (unsigned IID = getIntrinsicID()) setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID))); } Function::~Function() { dropAllReferences(); // After this it is safe to delete instructions. // Delete all of the method arguments and unlink from symbol table... ArgumentList.clear(); delete SymTab; // Remove the function from the on-the-side GC table. clearGC(); } void Function::BuildLazyArguments() const { // Create the arguments vector, all arguments start out unnamed. const FunctionType *FT = getFunctionType(); for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { assert(!FT->getParamType(i)->isVoidTy() && "Cannot have void typed arguments!"); ArgumentList.push_back(new Argument(FT->getParamType(i))); } // Clear the lazy arguments bit. unsigned SDC = getSubclassDataFromValue(); const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1); } size_t Function::arg_size() const { return getFunctionType()->getNumParams(); } bool Function::arg_empty() const { return getFunctionType()->getNumParams() == 0; } void Function::setParent(Module *parent) { if (getParent()) LeakDetector::addGarbageObject(this); Parent = parent; if (getParent()) LeakDetector::removeGarbageObject(this); } // dropAllReferences() - This function causes all the subinstructions to "let // go" of all references that they are maintaining. This allows one to // 'delete' a whole class at a time, even though there may be circular // references... first all references are dropped, and all use counts go to // zero. Then everything is deleted for real. Note that no operations are // valid on an object that has "dropped all references", except operator // delete. // void Function::dropAllReferences() { for (iterator I = begin(), E = end(); I != E; ++I) I->dropAllReferences(); // Delete all basic blocks. They are now unused, except possibly by // blockaddresses, but BasicBlock's destructor takes care of those. while (!BasicBlocks.empty()) BasicBlocks.begin()->eraseFromParent(); } void Function::addAttribute(unsigned i, Attributes attr) { AttrListPtr PAL = getAttributes(); PAL = PAL.addAttr(i, attr); setAttributes(PAL); } void Function::removeAttribute(unsigned i, Attributes attr) { AttrListPtr PAL = getAttributes(); PAL = PAL.removeAttr(i, attr); setAttributes(PAL); } // Maintain the GC name for each function in an on-the-side table. This saves // allocating an additional word in Function for programs which do not use GC // (i.e., most programs) at the cost of increased overhead for clients which do // use GC. static DenseMap<const Function*,PooledStringPtr> *GCNames; static StringPool *GCNamePool; static ManagedStatic<sys::SmartRWMutex<true> > GCLock; bool Function::hasGC() const { sys::SmartScopedReader<true> Reader(*GCLock); return GCNames && GCNames->count(this); } const char *Function::getGC() const { assert(hasGC() && "Function has no collector"); sys::SmartScopedReader<true> Reader(*GCLock); return *(*GCNames)[this]; } void Function::setGC(const char *Str) { sys::SmartScopedWriter<true> Writer(*GCLock); if (!GCNamePool) GCNamePool = new StringPool(); if (!GCNames) GCNames = new DenseMap<const Function*,PooledStringPtr>(); (*GCNames)[this] = GCNamePool->intern(Str); } void Function::clearGC() { sys::SmartScopedWriter<true> Writer(*GCLock); if (GCNames) { GCNames->erase(this); if (GCNames->empty()) { delete GCNames; GCNames = 0; if (GCNamePool->empty()) { delete GCNamePool; GCNamePool = 0; } } } } /// copyAttributesFrom - copy all additional attributes (those not needed to /// create a Function) from the Function Src to this one. void Function::copyAttributesFrom(const GlobalValue *Src) { assert(isa<Function>(Src) && "Expected a Function!"); GlobalValue::copyAttributesFrom(Src); const Function *SrcF = cast<Function>(Src); setCallingConv(SrcF->getCallingConv()); setAttributes(SrcF->getAttributes()); if (SrcF->hasGC()) setGC(SrcF->getGC()); else clearGC(); } /// getIntrinsicID - This method returns the ID number of the specified /// function, or Intrinsic::not_intrinsic if the function is not an /// intrinsic, or if the pointer is null. This value is always defined to be /// zero to allow easy checking for whether a function is intrinsic or not. The /// particular intrinsic functions which correspond to this value are defined in /// llvm/Intrinsics.h. /// unsigned Function::getIntrinsicID() const { const ValueName *ValName = this->getValueName(); if (!ValName) return 0; unsigned Len = ValName->getKeyLength(); const char *Name = ValName->getKeyData(); if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l' || Name[2] != 'v' || Name[3] != 'm') return 0; // All intrinsics start with 'llvm.' #define GET_FUNCTION_RECOGNIZER #include "llvm/Intrinsics.gen" #undef GET_FUNCTION_RECOGNIZER return 0; } std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { assert(id < num_intrinsics && "Invalid intrinsic ID!"); const char * const Table[] = { "not_intrinsic", #define GET_INTRINSIC_NAME_TABLE #include "llvm/Intrinsics.gen" #undef GET_INTRINSIC_NAME_TABLE }; if (numTys == 0) return Table[id]; std::string Result(Table[id]); for (unsigned i = 0; i < numTys; ++i) { if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) { Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) + EVT::getEVT(PTyp->getElementType()).getEVTString(); } else if (Tys[i]) Result += "." + EVT::getEVT(Tys[i]).getEVTString(); } return Result; } const FunctionType *Intrinsic::getType(LLVMContext &Context, ID id, const Type **Tys, unsigned numTys) { const Type *ResultTy = NULL; std::vector<const Type*> ArgTys; bool IsVarArg = false; #define GET_INTRINSIC_GENERATOR #include "llvm/Intrinsics.gen" #undef GET_INTRINSIC_GENERATOR return FunctionType::get(ResultTy, ArgTys, IsVarArg); } bool Intrinsic::isOverloaded(ID id) { const bool OTable[] = { false, #define GET_INTRINSIC_OVERLOAD_TABLE #include "llvm/Intrinsics.gen" #undef GET_INTRINSIC_OVERLOAD_TABLE }; return OTable[id]; } /// This defines the "Intrinsic::getAttributes(ID id)" method. #define GET_INTRINSIC_ATTRIBUTES #include "llvm/Intrinsics.gen" #undef GET_INTRINSIC_ATTRIBUTES Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, unsigned numTys) { // There can never be multiple globals with the same name of different types, // because intrinsics must be a specific type. return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), getType(M->getContext(), id, Tys, numTys))); } // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN #include "llvm/Intrinsics.gen" #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN /// hasAddressTaken - returns true if there are any uses of this function /// other than direct calls or invokes to it. bool Function::hasAddressTaken(const User* *PutOffender) const { for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) { const User *U = *I; if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) return PutOffender ? (*PutOffender = U, true) : true; ImmutableCallSite CS(cast<Instruction>(U)); if (!CS.isCallee(I)) return PutOffender ? (*PutOffender = U, true) : true; } return false; } // vim: sw=2 ai
bathtub/llvm-gcc
llvmCore/lib/VMCore/Function.cpp
C++
gpl-2.0
13,533
// Catch Flames Custom Scripts jQuery(document).ready(function() { /* Waypoint */ if ( jQuery.isFunction( jQuery.fn.waypoint ) ) { var waypointheader = new Waypoint({ element: document.getElementById('page'), handler: function(direction) { if( direction == 'down' ) { jQuery('#header-top').addClass( 'fixed-header' ); } else { jQuery('#header-top').removeClass( 'fixed-header' ); } }, offset: -50 }) var waypointtoup = new Waypoint({ element: document.getElementById('page'), handler: function(direction) { if( direction == 'up' ) { jQuery('#scrollup').fadeOut(); } else { jQuery('#scrollup').fadeIn(); } }, offset: -500 }) } jQuery('#scrollup').click(function () { jQuery('body,html').animate({ scrollTop: 1 }, 800); return false; }); /* Social */ jQuery( '#header-social-toggle' ).on( 'click.catchflames', function( event ) { var that = jQuery( this ), wrapper = jQuery( '#header-social' ); that.toggleClass( 'displayblock' ); wrapper.toggleClass( 'displaynone' ); }); /* Search */ jQuery( '#header-search-toggle' ).on( 'click.catchflames', function( event ) { var that = jQuery( this ), wrapper = jQuery( '#header-search' ); that.toggleClass( 'displayblock' ); wrapper.toggleClass( 'displaynone' ); }); //sidr if ( jQuery.isFunction( jQuery.fn.sidr ) ) { jQuery('#fixed-header-menu').sidr({ name: 'mobile-top-nav', side: 'left' // By default }); jQuery('#header-left-menu').sidr({ name: 'mobile-header-left-nav', side: 'left' // By default }); } });
ilke-zilci/newcomers-wp
wp-content/themes/catch-flames/js/catchflames-custom.js
JavaScript
gpl-2.0
1,623
// $Id: text.cpp 1016 2004-05-07 00:20:29Z rmcruz $ // // SuperTux // Copyright (C) 2004 Tobias Glaesser <tobi.web@gmx.de> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 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 <stdlib.h> #include <string.h> #include "globals.h" #include "defines.h" #include "screen.h" #include "text.h" Text::Text(const std::string& file, int kind_, int w_, int h_) { kind = kind_; w = w_; h = h_; int mx, my; SDL_Surface *conv; int pixels; int i; if(kind == TEXT_TEXT) { //mx = 26; //my = 3; mx = 52; my = 6; } else if(kind == TEXT_NUM) { //mx = 10; //my = 1; mx = 20; my = 2; } else { mx = 0; my = 0; } chars = new Surface(file, USE_ALPHA); // Load shadow font. conv = SDL_DisplayFormatAlpha(chars->impl->get_sdl_surface()); pixels = conv->w * conv->h; SDL_LockSurface(conv); for(i = 0; i < pixels; ++i) { Uint32 *p = (Uint32 *)conv->pixels + i; *p = *p & conv->format->Amask; } SDL_UnlockSurface(conv); SDL_SetAlpha(conv, SDL_SRCALPHA, 128); shadow_chars = new Surface(conv, USE_ALPHA); SDL_FreeSurface(conv); } Text::~Text() { delete chars; delete shadow_chars; } void Text::draw(const char* text, int x, int y, int shadowsize, int update) { if(text != NULL) { if(shadowsize != 0) draw_chars(shadow_chars, text,x+shadowsize,y+shadowsize, update); draw_chars(chars, text,x,y, update); } } void Text::draw_chars(Surface* pchars,const char* text, int x, int y, int update) { int i,j,len; len = strlen(text); int w = this->w; int h = this->h; if(kind == TEXT_TEXT) { for( i = 0, j = 0; i < len; ++i,++j) { if( text[i] >= ' ' && text[i] <= '/') pchars->draw_part((int)(text[i] - ' ')*w, 0 , x+(j*w), y, w, h, 255, update); else if( text[i] >= '0' && text[i] <= '?') pchars->draw_part((int)(text[i] - '0')*w, h*1, x+(j*w), y, w, h, 255, update); else if ( text[i] >= '@' && text[i] <= 'O') pchars->draw_part((int)(text[i] - '@')*w, h*2, x+(j*w), y, w, h, 255, update); else if ( text[i] >= 'P' && text[i] <= '_') pchars->draw_part((int)(text[i] - 'P')*w, h*3, x+(j*w), y, w, h, 255, update); else if ( text[i] >= '`' && text[i] <= 'o') pchars->draw_part((int)(text[i] - '`')*w, h*4, x+(j*w), y, w, h, 255, update); else if ( text[i] >= 'p' && text[i] <= '~') pchars->draw_part((int)(text[i] - 'p')*w, h*5, x+(j*w), y, w, h, 255, update); else if ( text[i] == '\n') { y += h + 2; j = 0; } } } else if(kind == TEXT_NUM) { for( i = 0, j = 0; i < len; ++i, ++j) { if ( text[i] >= '0' && text[i] <= '9') pchars->draw_part((int)(text[i] - '0')*w, 0, x+(j*w), y, w, h, 255, update); else if ( text[i] == '\n') { y += h + 2; j = 0; } } } } void Text::draw_align(const char* text, int x, int y, TextHAlign halign, TextVAlign valign, int shadowsize, int update) { if(text != NULL) { switch (halign) { case A_RIGHT: x += -(strlen(text)*w); break; case A_HMIDDLE: x += -((strlen(text)*w)/2); break; case A_LEFT: // default break; } switch (valign) { case A_BOTTOM: y -= h; break; case A_VMIDDLE: y -= h/2; case A_TOP: // default break; } draw(text, x, y, shadowsize, update); } } void Text::drawf(const char* text, int x, int y, TextHAlign halign, TextVAlign valign, int shadowsize, int update) { if(text != NULL) { if(halign == A_RIGHT) /* FIXME: this doesn't work correctly for strings with newlines.*/ x += screen->w - (strlen(text)*w); else if(halign == A_HMIDDLE) x += screen->w/2 - ((strlen(text)*w)/2); if(valign == A_BOTTOM) y += screen->h - h; else if(valign == A_VMIDDLE) y += screen->h/2 - h/2; draw(text,x,y,shadowsize, update); } } /* --- ERASE TEXT: --- */ void Text::erasetext(const char * text, int x, int y, Surface * ptexture, int update, int shadowsize) { SDL_Rect dest; dest.x = x; dest.y = y; dest.w = strlen(text) * w + shadowsize; dest.h = h; if (dest.w > screen->w) dest.w = screen->w; ptexture->draw_part(dest.x,dest.y,dest.x,dest.y,dest.w,dest.h, 255, update); if (update == UPDATE) update_rect(screen, dest.x, dest.y, dest.w, dest.h); } /* --- ERASE CENTERED TEXT: --- */ void Text::erasecenteredtext(const char * text, int y, Surface * ptexture, int update, int shadowsize) { erasetext(text, screen->w / 2 - (strlen(text) * 8), y, ptexture, update, shadowsize); } /* --- SCROLL TEXT FUNCTION --- */ #define MAX_VEL 10 #define SPEED_INC 0.01 #define SCROLL 60 #define ITEMS_SPACE 4 void display_text_file(const std::string& file, const std::string& surface, float scroll_speed) { Surface* sur = new Surface(datadir + surface, IGNORE_ALPHA); display_text_file(file, sur, scroll_speed); delete sur; } void display_text_file(const std::string& file, Surface* surface, float scroll_speed) { int done; float scroll; float speed; int y; int length; FILE* fi; char temp[1024]; string_list_type names; char filename[1024]; string_list_init(&names); sprintf(filename,"%s/%s", datadir.c_str(), file.c_str()); if((fi = fopen(filename,"r")) != NULL) { while(fgets(temp, sizeof(temp), fi) != NULL) { temp[strlen(temp)-1]='\0'; string_list_add_item(&names,temp); } fclose(fi); } else { string_list_add_item(&names,"File was not found!"); string_list_add_item(&names,filename); string_list_add_item(&names,"Shame on the guy, who"); string_list_add_item(&names,"forgot to include it"); string_list_add_item(&names,"in your SuperTux distribution."); } scroll = 0; speed = scroll_speed / 50; done = 0; length = names.num_items; SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); Uint32 lastticks = SDL_GetTicks(); while(done == 0) { /* in case of input, exit */ SDL_Event event; while(SDL_PollEvent(&event)) switch(event.type) { case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_UP: speed -= SPEED_INC; break; case SDLK_DOWN: speed += SPEED_INC; break; case SDLK_SPACE: case SDLK_RETURN: if(speed >= 0) scroll += SCROLL; break; case SDLK_ESCAPE: done = 1; break; default: break; } break; case SDL_QUIT: done = 1; break; default: break; } if(speed > MAX_VEL) speed = MAX_VEL; else if(speed < -MAX_VEL) speed = -MAX_VEL; /* draw the credits */ surface->draw_bg(); y = 0; for(int i = 0; i < length; i++) { switch(names.item[i][0]) { case ' ': white_small_text->drawf(names.item[i]+1, 0, screen->h+y-int(scroll), A_HMIDDLE, A_TOP, 1); y += white_small_text->h+ITEMS_SPACE; break; case ' ': white_text->drawf(names.item[i]+1, 0, screen->h+y-int(scroll), A_HMIDDLE, A_TOP, 1); y += white_text->h+ITEMS_SPACE; break; case '-': white_big_text->drawf(names.item[i]+1, 0, screen->h+y-int(scroll), A_HMIDDLE, A_TOP, 3); y += white_big_text->h+ITEMS_SPACE; break; default: blue_text->drawf(names.item[i], 0, screen->h+y-int(scroll), A_HMIDDLE, A_TOP, 1); y += blue_text->h+ITEMS_SPACE; break; } } flipscreen(); if(screen->h+y-scroll < 0 && 20+screen->h+y-scroll < 0) done = 1; Uint32 ticks = SDL_GetTicks(); scroll += speed * (ticks - lastticks); lastticks = ticks; if(scroll < 0) scroll = 0; SDL_Delay(10); } string_list_free(&names); SDL_EnableKeyRepeat(0, 0); // disables key repeating Menu::set_current(main_menu); }
jnetterf/supertux-bb10
src/text.cpp
C++
gpl-2.0
9,452
<?php session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {header ("Location: ../security/login_user.php");} switch($_SESSION['login']) { case "super": break; case "write":break; case "read": echo(" <script type='text/javascript'> alert('You do not have permission to edit databases.'); window.location='../main/home.php'; </script> "); break; default: echo(" <script type='text/javascript'> alert('You are not logged in.'); window.location='../security/login_user.php'; </script> "); } include("../jackets/db_connect.php"); //==OPEN DATABASE=== include("../functions/get_all_tenants.php"); //===GET LIST OF ALL TENANTS=== ?> <html> <head> <link rel="stylesheet" type="text/css" href="../style/style.css" /> <script type="text/javascript" src="../functions/set_default_dates.js"></script> <script type="text/javascript" src="../functions/atypical_dates.js"></script> <script type="text/javascript" src="../functions/show_parking.js"></script> <link href="../functions/calendar/calendar/calendar.css" rel="stylesheet" type="text/css" /> <script language="javascript" src="../functions/calendar/calendar/calendar.js"></script> <title>Input Parking</title> </head> <body> <div class='top'> <font class='main'> Parking Lease </font> </div> <?php include("../jackets/main_jacket.php");?> <div class="main"> <div class="text_in"> <div class="box_width"> <font class="box_head">Parking Lease</font></br> <hr class="box_line"> <form name="form_lease" id="form_lease" method="post" action="input_parking02_confirm.php"> <table class="input"> <tr> <td>Tenant ID:</td> <td> <select id="customer_id" name="customer_id" onchange="set_default_dates(this.value,'<?php echo($default_dates_implode) ?>')"> <?php echo($name_box_text); ?> </select> </td> </table> <!--==== PARKING LEASE ==================================--> <table class="input"> <tr id="show_parking_prepay"><td>Prepay Parking?</td> <td> No<input type="radio" name="prepay_parking" id="prepay_parking" value="no" checked="checked"/></br> Yes<input type="radio" name="prepay_parking" id="prepay_parking" value="yes" /> </td> </td> <tr id="show_parking_amount"> <td>Amount </br> <i>&nbsp(Total amount if prepay, otherwise monthly amount added to rent) </i></td> <td><input type="text" name="amount_parking"></td></tr> <tr id="show_parking_spot"><td>Spot</td><td><input type="text" name="spot_parking"></td></tr> </table> <!--==== ATPYPICAL DATES ENTRY =================================--> <table class="input"> <tr> <td>Default Dates</td> <td name="default_dates" id="default_dates"> </td> </tr> <tr><td><font class="box_head">Use Atypical Dates?</font></td> <td>No<input type="radio" name="use_atypical_dates" id="use_atypical_dates" value="no" onClick="hide_atypical_dates('no')" checked="checked"/></br> Yes<input type="radio" name="use_atypical_dates" id="use_atypical_dates" value="yes" onClick="hide_atypical_dates('yes')" /> </td></tr> <tr id="show01"> </tr> <tr id="hide01" style="display:none"> <td>Date Starts: </td><td><?php include('../functions/calendar/date1_include.php'); ?></td> </tr> <tr id="hide02" style="display:none"> <td>Date Expires: </td><td><?php include('../functions/calendar/date2_include.php'); ?></td> </tr> </table> </br></br> <input type="submit" name="submit_parking" value="submit parking"> </form> <script type="text/javascript"> create_find_form();</script> </br> </div> </div> </div> </body> </html>
slavenas/propman
input/input_parking01.php
PHP
gpl-2.0
4,176
#include <GsTLAppli/actions/property_group_actions.h> #include <GsTLAppli/actions/defines.h> #include <GsTLAppli/utils/string_manipulation.h> #include <GsTLAppli/utils/error_messages_handler.h> #include <GsTLAppli/appli/manager_repository.h> #include <GsTLAppli/appli/project.h> #include <GsTLAppli/grid/grid_model/geostat_grid.h> #include <GsTLAppli/grid/grid_model/grid_property.h> #include <GsTLAppli/grid/grid_model/grid_property_set.h> /** * New_property_group */ Named_interface* New_property_group::create_new_interface( std::string& ){ return new New_property_group; } bool New_property_group::init( std::string& parameters, GsTL_project* proj, Error_messages_handler* errors ){ std::vector< std::string > params = String_Op::decompose_string( parameters, Actions::separator, Actions::unique ); if( params.size() < 2 ) { errors->report( "Must have at least 2 parameters, name of the grid and name the group" ); return false; } // Get the grid std::string grid_name = params[0]; SmartPtr<Named_interface> ni = Root::instance()->interface( gridModels_manager + "/" + grid_name); Geostat_grid* grid = dynamic_cast<Geostat_grid*>( ni.raw_ptr() ); if(!grid) { errors->report( "The grid "+params[0]+" does not exist" ); return false; } GsTLGridPropertyGroup* group = grid->get_group(params[1]); if(group) { errors->report( "The goup "+params[1]+" already exist; hence cannot be created" ); return false; } std::string type = ""; if( params.size() == 3 ) { if( params[2] == "General" ) type = ""; else type = params[2]; } group = grid->add_group(params[1],type); if(!group) { errors->report( "The goup "+params[1]+" could no be created; possibly type undefined" ); return false; } for(int i=3; i< params.size(); i++) { GsTLGridProperty* prop = grid->property(params[i]); if(prop == NULL) { errors->report( "The property "+params[i]+" does not exist" ); return false; } } for(int i=3; i< params.size(); i++) { group->add_property(grid->property(params[i])); } proj->update(); return true; } bool New_property_group::exec(){ return true; } /** * Add_properties_to_group:: */ Named_interface* Add_properties_to_group::create_new_interface( std::string& ){ return new Add_properties_to_group; } bool Add_properties_to_group::init( std::string& parameters, GsTL_project* proj, Error_messages_handler* errors ){ std::vector< std::string > params = String_Op::decompose_string( parameters, Actions::separator, Actions::unique ); if( params.size() < 3 ) { errors->report( "Must have at least 3 parameters, name of the grid and name the group and at least one property" ); return false; } // Get the grid SmartPtr<Named_interface> ni = Root::instance()->interface( gridModels_manager + "/" + params[0] ); Geostat_grid* grid = dynamic_cast<Geostat_grid*>( ni.raw_ptr() ); if(!grid) { errors->report( "The grid "+params[0]+" does not exist" ); return false; } GsTLGridPropertyGroup* group = grid->get_group(params[1]); if(!group) { errors->report( "The goup "+params[1]+" does not exist" ); return false; } for(int i=2; i< params.size(); i++) { GsTLGridProperty* prop = grid->property(params[i]); if(prop == NULL) { errors->report( "The property "+params[i]+" does not exist" ); return false; } } for(int i=2; i< params.size(); i++) { if( !group->is_member_property( params[i] ) ) group->add_property(grid->property(params[i])); } return true; } bool Add_properties_to_group::exec(){ return true; } /*---------------------------*/ /** * Add_properties_to_group:: */ Named_interface* Remove_properties_from_group::create_new_interface( std::string& ){ return new Remove_properties_from_group; } bool Remove_properties_from_group::init( std::string& parameters, GsTL_project* proj, Error_messages_handler* errors ){ std::vector< std::string > params = String_Op::decompose_string( parameters, Actions::separator, Actions::unique ); if( params.size() < 3 ) { errors->report( "Must have at least 3 parameters, name of the grid and name the group and at least one property" ); return false; } // Get the grid SmartPtr<Named_interface> ni = Root::instance()->interface( gridModels_manager + "/" + params[0] ); Geostat_grid* grid = dynamic_cast<Geostat_grid*>( ni.raw_ptr() ); if(!grid) { errors->report( "The grid "+params[0]+" does not exist" ); return false; } GsTLGridPropertyGroup* group = grid->get_group(params[1]); if(!group) { errors->report( "The goup "+params[1]+" does not exist" ); return false; } for(int i=2; i< params.size(); i++) { GsTLGridProperty* prop = grid->property(params[i]); if(prop == NULL) { errors->report( "The property "+params[i]+" does not exist" ); return false; } } for(int i=2; i< params.size(); i++) { if( group->is_member_property( params[i] ) ) group->remove_property(grid->property(params[i])); } return true; } bool Remove_properties_from_group::exec(){ return true; } /*-------------------*/ Named_interface* Delete_property_in_group::create_new_interface( std::string& ){ return new Delete_property_in_group; } bool Delete_property_in_group::init( std::string& parameters, GsTL_project* proj, Error_messages_handler* errors ){ std::vector< std::string > params = String_Op::decompose_string( parameters, Actions::separator, Actions::unique ); if( params.size() != 2 ) { errors->report( "Must have 2 parameters, name of the grid and name the group to be deleted" ); return false; } // Get the grid SmartPtr<Named_interface> ni = Root::instance()->interface( gridModels_manager + "/" + params[0] ); Geostat_grid* grid = dynamic_cast<Geostat_grid*>( ni.raw_ptr() ); if(!grid) { errors->report( "The grid "+params[0]+" does not exist" ); return false; } GsTLGridPropertyGroup* group = grid->get_group(params[1]); if(!group) { errors->report( "The goup "+params[1]+" does not exist" ); return false; } //GsTLGridPropertyGroup::property_map::iterator it = group->begin_property(); std::vector<std::string> names = group->property_names(); std::vector<std::string>::const_iterator it = names.begin(); for(; it != names.end(); ++it){ grid->remove_property(*it); } grid->remove_group(params[1]); return true; } bool Delete_property_in_group::exec(){ return true; } /* * -------------------------------- */ Named_interface* Remove_group::create_new_interface( std::string& ){ return new Remove_group; } bool Remove_group::init( std::string& parameters, GsTL_project* proj, Error_messages_handler* errors ){ std::vector< std::string > params = String_Op::decompose_string( parameters, Actions::separator, Actions::unique ); if( params.size() != 2 ) { errors->report( "Must have 2 parameters, name of the grid and name the group to be removed" ); return false; } // Get the grid SmartPtr<Named_interface> ni = Root::instance()->interface( gridModels_manager + "/" + params[0] ); Geostat_grid* grid = dynamic_cast<Geostat_grid*>( ni.raw_ptr() ); if(!grid) { errors->report( "The grid "+params[0]+" does not exist" ); return false; } GsTLGridPropertyGroup* group = grid->get_group(params[1]); if(!group) { errors->report( "The group "+params[1]+" does not exist" ); return false; } grid->remove_group(params[1]); return true; } bool Remove_group::exec(){ return true; }
fnavarrov/SGeMS
GsTLAppli/actions/property_group_actions.cpp
C++
gpl-2.0
8,054
// jshint ignore: start /* eslint-disable */ /** * WordPress dependencies */ const { __ } = wp.i18n; const { Component, createRef, useMemo, Fragment } = wp.element; const { ToggleControl, withSpokenMessages, } = wp.components; const { LEFT, RIGHT, UP, DOWN, BACKSPACE, ENTER, ESCAPE } = wp.keycodes; const { getRectangleFromRange } = wp.dom; const { prependHTTP } = wp.url; const { create, insert, isCollapsed, applyFormat, getTextContent, slice, } = wp.richText; const { URLPopover } = wp.blockEditor; /** * Internal dependencies */ import { createLinkFormat, isValidHref } from './utils'; import PositionedAtSelection from './positioned-at-selection'; import LinkEditor from './link-editor'; import LinkViewer from './link-viewer'; const stopKeyPropagation = ( event ) => event.stopPropagation(); function isShowingInput( props, state ) { return props.addingLink || state.editLink; } const URLPopoverAtLink = ( { isActive, addingLink, value, resetOnMount, ...props } ) => { const anchorRect = useMemo( () => { const selection = window.getSelection(); const range = selection.rangeCount > 0 ? selection.getRangeAt( 0 ) : null; if ( ! range ) { return; } if ( addingLink ) { return getRectangleFromRange( range ); } let element = range.startContainer; // If the caret is right before the element, select the next element. element = element.nextElementSibling || element; while ( element.nodeType !== window.Node.ELEMENT_NODE ) { element = element.parentNode; } const closest = element.closest( 'a' ); if ( closest ) { return closest.getBoundingClientRect(); } }, [ isActive, addingLink, value.start, value.end ] ); if ( ! anchorRect ) { return null; } resetOnMount( anchorRect ); return <URLPopover anchorRect={ anchorRect } { ...props } />; }; class InlineLinkUI extends Component { constructor() { super( ...arguments ); this.editLink = this.editLink.bind( this ); this.submitLink = this.submitLink.bind( this ); this.onKeyDown = this.onKeyDown.bind( this ); this.onChangeInputValue = this.onChangeInputValue.bind( this ); this.setLinkTarget = this.setLinkTarget.bind( this ); this.setNoFollow = this.setNoFollow.bind( this ); this.setSponsored = this.setSponsored.bind( this ); this.onFocusOutside = this.onFocusOutside.bind( this ); this.resetState = this.resetState.bind( this ); this.autocompleteRef = createRef(); this.resetOnMount = this.resetOnMount.bind( this ); this.state = { opensInNewWindow: false, noFollow: false, sponsored: false, inputValue: '', anchorRect: false, }; } static getDerivedStateFromProps( props, state ) { const { activeAttributes: { url, target, rel } } = props; const opensInNewWindow = target === '_blank'; if ( ! isShowingInput( props, state ) ) { if ( url !== state.inputValue ) { return { inputValue: url }; } if ( opensInNewWindow !== state.opensInNewWindow ) { return { opensInNewWindow }; } if ( typeof rel === 'string' ) { const noFollow = rel.split( ' ' ).includes( 'nofollow' ); const sponsored = rel.split( ' ' ).includes( 'sponsored' ); if ( noFollow !== state.noFollow ) { return { noFollow }; } if ( sponsored !== state.sponsored ) { return { sponsored }; } } } return null; } onKeyDown( event ) { if ( [ LEFT, DOWN, RIGHT, UP, BACKSPACE, ENTER ].indexOf( event.keyCode ) > -1 ) { // Stop the key event from propagating up to ObserveTyping.startTypingInTextField. event.stopPropagation(); } if ( [ ESCAPE ].indexOf( event.keyCode ) > -1 ) { this.resetState(); } } onChangeInputValue( inputValue ) { this.setState( { inputValue } ); } setLinkTarget( opensInNewWindow ) { const { activeAttributes: { url = '' }, value, onChange } = this.props; this.setState( { opensInNewWindow } ); // Apply now if URL is not being edited. if ( ! isShowingInput( this.props, this.state ) ) { const selectedText = getTextContent( slice( value ) ); onChange( applyFormat( value, createLinkFormat( { url, opensInNewWindow, noFollow: this.state.noFollow, sponsored: this.state.sponsored, text: selectedText, } ) ) ); } } setNoFollow( noFollow ) { const { activeAttributes: { url = '' }, value, onChange } = this.props; this.setState( { noFollow } ); // Apply now if URL is not being edited. if ( ! isShowingInput( this.props, this.state ) ) { const selectedText = getTextContent( slice( value ) ); onChange( applyFormat( value, createLinkFormat( { url, opensInNewWindow: this.state.opensInNewWindow, noFollow, sponsored: this.state.sponsored, text: selectedText, } ) ) ); } } setSponsored( sponsored ) { const { activeAttributes: { url = '' }, value, onChange } = this.props; this.setState( { sponsored } ); // Apply now if URL is not being edited. if ( ! isShowingInput( this.props, this.state ) ) { const selectedText = getTextContent( slice( value ) ); onChange( applyFormat( value, createLinkFormat( { url, opensInNewWindow: this.state.opensInNewWindow, noFollow: this.state.noFollow, sponsored, text: selectedText, } ) ) ); } } editLink( event ) { this.setState( { editLink: true } ); event.preventDefault(); } submitLink( event ) { const { isActive, value, onChange, speak } = this.props; const { inputValue, opensInNewWindow, noFollow, sponsored } = this.state; const url = prependHTTP( inputValue ); const selectedText = getTextContent( slice( value ) ); const format = createLinkFormat( { url, opensInNewWindow, noFollow, sponsored, text: selectedText, } ); event.preventDefault(); if ( isCollapsed( value ) && ! isActive ) { const toInsert = applyFormat( create( { text: url } ), format, 0, url.length ); onChange( insert( value, toInsert ) ); } else { onChange( applyFormat( value, format ) ); } this.resetState(); if ( ! isValidHref( url ) ) { speak( __( 'Warning: the link has been inserted but could have errors. Please test it.', 'all-in-one-seo-pack' ), 'assertive' ); } else if ( isActive ) { speak( __( 'Link edited.', 'all-in-one-seo-pack' ), 'assertive' ); } else { speak( __( 'Link inserted.', 'all-in-one-seo-pack' ), 'assertive' ); } } onFocusOutside() { // The autocomplete suggestions list renders in a separate popover (in a portal), // so onClickOutside fails to detect that a click on a suggestion occured in the // LinkContainer. Detect clicks on autocomplete suggestions using a ref here, and // return to avoid the popover being closed. const autocompleteElement = this.autocompleteRef.current; if ( autocompleteElement && autocompleteElement.contains( event.target ) ) { return; } this.resetState(); } resetState() { this.props.stopAddingLink(); this.setState( { editLink: false } ); } resetOnMount( anchorRect ) { if ( this.state.anchorRect !== anchorRect ) { this.setState( { opensInNewWindow: false, noFollow: false, sponsored: false, anchorRect: anchorRect } ); } } render() { const { isActive, activeAttributes: { url, target, rel }, addingLink, value } = this.props; if ( ! isActive && ! addingLink ) { return null; } const { inputValue, opensInNewWindow, noFollow, sponsored } = this.state; const showInput = isShowingInput( this.props, this.state ); if ( ! opensInNewWindow && target === '_blank' ) { this.setState( { opensInNewWindow: true } ); } if ( typeof rel === 'string' ) { const relNoFollow = rel.split( ' ' ).includes( 'nofollow' ); const relSponsored = rel.split( ' ' ).includes( 'sponsored' ); if ( relNoFollow !== noFollow ) { this.setState( { noFollow: relNoFollow } ); } if ( relSponsored !== sponsored ) { this.setState( { sponsored: relSponsored } ); } } return ( <PositionedAtSelection key={ `${ value.start }${ value.end }` /* Used to force rerender on selection change */ } > <URLPopoverAtLink resetOnMount={ this.resetOnMount } value={ value } isActive={ isActive } addingLink={ addingLink } onFocusOutside={ this.onFocusOutside } onClose={ () => { if ( ! inputValue ) { this.resetState(); } } } focusOnMount={ showInput ? 'firstElement' : false } renderSettings={ () => ( <Fragment> <ToggleControl label={ __( 'Open in New Tab', 'all-in-one-seo-pack' ) } checked={ opensInNewWindow } onChange={ this.setLinkTarget } /> <ToggleControl label={ __( 'Add "nofollow" to link', 'all-in-one-seo-pack' ) } checked={ noFollow } onChange={ this.setNoFollow } /> <ToggleControl label={ __( 'Add "sponsored" to link', 'all-in-one-seo-pack' ) } checked={ sponsored } onChange={ this.setSponsored } /> </Fragment> ) } > { showInput ? ( <LinkEditor className="editor-format-toolbar__link-container-content block-editor-format-toolbar__link-container-content" value={ inputValue } onChangeInputValue={ this.onChangeInputValue } onKeyDown={ this.onKeyDown } onKeyPress={ stopKeyPropagation } onSubmit={ this.submitLink } autocompleteRef={ this.autocompleteRef } /> ) : ( <LinkViewer className="editor-format-toolbar__link-container-content block-editor-format-toolbar__link-container-content" onKeyPress={ stopKeyPropagation } url={ url } onEditLinkClick={ this.editLink } linkClassName={ isValidHref( prependHTTP( url ) ) ? undefined : 'has-invalid-link' } /> ) } </URLPopoverAtLink> </PositionedAtSelection> ); } } export default withSpokenMessages( InlineLinkUI );
semperfiwebdesign/all-in-one-seo-pack
src/components/inline.js
JavaScript
gpl-2.0
9,828
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 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. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package com.github.smeny.jpc.emulator.execution.opcodes.pm; import com.github.smeny.jpc.emulator.execution.*; import com.github.smeny.jpc.emulator.execution.decoder.*; import com.github.smeny.jpc.emulator.processor.*; import com.github.smeny.jpc.emulator.processor.fpu64.*; import static com.github.smeny.jpc.emulator.processor.Processor.*; public class shrd_Ed_Gd_Ib_mem extends Executable { final Pointer op1; final int op2Index; final int immb; public shrd_Ed_Gd_Ib_mem(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); op1 = Modrm.getPointer(prefices, modrm, input); op2Index = Modrm.Gd(modrm); immb = Modrm.Ib(input); } public Branch execute(Processor cpu) { Reg op2 = cpu.regs[op2Index]; if(immb != 0) { int shift = immb & 0x1f; cpu.flagOp1 = op1.get32(cpu); cpu.flagOp2 = shift; long rot = ((0xffffffffL &op2.get32()) << 32) | (0xffffffffL & op1.get32(cpu)); cpu.flagResult = ((int)(rot >> shift)); op1.set32(cpu, cpu.flagResult); cpu.flagIns = UCodes.SHRD32; cpu.flagStatus = OSZAPC; } return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
smeny/JPC
src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/pm/shrd_Ed_Gd_Ib_mem.java
Java
gpl-2.0
2,407
<?php $siteurl = "http://localhost/childcare/"; $siteurladmin = "http://localhost/childcare/admin"; ?>
srikantmatihali/childcare
include/settings.php
PHP
gpl-2.0
103
package dbfit.environment; import dbfit.annotations.DatabaseEnvironment; import dbfit.api.AbstractDbEnvironment; import dbfit.util.DbParameterAccessor; import dbfit.util.DbParameterAccessorsMapBuilder; import dbfit.util.Direction; import static dbfit.util.Direction.*; import static dbfit.util.LangUtils.enquoteAndJoin; import dbfit.util.TypeNormaliserFactory; import static dbfit.environment.SqlServerTypeNameNormaliser.normaliseTypeName; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; @DatabaseEnvironment(name="SqlServer", driver="com.microsoft.sqlserver.jdbc.SQLServerDriver") public class SqlServerEnvironment extends AbstractDbEnvironment { public SqlServerEnvironment(String driverClassName) { super(driverClassName); defaultParamPatternString = "@([A-Za-z0-9_]+)"; TypeNormaliserFactory.setNormaliser(java.sql.Time.class, new MillisecondTimeNormaliser()); } public boolean supportsOuputOnInsert() { return false; } @Override protected String getConnectionString(String dataSource) { return "jdbc:sqlserver://" + dataSource; } @Override protected String getConnectionString(String dataSource, String database) { return getConnectionString(dataSource) + ";database=" + database; } @Override public void connect(String connectionString, Properties info) throws SQLException { // Add sendTimeAsDatetime=false option to enforce sending Time as // java.sql.Time (otherwise some precision is lost in conversions) super.connect(connectionString + ";sendTimeAsDatetime=false", info); } public Map<String, DbParameterAccessor> getAllColumns(String tableOrViewName) throws SQLException { String qry = " select c.[name], TYPE_NAME(c.system_type_id) as [Type], c.max_length, " + " 0 As is_output, 0 As is_cursor_ref " + " from " + objectDatabasePrefix(tableOrViewName) + "sys.columns c " + " where c.object_id = OBJECT_ID(?) " + " order by column_id"; return readIntoParams(tableOrViewName, qry); } private Map<String, DbParameterAccessor> readIntoParams(String objname, String query) throws SQLException { DbParameterAccessorsMapBuilder params = new DbParameterAccessorsMapBuilder(dbfitToJdbcTransformerFactory); objname = objname.replaceAll("[^a-zA-Z0-9_.#$]", ""); String bracketedName = enquoteAndJoin(objname.split("\\."), ".", "[", "]"); try (PreparedStatement dc = currentConnection.prepareStatement(query)) { dc.setString(1, bracketedName); ResultSet rs = dc.executeQuery(); while (rs.next()) { String paramName = defaultIfNull(rs.getString(1), ""); params.add(paramName, getParameterDirection(rs.getInt(4), paramName), getSqlType(rs.getString(2)), getJavaClass(rs.getString(2))); } } return params.toMap(); } // List interface has sequential search, so using list instead of array to // map types private static List<String> stringTypes = Arrays.asList(new String[] { "VARCHAR", "NVARCHAR", "CHAR", "NCHAR", "TEXT", "NTEXT", "UNIQUEIDENTIFIER" }); private static List<String> intTypes = Arrays .asList(new String[] { "INT" }); private static List<String> booleanTypes = Arrays .asList(new String[] { "BIT" }); private static List<String> floatTypes = Arrays .asList(new String[] { "REAL" }); private static List<String> doubleTypes = Arrays .asList(new String[] { "FLOAT" }); private static List<String> longTypes = Arrays .asList(new String[] { "BIGINT" }); private static List<String> shortTypes = Arrays.asList(new String[] { "TINYINT", "SMALLINT" }); private static List<String> numericTypes = Arrays.asList("NUMERIC"); private static List<String> decimalTypes = Arrays.asList(new String[] { "DECIMAL", "MONEY", "SMALLMONEY" }); private static List<String> timestampTypes = Arrays.asList(new String[] { "SMALLDATETIME", "DATETIME", "DATETIME2" }); private static List<String> dateTypes = Arrays.asList("DATE"); private static List<String> timeTypes = Arrays.asList("TIME"); // private static List<String> refCursorTypes = Arrays.asList(new String[] { // }); // private static List<String> doubleTypes=Arrays.asList(new // String[]{"DOUBLE"}); // private static string[] BinaryTypes=new string[] {"BINARY","VARBINARY", "TIMESTAMP"}; // private static string[] GuidTypes = new string[] { "UNIQUEIDENTIFIER" }; // private static string[] VariantTypes = new string[] { "SQL_VARIANT" }; private String objectDatabasePrefix(String dbObjectName) { String objectDatabasePrefix = ""; String[] objnameParts = dbObjectName.split("\\."); if (objnameParts.length == 3) { objectDatabasePrefix = objnameParts[0] + "."; } return objectDatabasePrefix; } private static Direction getParameterDirection(int isOutput, String name) { if (name.isEmpty()) { return RETURN_VALUE; } return (isOutput == 1) ? INPUT_OUTPUT : INPUT; } private static int getSqlType(String dataType) { // todo:strip everything from first blank dataType = normaliseTypeName(dataType); if (stringTypes.contains(dataType)) return java.sql.Types.VARCHAR; if (numericTypes.contains(dataType)) return java.sql.Types.NUMERIC; if (decimalTypes.contains(dataType)) return java.sql.Types.DECIMAL; if (intTypes.contains(dataType)) return java.sql.Types.INTEGER; if (timestampTypes.contains(dataType)) return java.sql.Types.TIMESTAMP; if (dateTypes.contains(dataType)) return java.sql.Types.DATE; if (timeTypes.contains(dataType)) return java.sql.Types.TIME; if (booleanTypes.contains(dataType)) return java.sql.Types.BOOLEAN; if (floatTypes.contains(dataType)) return java.sql.Types.FLOAT; if (doubleTypes.contains(dataType)) return java.sql.Types.DOUBLE; if (longTypes.contains(dataType)) return java.sql.Types.BIGINT; if (shortTypes.contains(dataType)) return java.sql.Types.SMALLINT; throw new UnsupportedOperationException("Type " + dataType + " is not supported"); } public Class<?> getJavaClass(String dataType) { dataType = normaliseTypeName(dataType); if (stringTypes.contains(dataType)) return String.class; if (numericTypes.contains(dataType)) return BigDecimal.class; if (decimalTypes.contains(dataType)) return BigDecimal.class; if (intTypes.contains(dataType)) return Integer.class; if (timestampTypes.contains(dataType)) return java.sql.Timestamp.class; if (dateTypes.contains(dataType)) return java.sql.Date.class; if (timeTypes.contains(dataType)) return java.sql.Time.class; if (booleanTypes.contains(dataType)) return Boolean.class; if (floatTypes.contains(dataType)) return Float.class; if (doubleTypes.contains(dataType)) return Double.class; if (longTypes.contains(dataType)) return Long.class; if (shortTypes.contains(dataType)) return Short.class; throw new UnsupportedOperationException("Type " + dataType + " is not supported"); } public Map<String, DbParameterAccessor> getAllProcedureParameters( String procName) throws SQLException { return readIntoParams( procName, "select [name], [Type], max_length, is_output, is_cursor_ref from " + "(" + " select " + " p.[name], TYPE_NAME(p.system_type_id) as [Type], " + " p.max_length, p.is_output, p.is_cursor_ref, " + " p.parameter_id, 0 as set_id, p.object_id " + " from " + objectDatabasePrefix(procName) + "sys.parameters p " + " union all select " + " '' as [name], 'int' as [Type], " + " 4 as max_length, 1 as is_output, 0 as is_cursor_ref, " + " null as parameter_id, 1 as set_id, object_id " + " from " + objectDatabasePrefix(procName) + "sys.objects where type in (N'P', N'PC') " + ") as u where object_id = OBJECT_ID(?) order by set_id, parameter_id"); } public String buildInsertCommand(String tableName, DbParameterAccessor[] accessors) { StringBuilder sb = new StringBuilder("insert into "); sb.append(tableName).append("("); String comma = ""; StringBuilder values = new StringBuilder(); for (DbParameterAccessor accessor : accessors) { if (accessor.hasDirection(Direction.INPUT)) { sb.append(comma); values.append(comma); //This will allow column names that have spaces or are keywords. sb.append("[" + accessor.getName() + "]"); values.append("?"); comma = ","; } } sb.append(") values ("); sb.append(values); sb.append(")"); return sb.toString(); } }
dbfit/dbfit
dbfit-java/sqlserver/src/main/java/dbfit/environment/SqlServerEnvironment.java
Java
gpl-2.0
10,073
<?php /** * Template to include on wp_footer front-end; passes plugin options to javascript function * @package Infinite_Scroll */ ?> <script type="text/javascript"> // Because the `wp_localize_script` method makes everything a string infinite_scroll = jQuery.parseJSON(infinite_scroll); jQuery( infinite_scroll.contentSelector ).infinitescroll( infinite_scroll, function(newElements, data, url) { eval(infinite_scroll.callback); }); </script>
zdislaw/fiercefamily_wp
wp-content/plugins.bak/infinite-scroll/templates/footer.php
PHP
gpl-2.0
460
/* * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.security.tools.keytool; /** * <p> This class represents the <code>ResourceBundle</code> * for the keytool. * */ public class Resources_ja extends java.util.ListResourceBundle { private static final Object[][] contents = { {"NEWLINE", "\n"}, {"STAR", "*******************************************"}, {"STARNN", "*******************************************\n\n"}, // keytool: Help part {".OPTION.", " [OPTION]..."}, {"Options.", "\u30AA\u30D7\u30B7\u30E7\u30F3:"}, {"option.1.set.twice", "%s\u30AA\u30D7\u30B7\u30E7\u30F3\u304C\u8907\u6570\u56DE\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059\u3002\u6700\u5F8C\u306E\u3082\u306E\u4EE5\u5916\u306F\u3059\u3079\u3066\u7121\u8996\u3055\u308C\u307E\u3059\u3002"}, {"multiple.commands.1.2", "1\u3064\u306E\u30B3\u30DE\u30F3\u30C9\u306E\u307F\u8A31\u53EF\u3055\u308C\u307E\u3059: %1$s\u3068%2$s\u306E\u4E21\u65B9\u304C\u6307\u5B9A\u3055\u308C\u307E\u3057\u305F\u3002"}, {"Use.keytool.help.for.all.available.commands", "\u3053\u306E\u30D8\u30EB\u30D7\u30FB\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u8868\u793A\u3059\u308B\u306B\u306F\"keytool -?\u3001-h\u307E\u305F\u306F--help\"\u3092\u4F7F\u7528\u3057\u307E\u3059"}, {"Key.and.Certificate.Management.Tool", "\u30AD\u30FC\u304A\u3088\u3073\u8A3C\u660E\u66F8\u7BA1\u7406\u30C4\u30FC\u30EB"}, {"Commands.", "\u30B3\u30DE\u30F3\u30C9:"}, {"Use.keytool.command.name.help.for.usage.of.command.name", "command_name\u306E\u4F7F\u7528\u65B9\u6CD5\u306B\u3064\u3044\u3066\u306F\u3001\"keytool -command_name --help\"\u3092\u4F7F\u7528\u3057\u307E\u3059\u3002\n\u4E8B\u524D\u69CB\u6210\u6E08\u306E\u30AA\u30D7\u30B7\u30E7\u30F3\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u6307\u5B9A\u3059\u308B\u306B\u306F\u3001-conf <url>\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u307E\u3059\u3002"}, // keytool: help: commands {"Generates.a.certificate.request", "\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8\u3092\u751F\u6210\u3057\u307E\u3059"}, //-certreq {"Changes.an.entry.s.alias", "\u30A8\u30F3\u30C8\u30EA\u306E\u5225\u540D\u3092\u5909\u66F4\u3057\u307E\u3059"}, //-changealias {"Deletes.an.entry", "\u30A8\u30F3\u30C8\u30EA\u3092\u524A\u9664\u3057\u307E\u3059"}, //-delete {"Exports.certificate", "\u8A3C\u660E\u66F8\u3092\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u3057\u307E\u3059"}, //-exportcert {"Generates.a.key.pair", "\u30AD\u30FC\u30FB\u30DA\u30A2\u3092\u751F\u6210\u3057\u307E\u3059"}, //-genkeypair {"Generates.a.secret.key", "\u79D8\u5BC6\u30AD\u30FC\u3092\u751F\u6210\u3057\u307E\u3059"}, //-genseckey {"Generates.certificate.from.a.certificate.request", "\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8\u304B\u3089\u8A3C\u660E\u66F8\u3092\u751F\u6210\u3057\u307E\u3059"}, //-gencert {"Generates.CRL", "CRL\u3092\u751F\u6210\u3057\u307E\u3059"}, //-gencrl {"Generated.keyAlgName.secret.key", "{0}\u79D8\u5BC6\u30AD\u30FC\u3092\u751F\u6210\u3057\u307E\u3057\u305F"}, //-genseckey {"Generated.keysize.bit.keyAlgName.secret.key", "{0}\u30D3\u30C3\u30C8{1}\u79D8\u5BC6\u30AD\u30FC\u3092\u751F\u6210\u3057\u307E\u3057\u305F"}, //-genseckey {"Imports.entries.from.a.JDK.1.1.x.style.identity.database", "JDK 1.1.x-style\u30A2\u30A4\u30C7\u30F3\u30C6\u30A3\u30C6\u30A3\u30FB\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u304B\u3089\u30A8\u30F3\u30C8\u30EA\u3092\u30A4\u30F3\u30DD\u30FC\u30C8\u3057\u307E\u3059"}, //-identitydb {"Imports.a.certificate.or.a.certificate.chain", "\u8A3C\u660E\u66F8\u307E\u305F\u306F\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u3092\u30A4\u30F3\u30DD\u30FC\u30C8\u3057\u307E\u3059"}, //-importcert {"Imports.a.password", "\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u30A4\u30F3\u30DD\u30FC\u30C8\u3057\u307E\u3059"}, //-importpass {"Imports.one.or.all.entries.from.another.keystore", "\u5225\u306E\u30AD\u30FC\u30B9\u30C8\u30A2\u304B\u30891\u3064\u307E\u305F\u306F\u3059\u3079\u3066\u306E\u30A8\u30F3\u30C8\u30EA\u3092\u30A4\u30F3\u30DD\u30FC\u30C8\u3057\u307E\u3059"}, //-importkeystore {"Clones.a.key.entry", "\u30AD\u30FC\u30FB\u30A8\u30F3\u30C8\u30EA\u306E\u30AF\u30ED\u30FC\u30F3\u3092\u4F5C\u6210\u3057\u307E\u3059"}, //-keyclone {"Changes.the.key.password.of.an.entry", "\u30A8\u30F3\u30C8\u30EA\u306E\u30AD\u30FC\u30FB\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5909\u66F4\u3057\u307E\u3059"}, //-keypasswd {"Lists.entries.in.a.keystore", "\u30AD\u30FC\u30B9\u30C8\u30A2\u5185\u306E\u30A8\u30F3\u30C8\u30EA\u3092\u30EA\u30B9\u30C8\u3057\u307E\u3059"}, //-list {"Prints.the.content.of.a.certificate", "\u8A3C\u660E\u66F8\u306E\u5185\u5BB9\u3092\u51FA\u529B\u3057\u307E\u3059"}, //-printcert {"Prints.the.content.of.a.certificate.request", "\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u5185\u5BB9\u3092\u51FA\u529B\u3057\u307E\u3059"}, //-printcertreq {"Prints.the.content.of.a.CRL.file", "CRL\u30D5\u30A1\u30A4\u30EB\u306E\u5185\u5BB9\u3092\u51FA\u529B\u3057\u307E\u3059"}, //-printcrl {"Generates.a.self.signed.certificate", "\u81EA\u5DF1\u7F72\u540D\u578B\u8A3C\u660E\u66F8\u3092\u751F\u6210\u3057\u307E\u3059"}, //-selfcert {"Changes.the.store.password.of.a.keystore", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30B9\u30C8\u30A2\u30FB\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5909\u66F4\u3057\u307E\u3059"}, //-storepasswd {"showinfo.command.help", "\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u95A2\u9023\u60C5\u5831\u3092\u8868\u793A\u3057\u307E\u3059"}, // keytool: help: options {"alias.name.of.the.entry.to.process", "\u51E6\u7406\u3059\u308B\u30A8\u30F3\u30C8\u30EA\u306E\u5225\u540D"}, //-alias {"groupname.option.help", "\u30B0\u30EB\u30FC\u30D7\u540D\u3002\u305F\u3068\u3048\u3070\u3001\u6955\u5186\u66F2\u7DDA\u540D\u3067\u3059\u3002"}, //-groupname {"destination.alias", "\u51FA\u529B\u5148\u306E\u5225\u540D"}, //-destalias {"destination.key.password", "\u51FA\u529B\u5148\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-destkeypass {"destination.keystore.name", "\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u540D"}, //-destkeystore {"destination.keystore.password.protected", "\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u4FDD\u8B77\u5BFE\u8C61\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-destprotected {"destination.keystore.provider.name", "\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D7\u30ED\u30D0\u30A4\u30C0\u540D"}, //-destprovidername {"destination.keystore.password", "\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-deststorepass {"destination.keystore.type", "\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30BF\u30A4\u30D7"}, //-deststoretype {"distinguished.name", "\u8B58\u5225\u540D"}, //-dname {"X.509.extension", "X.509\u62E1\u5F35"}, //-ext {"output.file.name", "\u51FA\u529B\u30D5\u30A1\u30A4\u30EB\u540D"}, //-file and -outfile {"input.file.name", "\u5165\u529B\u30D5\u30A1\u30A4\u30EB\u540D"}, //-file and -infile {"key.algorithm.name", "\u30AD\u30FC\u30FB\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u540D"}, //-keyalg {"key.password", "\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-keypass {"key.bit.size", "\u30AD\u30FC\u306E\u30D3\u30C3\u30C8\u30FB\u30B5\u30A4\u30BA"}, //-keysize {"keystore.name", "\u30AD\u30FC\u30B9\u30C8\u30A2\u540D"}, //-keystore {"access.the.cacerts.keystore", "cacerts\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u30A2\u30AF\u30BB\u30B9\u3059\u308B"}, // -cacerts {"warning.cacerts.option", "\u8B66\u544A: cacerts\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u30A2\u30AF\u30BB\u30B9\u3059\u308B\u306B\u306F-cacerts\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044"}, {"new.password", "\u65B0\u898F\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-new {"do.not.prompt", "\u30D7\u30ED\u30F3\u30D7\u30C8\u3092\u8868\u793A\u3057\u306A\u3044"}, //-noprompt {"password.through.protected.mechanism", "\u4FDD\u8B77\u30E1\u30AB\u30CB\u30BA\u30E0\u306B\u3088\u308B\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-protected {"tls.option.help", "TLS\u69CB\u6210\u60C5\u5831\u3092\u8868\u793A\u3057\u307E\u3059"}, // The following 2 values should span 2 lines, the first for the // option itself, the second for its -providerArg value. {"addprovider.option", "\u540D\u524D\u3067\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30D7\u30ED\u30D0\u30A4\u30C0\u3092\u8FFD\u52A0\u3059\u308B(SunPKCS11\u306A\u3069)\n-addprovider\u306E\u5F15\u6570\u3092\u69CB\u6210\u3059\u308B"}, //-addprovider {"provider.class.option", "\u5B8C\u5168\u4FEE\u98FE\u30AF\u30E9\u30B9\u540D\u3067\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30D7\u30ED\u30D0\u30A4\u30C0\u3092\u8FFD\u52A0\u3059\u308B\n-providerclass\u306E\u5F15\u6570\u3092\u69CB\u6210\u3059\u308B"}, //-providerclass {"provider.name", "\u30D7\u30ED\u30D0\u30A4\u30C0\u540D"}, //-providername {"provider.classpath", "\u30D7\u30ED\u30D0\u30A4\u30C0\u30FB\u30AF\u30E9\u30B9\u30D1\u30B9"}, //-providerpath {"output.in.RFC.style", "RFC\u30B9\u30BF\u30A4\u30EB\u306E\u51FA\u529B"}, //-rfc {"signature.algorithm.name", "\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u540D"}, //-sigalg {"source.alias", "\u30BD\u30FC\u30B9\u5225\u540D"}, //-srcalias {"source.key.password", "\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-srckeypass {"source.keystore.name", "\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u540D"}, //-srckeystore {"source.keystore.password.protected", "\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u4FDD\u8B77\u5BFE\u8C61\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-srcprotected {"source.keystore.provider.name", "\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D7\u30ED\u30D0\u30A4\u30C0\u540D"}, //-srcprovidername {"source.keystore.password", "\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-srcstorepass {"source.keystore.type", "\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30BF\u30A4\u30D7"}, //-srcstoretype {"SSL.server.host.and.port", "SSL\u30B5\u30FC\u30D0\u30FC\u306E\u30DB\u30B9\u30C8\u3068\u30DD\u30FC\u30C8"}, //-sslserver {"signed.jar.file", "\u7F72\u540D\u4ED8\u304DJAR\u30D5\u30A1\u30A4\u30EB"}, //=jarfile {"certificate.validity.start.date.time", "\u8A3C\u660E\u66F8\u306E\u6709\u52B9\u958B\u59CB\u65E5\u6642"}, //-startdate {"keystore.password", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-storepass {"keystore.type", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30BF\u30A4\u30D7"}, //-storetype {"trust.certificates.from.cacerts", "cacerts\u304B\u3089\u306E\u8A3C\u660E\u66F8\u3092\u4FE1\u983C\u3059\u308B"}, //-trustcacerts {"verbose.output", "\u8A73\u7D30\u51FA\u529B"}, //-v {"validity.number.of.days", "\u59A5\u5F53\u6027\u65E5\u6570"}, //-validity {"Serial.ID.of.cert.to.revoke", "\u5931\u52B9\u3059\u308B\u8A3C\u660E\u66F8\u306E\u30B7\u30EA\u30A2\u30EBID"}, //-id // keytool: Running part {"keytool.error.", "keytool\u30A8\u30E9\u30FC: "}, {"Illegal.option.", "\u4E0D\u6B63\u306A\u30AA\u30D7\u30B7\u30E7\u30F3: "}, {"Illegal.value.", "\u4E0D\u6B63\u306A\u5024: "}, {"Unknown.password.type.", "\u4E0D\u660E\u306A\u30D1\u30B9\u30EF\u30FC\u30C9\u30FB\u30BF\u30A4\u30D7: "}, {"Cannot.find.environment.variable.", "\u74B0\u5883\u5909\u6570\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: "}, {"Cannot.find.file.", "\u30D5\u30A1\u30A4\u30EB\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: "}, {"Command.option.flag.needs.an.argument.", "\u30B3\u30DE\u30F3\u30C9\u30FB\u30AA\u30D7\u30B7\u30E7\u30F3{0}\u306B\u306F\u5F15\u6570\u304C\u5FC5\u8981\u3067\u3059\u3002"}, {"Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value.", "\u8B66\u544A: PKCS12\u30AD\u30FC\u30B9\u30C8\u30A2\u3067\u306F\u3001\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3068\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u304C\u7570\u306A\u308B\u72B6\u6CC1\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093\u3002\u30E6\u30FC\u30B6\u30FC\u304C\u6307\u5B9A\u3057\u305F{0}\u306E\u5024\u306F\u7121\u8996\u3057\u307E\u3059\u3002"}, {"the.keystore.or.storetype.option.cannot.be.used.with.the.cacerts.option", "-keystore\u307E\u305F\u306F-storetype\u30AA\u30D7\u30B7\u30E7\u30F3\u306F\u3001-cacerts\u30AA\u30D7\u30B7\u30E7\u30F3\u3068\u3068\u3082\u306B\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093"}, {".keystore.must.be.NONE.if.storetype.is.{0}", "-storetype\u304C{0}\u306E\u5834\u5408\u3001-keystore\u306FNONE\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"}, {"Too.many.retries.program.terminated", "\u518D\u8A66\u884C\u304C\u591A\u3059\u304E\u307E\u3059\u3002\u30D7\u30ED\u30B0\u30E9\u30E0\u304C\u7D42\u4E86\u3057\u307E\u3057\u305F"}, {".storepasswd.and.keypasswd.commands.not.supported.if.storetype.is.{0}", "-storetype\u304C{0}\u306E\u5834\u5408\u3001-storepasswd\u30B3\u30DE\u30F3\u30C9\u304A\u3088\u3073-keypasswd\u30B3\u30DE\u30F3\u30C9\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093"}, {".keypasswd.commands.not.supported.if.storetype.is.PKCS12", "-storetype\u304CPKCS12\u306E\u5834\u5408\u3001-keypasswd\u30B3\u30DE\u30F3\u30C9\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093"}, {".keypass.and.new.can.not.be.specified.if.storetype.is.{0}", "-storetype\u304C{0}\u306E\u5834\u5408\u3001-keypass\u3068-new\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"}, {"if.protected.is.specified.then.storepass.keypass.and.new.must.not.be.specified", "-protected\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u308B\u5834\u5408\u3001-storepass\u3001-keypass\u304A\u3088\u3073-new\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"}, {"if.srcprotected.is.specified.then.srcstorepass.and.srckeypass.must.not.be.specified", "-srcprotected\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u308B\u5834\u5408\u3001-srcstorepass\u304A\u3088\u3073-srckeypass\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"}, {"if.keystore.is.not.password.protected.then.storepass.keypass.and.new.must.not.be.specified", "\u30AD\u30FC\u30B9\u30C8\u30A2\u304C\u30D1\u30B9\u30EF\u30FC\u30C9\u3067\u4FDD\u8B77\u3055\u308C\u3066\u3044\u306A\u3044\u5834\u5408\u3001-storepass\u3001-keypass\u304A\u3088\u3073-new\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"}, {"if.source.keystore.is.not.password.protected.then.srcstorepass.and.srckeypass.must.not.be.specified", "\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u304C\u30D1\u30B9\u30EF\u30FC\u30C9\u3067\u4FDD\u8B77\u3055\u308C\u3066\u3044\u306A\u3044\u5834\u5408\u3001-srcstorepass\u304A\u3088\u3073-srckeypass\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"}, {"Illegal.startdate.value", "startdate\u5024\u304C\u7121\u52B9\u3067\u3059"}, {"Validity.must.be.greater.than.zero", "\u59A5\u5F53\u6027\u306F\u30BC\u30ED\u3088\u308A\u5927\u304D\u3044\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"}, {"provclass.not.a.provider", "%s\u306F\u30D7\u30ED\u30D0\u30A4\u30C0\u3067\u306F\u3042\u308A\u307E\u305B\u3093"}, {"provider.name.not.found", "\u30D7\u30ED\u30D0\u30A4\u30C0\u540D\"%s\"\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093"}, {"provider.class.not.found", "\u30D7\u30ED\u30D0\u30A4\u30C0\"%s\"\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093"}, {"Usage.error.no.command.provided", "\u4F7F\u7528\u30A8\u30E9\u30FC: \u30B3\u30DE\u30F3\u30C9\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093"}, {"Source.keystore.file.exists.but.is.empty.", "\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D5\u30A1\u30A4\u30EB\u306F\u3001\u5B58\u5728\u3057\u307E\u3059\u304C\u7A7A\u3067\u3059: "}, {"Please.specify.srckeystore", "-srckeystore\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"}, {"Must.not.specify.both.v.and.rfc.with.list.command", "'list'\u30B3\u30DE\u30F3\u30C9\u306B-v\u3068-rfc\u306E\u4E21\u65B9\u3092\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093"}, {"Key.password.must.be.at.least.6.characters", "\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u306F6\u6587\u5B57\u4EE5\u4E0A\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"}, {"New.password.must.be.at.least.6.characters", "\u65B0\u898F\u30D1\u30B9\u30EF\u30FC\u30C9\u306F6\u6587\u5B57\u4EE5\u4E0A\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"}, {"Keystore.file.exists.but.is.empty.", "\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D5\u30A1\u30A4\u30EB\u306F\u5B58\u5728\u3057\u307E\u3059\u304C\u3001\u7A7A\u3067\u3059: "}, {"Keystore.file.does.not.exist.", "\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D5\u30A1\u30A4\u30EB\u306F\u5B58\u5728\u3057\u307E\u305B\u3093: "}, {"Must.specify.destination.alias", "\u51FA\u529B\u5148\u306E\u5225\u540D\u3092\u6307\u5B9A\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"}, {"Must.specify.alias", "\u5225\u540D\u3092\u6307\u5B9A\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"}, {"Keystore.password.must.be.at.least.6.characters", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u306F6\u6587\u5B57\u4EE5\u4E0A\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"}, {"Enter.the.password.to.be.stored.", "\u4FDD\u5B58\u3059\u308B\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "}, {"Enter.keystore.password.", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "}, {"Enter.source.keystore.password.", "\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "}, {"Enter.destination.keystore.password.", "\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "}, {"Keystore.password.is.too.short.must.be.at.least.6.characters", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u304C\u77ED\u3059\u304E\u307E\u3059 - 6\u6587\u5B57\u4EE5\u4E0A\u306B\u3057\u3066\u304F\u3060\u3055\u3044"}, {"Unknown.Entry.Type", "\u4E0D\u660E\u306A\u30A8\u30F3\u30C8\u30EA\u30FB\u30BF\u30A4\u30D7"}, {"Entry.for.alias.alias.successfully.imported.", "\u5225\u540D{0}\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u30A4\u30F3\u30DD\u30FC\u30C8\u306B\u6210\u529F\u3057\u307E\u3057\u305F\u3002"}, {"Entry.for.alias.alias.not.imported.", "\u5225\u540D{0}\u306E\u30A8\u30F3\u30C8\u30EA\u306F\u30A4\u30F3\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002"}, {"Problem.importing.entry.for.alias.alias.exception.Entry.for.alias.alias.not.imported.", "\u5225\u540D{0}\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u30A4\u30F3\u30DD\u30FC\u30C8\u4E2D\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F: {1}\u3002\n\u5225\u540D{0}\u306E\u30A8\u30F3\u30C8\u30EA\u306F\u30A4\u30F3\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002"}, {"Import.command.completed.ok.entries.successfully.imported.fail.entries.failed.or.cancelled", "\u30A4\u30F3\u30DD\u30FC\u30C8\u30FB\u30B3\u30DE\u30F3\u30C9\u304C\u5B8C\u4E86\u3057\u307E\u3057\u305F: {0}\u4EF6\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u30A4\u30F3\u30DD\u30FC\u30C8\u304C\u6210\u529F\u3057\u307E\u3057\u305F\u3002{1}\u4EF6\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u30A4\u30F3\u30DD\u30FC\u30C8\u304C\u5931\u6557\u3057\u305F\u304B\u53D6\u308A\u6D88\u3055\u308C\u307E\u3057\u305F"}, {"Warning.Overwriting.existing.alias.alias.in.destination.keystore", "\u8B66\u544A: \u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u5185\u306E\u65E2\u5B58\u306E\u5225\u540D{0}\u3092\u4E0A\u66F8\u304D\u3057\u3066\u3044\u307E\u3059"}, {"Existing.entry.alias.alias.exists.overwrite.no.", "\u65E2\u5B58\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u5225\u540D{0}\u304C\u5B58\u5728\u3057\u3066\u3044\u307E\u3059\u3002\u4E0A\u66F8\u304D\u3057\u307E\u3059\u304B\u3002[\u3044\u3044\u3048]: "}, {"Too.many.failures.try.later", "\u969C\u5BB3\u304C\u591A\u3059\u304E\u307E\u3059 - \u5F8C\u3067\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044"}, {"Certification.request.stored.in.file.filename.", "\u8A8D\u8A3C\u30EA\u30AF\u30A8\u30B9\u30C8\u304C\u30D5\u30A1\u30A4\u30EB<{0}>\u306B\u4FDD\u5B58\u3055\u308C\u307E\u3057\u305F"}, {"Submit.this.to.your.CA", "\u3053\u308C\u3092CA\u306B\u63D0\u51FA\u3057\u3066\u304F\u3060\u3055\u3044"}, {"if.alias.not.specified.destalias.and.srckeypass.must.not.be.specified", "\u5225\u540D\u3092\u6307\u5B9A\u3057\u306A\u3044\u5834\u5408\u3001\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u5225\u540D\u304A\u3088\u3073\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"}, {"The.destination.pkcs12.keystore.has.different.storepass.and.keypass.Please.retry.with.destkeypass.specified.", "\u51FA\u529B\u5148pkcs12\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u3001\u7570\u306A\u308Bstorepass\u304A\u3088\u3073keypass\u304C\u3042\u308A\u307E\u3059\u3002-destkeypass\u3092\u6307\u5B9A\u3057\u3066\u518D\u8A66\u884C\u3057\u3066\u304F\u3060\u3055\u3044\u3002"}, {"Certificate.stored.in.file.filename.", "\u8A3C\u660E\u66F8\u304C\u30D5\u30A1\u30A4\u30EB<{0}>\u306B\u4FDD\u5B58\u3055\u308C\u307E\u3057\u305F"}, {"Certificate.reply.was.installed.in.keystore", "\u8A3C\u660E\u66F8\u5FDC\u7B54\u304C\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u3055\u308C\u307E\u3057\u305F"}, {"Certificate.reply.was.not.installed.in.keystore", "\u8A3C\u660E\u66F8\u5FDC\u7B54\u304C\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F"}, {"Certificate.was.added.to.keystore", "\u8A3C\u660E\u66F8\u304C\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u8FFD\u52A0\u3055\u308C\u307E\u3057\u305F"}, {"Certificate.was.not.added.to.keystore", "\u8A3C\u660E\u66F8\u304C\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u8FFD\u52A0\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F"}, {".Storing.ksfname.", "[{0}\u3092\u683C\u7D0D\u4E2D]"}, {"alias.has.no.public.key.certificate.", "{0}\u306B\u306F\u516C\u958B\u30AD\u30FC(\u8A3C\u660E\u66F8)\u304C\u3042\u308A\u307E\u305B\u3093"}, {"Cannot.derive.signature.algorithm", "\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093"}, {"Alias.alias.does.not.exist", "\u5225\u540D<{0}>\u306F\u5B58\u5728\u3057\u307E\u305B\u3093"}, {"Alias.alias.has.no.certificate", "\u5225\u540D<{0}>\u306B\u306F\u8A3C\u660E\u66F8\u304C\u3042\u308A\u307E\u305B\u3093"}, {"groupname.keysize.coexist", "-groupname\u3068-keysize\u306E\u4E21\u65B9\u3092\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"}, {"deprecate.keysize.for.ec", "-keysize\u306E\u6307\u5B9A\u306B\u3088\u308BEC\u30AD\u30FC\u306E\u751F\u6210\u306F\u975E\u63A8\u5968\u3067\u3059\u3002\u304B\u308F\u308A\u306B\"-groupname %s\"\u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044\u3002"}, {"Key.pair.not.generated.alias.alias.already.exists", "\u30AD\u30FC\u30FB\u30DA\u30A2\u306F\u751F\u6210\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u5225\u540D<{0}>\u306F\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"}, {"Generating.keysize.bit.keyAlgName.key.pair.and.self.signed.certificate.sigAlgName.with.a.validity.of.validality.days.for", "{3}\u65E5\u9593\u6709\u52B9\u306A{0}\u30D3\u30C3\u30C8\u306E{1}\u306E\u30AD\u30FC\u30FB\u30DA\u30A2\u3068\u81EA\u5DF1\u7F72\u540D\u578B\u8A3C\u660E\u66F8({2})\u3092\u751F\u6210\u3057\u3066\u3044\u307E\u3059\n\t\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u540D: {4}"}, {"Enter.key.password.for.alias.", "<{0}>\u306E\u30AD\u30FC\u30FB\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044"}, {".RETURN.if.same.as.keystore.password.", "\t(\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3068\u540C\u3058\u5834\u5408\u306FRETURN\u3092\u62BC\u3057\u3066\u304F\u3060\u3055\u3044): "}, {"Key.password.is.too.short.must.be.at.least.6.characters", "\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u304C\u77ED\u3059\u304E\u307E\u3059 - 6\u6587\u5B57\u4EE5\u4E0A\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"}, {"Too.many.failures.key.not.added.to.keystore", "\u969C\u5BB3\u304C\u591A\u3059\u304E\u307E\u3059 - \u30AD\u30FC\u306F\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u8FFD\u52A0\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F"}, {"Destination.alias.dest.already.exists", "\u51FA\u529B\u5148\u306E\u5225\u540D<{0}>\u306F\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"}, {"Password.is.too.short.must.be.at.least.6.characters", "\u30D1\u30B9\u30EF\u30FC\u30C9\u304C\u77ED\u3059\u304E\u307E\u3059 - 6\u6587\u5B57\u4EE5\u4E0A\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"}, {"Too.many.failures.Key.entry.not.cloned", "\u969C\u5BB3\u304C\u591A\u3059\u304E\u307E\u3059\u3002\u30AD\u30FC\u30FB\u30A8\u30F3\u30C8\u30EA\u306E\u30AF\u30ED\u30FC\u30F3\u306F\u4F5C\u6210\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F"}, {"key.password.for.alias.", "<{0}>\u306E\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, {"No.entries.from.identity.database.added", "\u30A2\u30A4\u30C7\u30F3\u30C6\u30A3\u30C6\u30A3\u30FB\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u304B\u3089\u8FFD\u52A0\u3055\u308C\u305F\u30A8\u30F3\u30C8\u30EA\u306F\u3042\u308A\u307E\u305B\u3093"}, {"Alias.name.alias", "\u5225\u540D: {0}"}, {"Creation.date.keyStore.getCreationDate.alias.", "\u4F5C\u6210\u65E5: {0,date}"}, {"alias.keyStore.getCreationDate.alias.", "{0},{1,date}, "}, {"alias.", "{0}, "}, {"Entry.type.type.", "\u30A8\u30F3\u30C8\u30EA\u30FB\u30BF\u30A4\u30D7: {0}"}, {"Certificate.chain.length.", "\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u306E\u9577\u3055: "}, {"Certificate.i.1.", "\u8A3C\u660E\u66F8[{0,number,integer}]:"}, {"Certificate.fingerprint.SHA.256.", "\u8A3C\u660E\u66F8\u306E\u30D5\u30A3\u30F3\u30AC\u30D7\u30EA\u30F3\u30C8(SHA-256): "}, {"Keystore.type.", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30BF\u30A4\u30D7: "}, {"Keystore.provider.", "\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D7\u30ED\u30D0\u30A4\u30C0: "}, {"Your.keystore.contains.keyStore.size.entry", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u306F{0,number,integer}\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u307E\u3059"}, {"Your.keystore.contains.keyStore.size.entries", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u306F{0,number,integer}\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u307E\u3059"}, {"Failed.to.parse.input", "\u5165\u529B\u306E\u69CB\u6587\u89E3\u6790\u306B\u5931\u6557\u3057\u307E\u3057\u305F"}, {"Empty.input", "\u5165\u529B\u304C\u3042\u308A\u307E\u305B\u3093"}, {"Not.X.509.certificate", "X.509\u8A3C\u660E\u66F8\u3067\u306F\u3042\u308A\u307E\u305B\u3093"}, {"alias.has.no.public.key", "{0}\u306B\u306F\u516C\u958B\u30AD\u30FC\u304C\u3042\u308A\u307E\u305B\u3093"}, {"alias.has.no.X.509.certificate", "{0}\u306B\u306FX.509\u8A3C\u660E\u66F8\u304C\u3042\u308A\u307E\u305B\u3093"}, {"New.certificate.self.signed.", "\u65B0\u3057\u3044\u8A3C\u660E\u66F8(\u81EA\u5DF1\u7F72\u540D\u578B):"}, {"Reply.has.no.certificates", "\u5FDC\u7B54\u306B\u306F\u8A3C\u660E\u66F8\u304C\u3042\u308A\u307E\u305B\u3093"}, {"Certificate.not.imported.alias.alias.already.exists", "\u8A3C\u660E\u66F8\u306F\u30A4\u30F3\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u5225\u540D<{0}>\u306F\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"}, {"Input.not.an.X.509.certificate", "\u5165\u529B\u306FX.509\u8A3C\u660E\u66F8\u3067\u306F\u3042\u308A\u307E\u305B\u3093"}, {"Certificate.already.exists.in.keystore.under.alias.trustalias.", "\u8A3C\u660E\u66F8\u306F\u3001\u5225\u540D<{0}>\u306E\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"}, {"Do.you.still.want.to.add.it.no.", "\u8FFD\u52A0\u3057\u307E\u3059\u304B\u3002[\u3044\u3044\u3048]: "}, {"Certificate.already.exists.in.system.wide.CA.keystore.under.alias.trustalias.", "\u8A3C\u660E\u66F8\u306F\u3001\u5225\u540D<{0}>\u306E\u30B7\u30B9\u30C6\u30E0\u898F\u6A21\u306ECA\u30AD\u30FC\u30B9\u30C8\u30A2\u5185\u306B\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"}, {"Do.you.still.want.to.add.it.to.your.own.keystore.no.", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u8FFD\u52A0\u3057\u307E\u3059\u304B\u3002 [\u3044\u3044\u3048]: "}, {"Trust.this.certificate.no.", "\u3053\u306E\u8A3C\u660E\u66F8\u3092\u4FE1\u983C\u3057\u307E\u3059\u304B\u3002 [\u3044\u3044\u3048]: "}, {"New.prompt.", "\u65B0\u898F{0}: "}, {"Passwords.must.differ", "\u30D1\u30B9\u30EF\u30FC\u30C9\u306F\u7570\u306A\u3063\u3066\u3044\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"}, {"Re.enter.new.prompt.", "\u65B0\u898F{0}\u3092\u518D\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "}, {"Re.enter.password.", "\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u518D\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "}, {"Re.enter.new.password.", "\u65B0\u898F\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u518D\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "}, {"They.don.t.match.Try.again", "\u4E00\u81F4\u3057\u307E\u305B\u3093\u3002\u3082\u3046\u4E00\u5EA6\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044"}, {"Enter.prompt.alias.name.", "{0}\u306E\u5225\u540D\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "}, {"Enter.new.alias.name.RETURN.to.cancel.import.for.this.entry.", "\u65B0\u3057\u3044\u5225\u540D\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044\t(\u3053\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u30A4\u30F3\u30DD\u30FC\u30C8\u3092\u53D6\u308A\u6D88\u3059\u5834\u5408\u306FRETURN\u3092\u62BC\u3057\u3066\u304F\u3060\u3055\u3044): "}, {"Enter.alias.name.", "\u5225\u540D\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "}, {".RETURN.if.same.as.for.otherAlias.", "\t(<{0}>\u3068\u540C\u3058\u5834\u5408\u306FRETURN\u3092\u62BC\u3057\u3066\u304F\u3060\u3055\u3044)"}, {"What.is.your.first.and.last.name.", "\u59D3\u540D\u306F\u4F55\u3067\u3059\u304B\u3002"}, {"What.is.the.name.of.your.organizational.unit.", "\u7D44\u7E54\u5358\u4F4D\u540D\u306F\u4F55\u3067\u3059\u304B\u3002"}, {"What.is.the.name.of.your.organization.", "\u7D44\u7E54\u540D\u306F\u4F55\u3067\u3059\u304B\u3002"}, {"What.is.the.name.of.your.City.or.Locality.", "\u90FD\u5E02\u540D\u307E\u305F\u306F\u5730\u57DF\u540D\u306F\u4F55\u3067\u3059\u304B\u3002"}, {"What.is.the.name.of.your.State.or.Province.", "\u90FD\u9053\u5E9C\u770C\u540D\u307E\u305F\u306F\u5DDE\u540D\u306F\u4F55\u3067\u3059\u304B\u3002"}, {"What.is.the.two.letter.country.code.for.this.unit.", "\u3053\u306E\u5358\u4F4D\u306B\u8A72\u5F53\u3059\u308B2\u6587\u5B57\u306E\u56FD\u30B3\u30FC\u30C9\u306F\u4F55\u3067\u3059\u304B\u3002"}, {"Is.name.correct.", "{0}\u3067\u3088\u308D\u3057\u3044\u3067\u3059\u304B\u3002"}, {"no", "\u3044\u3044\u3048"}, {"yes", "\u306F\u3044"}, {"y", "y"}, {".defaultValue.", " [{0}]: "}, {"Alias.alias.has.no.key", "\u5225\u540D<{0}>\u306B\u306F\u30AD\u30FC\u304C\u3042\u308A\u307E\u305B\u3093"}, {"Alias.alias.references.an.entry.type.that.is.not.a.private.key.entry.The.keyclone.command.only.supports.cloning.of.private.key", "\u5225\u540D<{0}>\u304C\u53C2\u7167\u3057\u3066\u3044\u308B\u30A8\u30F3\u30C8\u30EA\u30FB\u30BF\u30A4\u30D7\u306F\u79D8\u5BC6\u30AD\u30FC\u30FB\u30A8\u30F3\u30C8\u30EA\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002-keyclone\u30B3\u30DE\u30F3\u30C9\u306F\u79D8\u5BC6\u30AD\u30FC\u30FB\u30A8\u30F3\u30C8\u30EA\u306E\u30AF\u30ED\u30FC\u30F3\u4F5C\u6210\u306E\u307F\u3092\u30B5\u30DD\u30FC\u30C8\u3057\u307E\u3059"}, {".WARNING.WARNING.WARNING.", "***************** WARNING WARNING WARNING *****************"}, {"Signer.d.", "\u7F72\u540D\u8005\u756A\u53F7%d:"}, {"Timestamp.", "\u30BF\u30A4\u30E0\u30B9\u30BF\u30F3\u30D7:"}, {"Signature.", "\u7F72\u540D:"}, {"Certificate.owner.", "\u8A3C\u660E\u66F8\u306E\u6240\u6709\u8005: "}, {"Not.a.signed.jar.file", "\u7F72\u540D\u4ED8\u304DJAR\u30D5\u30A1\u30A4\u30EB\u3067\u306F\u3042\u308A\u307E\u305B\u3093"}, {"No.certificate.from.the.SSL.server", "SSL\u30B5\u30FC\u30D0\u30FC\u304B\u3089\u306E\u8A3C\u660E\u66F8\u304C\u3042\u308A\u307E\u305B\u3093"}, {".The.integrity.of.the.information.stored.in.your.keystore.", "*\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u4FDD\u5B58\u3055\u308C\u305F\u60C5\u5831\u306E\u6574\u5408\u6027\u306F*\n*\u691C\u8A3C\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u6574\u5408\u6027\u3092\u691C\u8A3C\u3059\u308B\u306B\u306F*\n*\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002*"}, {".The.integrity.of.the.information.stored.in.the.srckeystore.", "*\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u4FDD\u5B58\u3055\u308C\u305F\u60C5\u5831\u306E\u6574\u5408\u6027\u306F*\n*\u691C\u8A3C\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u6574\u5408\u6027\u3092\u691C\u8A3C\u3059\u308B\u306B\u306F*\n*\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002*"}, {"Certificate.reply.does.not.contain.public.key.for.alias.", "\u8A3C\u660E\u66F8\u5FDC\u7B54\u306B\u306F\u3001<{0}>\u306E\u516C\u958B\u30AD\u30FC\u306F\u542B\u307E\u308C\u307E\u305B\u3093"}, {"Incomplete.certificate.chain.in.reply", "\u5FDC\u7B54\u3057\u305F\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u306F\u4E0D\u5B8C\u5168\u3067\u3059"}, {"Top.level.certificate.in.reply.", "\u5FDC\u7B54\u3057\u305F\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\u306E\u8A3C\u660E\u66F8:\n"}, {".is.not.trusted.", "... \u306F\u4FE1\u983C\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002 "}, {"Install.reply.anyway.no.", "\u5FDC\u7B54\u3092\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u3057\u307E\u3059\u304B\u3002[\u3044\u3044\u3048]: "}, {"Public.keys.in.reply.and.keystore.don.t.match", "\u5FDC\u7B54\u3057\u305F\u516C\u958B\u30AD\u30FC\u3068\u30AD\u30FC\u30B9\u30C8\u30A2\u304C\u4E00\u81F4\u3057\u307E\u305B\u3093"}, {"Certificate.reply.and.certificate.in.keystore.are.identical", "\u8A3C\u660E\u66F8\u5FDC\u7B54\u3068\u30AD\u30FC\u30B9\u30C8\u30A2\u5185\u306E\u8A3C\u660E\u66F8\u304C\u540C\u3058\u3067\u3059"}, {"Failed.to.establish.chain.from.reply", "\u5FDC\u7B54\u304B\u3089\u9023\u9396\u3092\u78BA\u7ACB\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F"}, {"n", "n"}, {"Wrong.answer.try.again", "\u5FDC\u7B54\u304C\u9593\u9055\u3063\u3066\u3044\u307E\u3059\u3002\u3082\u3046\u4E00\u5EA6\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044"}, {"Secret.key.not.generated.alias.alias.already.exists", "\u79D8\u5BC6\u30AD\u30FC\u306F\u751F\u6210\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u5225\u540D<{0}>\u306F\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"}, {"Please.provide.keysize.for.secret.key.generation", "\u79D8\u5BC6\u30AD\u30FC\u306E\u751F\u6210\u6642\u306B\u306F -keysize\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"}, {"warning.not.verified.make.sure.keystore.is.correct", "\u8B66\u544A: \u691C\u8A3C\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002-keystore\u304C\u6B63\u3057\u3044\u3053\u3068\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002"}, {"Extensions.", "\u62E1\u5F35: "}, {".Empty.value.", "(\u7A7A\u306E\u5024)"}, {"Extension.Request.", "\u62E1\u5F35\u30EA\u30AF\u30A8\u30B9\u30C8:"}, {"Unknown.keyUsage.type.", "\u4E0D\u660E\u306AkeyUsage\u30BF\u30A4\u30D7: "}, {"Unknown.extendedkeyUsage.type.", "\u4E0D\u660E\u306AextendedkeyUsage\u30BF\u30A4\u30D7: "}, {"Unknown.AccessDescription.type.", "\u4E0D\u660E\u306AAccessDescription\u30BF\u30A4\u30D7: "}, {"Unrecognized.GeneralName.type.", "\u8A8D\u8B58\u3055\u308C\u306A\u3044GeneralName\u30BF\u30A4\u30D7: "}, {"This.extension.cannot.be.marked.as.critical.", "\u3053\u306E\u62E1\u5F35\u306F\u30AF\u30EA\u30C6\u30A3\u30AB\u30EB\u3068\u3057\u3066\u30DE\u30FC\u30AF\u4ED8\u3051\u3067\u304D\u307E\u305B\u3093\u3002 "}, {"Odd.number.of.hex.digits.found.", "\u5947\u6570\u306E16\u9032\u6570\u304C\u898B\u3064\u304B\u308A\u307E\u3057\u305F: "}, {"Unknown.extension.type.", "\u4E0D\u660E\u306A\u62E1\u5F35\u30BF\u30A4\u30D7: "}, {"command.{0}.is.ambiguous.", "\u30B3\u30DE\u30F3\u30C9{0}\u306F\u3042\u3044\u307E\u3044\u3067\u3059:"}, // 8171319: keytool should print out warnings when reading or // generating cert/cert req using weak algorithms {"the.certificate.request", "\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8"}, {"the.issuer", "\u767A\u884C\u8005"}, {"the.generated.certificate", "\u751F\u6210\u3055\u308C\u305F\u8A3C\u660E\u66F8"}, {"the.generated.crl", "\u751F\u6210\u3055\u308C\u305FCRL"}, {"the.generated.certificate.request", "\u751F\u6210\u3055\u308C\u305F\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8"}, {"the.certificate", "\u8A3C\u660E\u66F8"}, {"the.crl", "CRL"}, {"the.tsa.certificate", "TSA\u8A3C\u660E\u66F8"}, {"the.input", "\u5165\u529B"}, {"reply", "\u5FDC\u7B54"}, {"one.in.many", "%1$s #%2$d / %3$d"}, {"alias.in.cacerts", "cacerts\u5185\u306E\u767A\u884C\u8005<%s>"}, {"alias.in.keystore", "\u767A\u884C\u8005<%s>"}, {"with.weak", "%s (\u5F31)"}, {"key.bit", "%1$d\u30D3\u30C3\u30C8%2$s\u30AD\u30FC"}, {"key.bit.weak", "%1$d\u30D3\u30C3\u30C8%2$s\u30AD\u30FC(\u5F31)"}, {"unknown.size.1", "\u4E0D\u660E\u306A\u30B5\u30A4\u30BA\u306E%s\u30AD\u30FC"}, {".PATTERN.printX509Cert.with.weak", "\u6240\u6709\u8005: {0}\n\u767A\u884C\u8005: {1}\n\u30B7\u30EA\u30A2\u30EB\u756A\u53F7: {2}\n\u6709\u52B9\u671F\u9593\u306E\u958B\u59CB\u65E5: {3}\u7D42\u4E86\u65E5: {4}\n\u8A3C\u660E\u66F8\u306E\u30D5\u30A3\u30F3\u30AC\u30D7\u30EA\u30F3\u30C8:\n\t SHA1: {5}\n\t SHA256: {6}\n\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u540D: {7}\n\u30B5\u30D6\u30B8\u30A7\u30AF\u30C8\u516C\u958B\u30AD\u30FC\u30FB\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0: {8}\n\u30D0\u30FC\u30B8\u30E7\u30F3: {9}"}, {"PKCS.10.with.weak", "PKCS #10\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8(\u30D0\u30FC\u30B8\u30E7\u30F31.0)\n\u30B5\u30D6\u30B8\u30A7\u30AF\u30C8: %1$s\n\u30D5\u30A9\u30FC\u30DE\u30C3\u30C8: %2$s\n\u516C\u958B\u30AD\u30FC: %3$s\n\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0: %4$s\n"}, {"verified.by.s.in.s.weak", "%2$s\u5185\u306E%1$s\u306B\u3088\u308A%3$s\u3067\u691C\u8A3C\u3055\u308C\u307E\u3057\u305F"}, {"whose.sigalg.risk", "%1$s\u306F%2$s\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u3092\u4F7F\u7528\u3057\u3066\u304A\u308A\u3001\u3053\u308C\u306F\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30EA\u30B9\u30AF\u3068\u307F\u306A\u3055\u308C\u307E\u3059\u3002"}, {"whose.key.risk", "%1$s\u306F%2$s\u3092\u4F7F\u7528\u3057\u3066\u304A\u308A\u3001\u3053\u308C\u306F\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30EA\u30B9\u30AF\u3068\u307F\u306A\u3055\u308C\u307E\u3059\u3002"}, {"jks.storetype.warning", "%1$s\u30AD\u30FC\u30B9\u30C8\u30A2\u306F\u72EC\u81EA\u306E\u5F62\u5F0F\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059\u3002\"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\"\u3092\u4F7F\u7528\u3059\u308B\u696D\u754C\u6A19\u6E96\u306E\u5F62\u5F0F\u3067\u3042\u308BPKCS12\u306B\u79FB\u884C\u3059\u308B\u3053\u3068\u3092\u304A\u85A6\u3081\u3057\u307E\u3059\u3002"}, {"migrate.keystore.warning", "\"%1$s\"\u304C%4$s\u306B\u79FB\u884C\u3055\u308C\u307E\u3057\u305F\u3002%2$s\u30AD\u30FC\u30B9\u30C8\u30A2\u306F\"%3$s\"\u3068\u3057\u3066\u30D0\u30C3\u30AF\u30A2\u30C3\u30D7\u3055\u308C\u307E\u3059\u3002"}, {"backup.keystore.warning", "\u5143\u306E\u30AD\u30FC\u30B9\u30C8\u30A2\"%1$s\"\u306F\"%3$s\"\u3068\u3057\u3066\u30D0\u30C3\u30AF\u30A2\u30C3\u30D7\u3055\u308C\u307E\u3059..."}, {"importing.keystore.status", "\u30AD\u30FC\u30B9\u30C8\u30A2%1$s\u3092%2$s\u306B\u30A4\u30F3\u30DD\u30FC\u30C8\u3057\u3066\u3044\u307E\u3059..."}, {"keyalg.option.1.missing.warning", "-keyalg\u30AA\u30D7\u30B7\u30E7\u30F3\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u30C7\u30D5\u30A9\u30EB\u30C8\u306E\u30AD\u30FC\u30FB\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0(%s)\u306F\u3001\u65E7\u5F0F\u306E\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u3067\u3001\u73FE\u5728\u306F\u63A8\u5968\u3055\u308C\u307E\u305B\u3093\u3002JDK\u306E\u5F8C\u7D9A\u306E\u30EA\u30EA\u30FC\u30B9\u3067\u306F\u3001\u30C7\u30D5\u30A9\u30EB\u30C8\u306F\u524A\u9664\u3055\u308C\u308B\u4E88\u5B9A\u3067\u3001-keyalg\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u6307\u5B9A\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"}, {"showinfo.no.option", "-showinfo\u306E\u30AA\u30D7\u30B7\u30E7\u30F3\u304C\u3042\u308A\u307E\u305B\u3093\u3002\"keytool -showinfo -tls\"\u3092\u8A66\u3057\u3066\u304F\u3060\u3055\u3044\u3002"}, }; /** * Returns the contents of this <code>ResourceBundle</code>. * * <p> * * @return the contents of this <code>ResourceBundle</code>. */ @Override public Object[][] getContents() { return contents; } }
md-5/jdk10
src/java.base/share/classes/sun/security/tools/keytool/Resources_ja.java
Java
gpl-2.0
45,912
""" core/api/serializers.py is the module for core model api data serializers """ #import core django module from django.contrib.auth.models import User, Permission #import external modules from rest_framework import serializers #import project modules from core.models import (Product, ProductCategory, UnitOfMeasurement, UOMCategory, CompanyCategory, Company, Currency, Rate, Contact, Address, EmployeeCategory, Employee, ProductPresentation, ModeOfAdministration, ProductItem, ProductFormulation) class UserSerializer(serializers.ModelSerializer): """ REST API serializer for User model """ class Meta: model = User class BaseModelSerializer(serializers.ModelSerializer): """ Base Model Serializer for models """ created_by = UserSerializer(required=False, read_only=True) modified_by = UserSerializer(required=False, read_only=True) class ProductCategorySerializer(BaseModelSerializer): """ REST API Serializer for ProductCategory model """ class Meta: model = ProductCategory class ProductSerializer(BaseModelSerializer): """ REST API Serializer for Product models """ class Meta: model = Product class UOMCategorySerializer(BaseModelSerializer): """ REST API Serializer for UOMCategory model """ class Meta: model = UOMCategory class UnitOfMeasurementSerializer(BaseModelSerializer): """ REST API Serializer for UnitOfMeasurement model """ class Meta: model = UnitOfMeasurement class CompanyCategorySerializer(BaseModelSerializer): """ REST API serializer for CompanyCategory model """ class Meta: model = CompanyCategory class CompanySerializer(BaseModelSerializer): """ REST API serializer for Company model """ class Meta: model = Company class CurrencySerializer(BaseModelSerializer): """ REST API serializer for Currency model """ class Meta: model = Currency fields = ('code', 'name', 'symbol', 'symbol_position', 'rates',) class RateSerializer(BaseModelSerializer): """ REST API serializer for Rate model """ class Meta: model = Rate class ContactSerializer(BaseModelSerializer): """ REST API serializer for Contact model """ class Meta: model = Contact class AddressSerializer(BaseModelSerializer): """ REST API serializer for Address model """ class Meta: model = Address class EmployeeCategorySerializer(BaseModelSerializer): """ REST API serializer for EmployeeCategory """ class Meta: model = EmployeeCategory class EmployeeSerializer(BaseModelSerializer): """ REST API serializer for Employee """ class Meta: model = Employee class PermissionSerializer(BaseModelSerializer): """ REST API serializer for Permission model """ class Meta: model = Permission class ProductPresentationSerializer(BaseModelSerializer): """ REST API serializer for ProductPresentation model """ class Meta: model = ProductPresentation class ModeOfAdministrationSerializer(BaseModelSerializer): """ REST API serializer for ModeOfAdministration model """ class Meta: model = ModeOfAdministration class ProductItemSerializer(BaseModelSerializer): """ REST API serializer for ProductItem model """ class Meta: model = ProductItem class ProductFormulationSerializer(BaseModelSerializer): """ REST API serializer for ProductFormulation model, it can be Lyophilized, Liquid or Not Applicable """ class Meta: model = ProductFormulation
eHealthAfrica/LMIS
LMIS/core/api/serializers.py
Python
gpl-2.0
3,856
package com.charlesdream.office.word.enums; import com.charlesdream.office.BaseEnum; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; /** * Specifies how text is laid out in the layout mode for the current document. * <p> * * @author Charles Cui on 3/4/16. * @since 1.0 */ public enum WdLayoutMode implements BaseEnum { /** * No grid is used to lay out text. * * @since 1.0 */ wdLayoutModeDefault(0), /** * Text is laid out on a grid; the user specifies the number of lines and the number of characters per line. As the user types, Microsoft Word automatically aligns characters with gridlines. * * @since 1.0 */ wdLayoutModeGenko(3), /** * Text is laid out on a grid; the user specifies the number of lines and the number of characters per line. As the user types, Microsoft Word doesn't automatically align characters with gridlines. * * @since 1.0 */ wdLayoutModeGrid(1), /** * Text is laid out on a grid; the user specifies the number of lines, but not the number of characters per line. * * @since 1.0 */ wdLayoutModeLineGrid(2); private static final Map<Integer, WdLayoutMode> lookup; static { lookup = new HashMap<>(); for (WdLayoutMode e : EnumSet.allOf(WdLayoutMode.class)) { lookup.put(e.value(), e); } } private final int value; WdLayoutMode(int value) { this.value = value; } /** * Find the enum type by its value. * * @param value The enum value. * @return The enum type, or null if this enum value does not exists. * @since 1.0 */ public static WdLayoutMode find(int value) { WdLayoutMode result = lookup.get(value); return result; } /** * Find the enum type by its value, with the default value. * * @param value The enum value. * @param defaultValue The default return value if the enum value does not exists. * @return The enum type, or the default value if this enum value does not exists. * @since 1.0 */ public static WdLayoutMode find(int value, WdLayoutMode defaultValue) { WdLayoutMode result = WdLayoutMode.find(value); if (result == null) { result = defaultValue; } return result; } /** * Get the value of a enum type. * * @return The value of a enum type. * @since 1.0 */ public int value() { return this.value; } }
Lotusun/OfficeHelper
src/main/java/com/charlesdream/office/word/enums/WdLayoutMode.java
Java
gpl-2.0
2,574
using System; using System.Collections.Specialized; using System.Drawing; using System.Text.RegularExpressions; using System.Xml; namespace Wilco.SyntaxHighlighting { /// <summary> /// Represents an Xml scanner. /// </summary> public class XmlScanner : ScannerBase { private XmlSpecialCharNode xmlSpecialCharNode; private XmlNamespaceNode xmlNamespaceNode; private XmlTagNode xmlTagNode; private XmlCommentNode xmlCommentNode; private XmlAttributeNameNode xmlAttributeNameNode; private XmlAttributeValueNode xmlAttributeValueNode; private bool identifierEnabled; /// <summary> /// Occurs when XML was matched. /// </summary> public event MatchEventHandler Match; /// <summary> /// Gets or sets the Xml special char node. /// </summary> public XmlSpecialCharNode XmlSpecialCharNode { get { return this.xmlSpecialCharNode; } set { if (value != this.xmlSpecialCharNode) { this.xmlSpecialCharNode = value; } } } /// <summary> /// Gets or sets the Xml namespace node. /// </summary> public XmlNamespaceNode XmlNamespaceNode { get { return this.xmlNamespaceNode; } set { if (value != this.xmlNamespaceNode) { this.xmlNamespaceNode = value; } } } /// <summary> /// Gets or sets the Xml tag node. /// </summary> public XmlTagNode XmlTagNode { get { return this.xmlTagNode; } set { if (value != this.xmlTagNode) { this.xmlTagNode = value; } } } /// <summary> /// Gets or sets the Xml comment node. /// </summary> public XmlCommentNode XmlCommentNode { get { return this.xmlCommentNode; } set { if (value != this.xmlCommentNode) { this.xmlCommentNode = value; } } } /// <summary> /// Gets or sets the Xml attribute name node. /// </summary> public XmlAttributeNameNode XmlAttributeNameNode { get { return this.xmlAttributeNameNode; } set { if (value != this.xmlAttributeNameNode) { this.xmlAttributeNameNode = value; } } } /// <summary> /// Gets or sets the Xml attribute value node. /// </summary> public XmlAttributeValueNode XmlAttributeValueNode { get { return this.xmlAttributeValueNode; } set { if (value != this.xmlAttributeValueNode) { this.xmlAttributeValueNode = value; } } } /// <summary> /// Initializes a new instance of an <see cref="Wilco.SyntaxHighlighting.XmlScanner"/> class. /// </summary> public XmlScanner() : base(null, null) { // } /// <summary> /// Initializes a new instance of an <see cref="Wilco.SyntaxHighlighting.XmlScanner"/> class. /// </summary> /// <param name="tokenizer">The <see cref="Wilco.SyntaxHighlighting.TokenizerBase"/> which is used to tokenize the source code.</param> /// <param name="scannerResult">The <see cref="Wilco.SyntaxHighlighting.OccurrenceCollection"/> which will contain the scanner result.</param> public XmlScanner(TokenizerBase tokenizer, OccurrenceCollection scannerResult) : base(tokenizer, scannerResult) { this.xmlSpecialCharNode = new XmlSpecialCharNode(); this.xmlSpecialCharNode.ForeColor = System.Drawing.Color.Blue; this.xmlTagNode = new XmlTagNode(); this.xmlTagNode.ForeColor = System.Drawing.Color.Maroon; this.xmlNamespaceNode = new XmlNamespaceNode(); this.xmlNamespaceNode.ForeColor = System.Drawing.Color.MediumVioletRed; this.xmlCommentNode = new XmlCommentNode(); this.xmlCommentNode.ForeColor = System.Drawing.Color.Green; this.xmlAttributeNameNode = new XmlAttributeNameNode(); this.xmlAttributeNameNode.ForeColor = System.Drawing.Color.Red; this.xmlAttributeValueNode = new XmlAttributeValueNode(); this.xmlAttributeValueNode.ForeColor = System.Drawing.Color.Blue; this.SetID("XmlScanner"); } /// <summary> /// Initializes a new instance of a <see cref="Wilco.SyntaxHighlighting.IScanner"/> implementation class. /// </summary> /// <param name="tokenizer">The <see cref="Wilco.SyntaxHighlighting.TokenizerBase"/> which is used to tokenize the source code.</param> /// <param name="scannerResult">The <see cref="Wilco.SyntaxHighlighting.OccurrenceCollection"/> which will contain the scanner result.</param> /// <returns>A new instance of a <see cref="Wilco.SyntaxHighlighting.IScanner"/> implementation class.</returns> public override IScanner Create(TokenizerBase tokenizer, OccurrenceCollection scannerResult) { return new XmlScanner(tokenizer, scannerResult); } /// <summary> /// Loads the state of the scanner. /// </summary> /// <param name="state">An <see cref="System.Object"/> that contains the state of the scanner.</param> public override void LoadState(object state) { XmlElement element = (XmlElement)state; this.LoadNode(element, this.xmlSpecialCharNode, "SpecialCharNode"); this.LoadNode(element, this.xmlTagNode, "TagNode"); this.LoadNode(element, this.xmlNamespaceNode, "NamespaceNode"); this.LoadNode(element, this.xmlCommentNode, "CommentNode"); this.LoadNode(element, this.xmlAttributeNameNode, "AttributeNameNode"); this.LoadNode(element, this.xmlAttributeValueNode, "AttributeValueNode"); } /// <summary> /// Loads the information for a node. /// </summary> /// <param name="element">The <see cref="System.Xml.XmlElement"/> which contains the information about the node.</param> /// <param name="node">The <see cref="Wilco.SyntaxHighlighting.INode"/> implementation class for which the information will be set.</param> /// <param name="name">The name of the node.</param> private void LoadNode(XmlElement element, INode node, string name) { FontConverter converter = new FontConverter(); XmlElement nodeElement = (XmlElement)element.SelectSingleNode(String.Format("nodes/node[@name='{0}']", name)); node.BackColor = ColorTranslator.FromHtml(element.SelectSingleNode("settings/setting[@name='BackColor']").InnerText); node.ForeColor = ColorTranslator.FromHtml(element.SelectSingleNode("settings/setting[@name='ForeColor']").InnerText); node.Font = (Font)converter.ConvertFromString(element.SelectSingleNode("settings/setting[@name='Font']").InnerText); node.NavigateUrl = element.SelectSingleNode("settings/setting[@name='NavigateUrl']").InnerText; } /// <summary> /// Saves the current state of the scanner. /// </summary> /// <param name="container">The container which will contain the state.</param> /// <returns>An <see cref="System.Object"/> that contains the state of the scanner.</returns> public override object SaveState(object container) { XmlDocument document = (XmlDocument)container; XmlElement element = (XmlElement)base.SaveState(container); // Save settings. XmlElement nodeRootElement = document.CreateElement("nodes"); element.AppendChild(nodeRootElement); this.StoreNode(document, nodeRootElement, this.xmlSpecialCharNode, "SpecialCharNode"); this.StoreNode(document, nodeRootElement, this.xmlTagNode, "TagNode"); this.StoreNode(document, nodeRootElement, this.xmlNamespaceNode, "NamespaceNode"); this.StoreNode(document, nodeRootElement, this.xmlCommentNode, "CommentNode"); this.StoreNode(document, nodeRootElement, this.xmlAttributeNameNode, "AttributeNameNode"); this.StoreNode(document, nodeRootElement, this.xmlAttributeValueNode, "AttributeValueNode"); return element; } /// <summary> /// Stores a node. /// </summary> /// <param name="document">The document which will contain the settings for this node.</param> /// <param name="nodeRootElement">The element which will hold the node's settings.</param> /// <param name="node">The node which should be represented.</param> /// <param name="name">The name of the node.</param> private void StoreNode(XmlDocument document, XmlElement nodeRootElement, INode node, string name) { XmlElement nodeElement = document.CreateElement("node"); nodeElement.SetAttribute("name", name); nodeRootElement.AppendChild(nodeElement); XmlElement settingRootElement = document.CreateElement("settings"); nodeElement.AppendChild(settingRootElement); FontConverter converter = new FontConverter(); settingRootElement.AppendChild(this.CreateSetting(document, "BackColor", ColorTranslator.ToHtml(node.BackColor))); settingRootElement.AppendChild(this.CreateSetting(document, "ForeColor", ColorTranslator.ToHtml(node.ForeColor))); settingRootElement.AppendChild(this.CreateSetting(document, "ForeColor", converter.ConvertToString(node.Font))); settingRootElement.AppendChild(this.CreateSetting(document, "NavigateUrl", node.NavigateUrl)); } /// <summary> /// Creates a steting. /// </summary> /// <param name="document">The document which will contain the setting.</param> /// <param name="name">The name of the setting.</param> /// <param name="value">The value of the setting.</param> /// <returns>The <see cref="System.Xml.XmlElement"/> which represents the setting.</returns> private XmlElement CreateSetting(XmlDocument document, string name, string value) { XmlElement element = document.CreateElement("setting"); element.SetAttribute("name", name); element.InnerText = value; return element; } /// <summary> /// Scans a token. /// </summary> /// <remarks> /// An <see cref="Wilco.SyntaxHighlighting.IScanner"/> implementation will generally have a reference to a /// <see cref="Wilco.SyntaxHighlighting.NodeCollection"/> which will be used to store results of a scan. /// </remarks> /// <param name="token">A token from the source code.</param> public override void Scan(string token) { if (!this.Enabled) { if (this.Child != null) { this.Child.Scan(token); } } else { bool isMatch = false; // Match the closing tag, such as "</asp:Label>"; if ((this.Tokenizer.Position + 2 <= this.Tokenizer.Source.Length) && this.Tokenizer.GetNextTokens(2) == "</") { this.ScannerResult.Add(new Occurrence(this.Tokenizer.Position, 2, this.xmlSpecialCharNode)); // Match [special chars/namespace/]tag. int offset = 2; string ns = this.MatchNamespace(offset); if (ns.Length > 0) offset += ns.Length + 1; string tag = this.MatchTag(offset); if (tag.Length > 0) offset += tag.Length; // Match end character of the closing tag (">"). int endCharIndex = this.Tokenizer.Source.IndexOfAny("<>".ToCharArray(), this.Tokenizer.Position + offset); if (endCharIndex > -1) { if (this.Tokenizer.Source.Substring(endCharIndex, 1).IndexOfAny("<".ToCharArray()) == -1) { this.ScannerResult.Add(new Occurrence(endCharIndex, 1, this.xmlSpecialCharNode)); this.OnMatch(new MatchEventArgs(this.Tokenizer.Position, endCharIndex + 1, ns, tag, null, MatchType.EndTag)); } this.Tokenizer.MoveTo(endCharIndex); } else this.Tokenizer.MoveTo(this.Tokenizer.Position + offset); } // Match comments. else if ((this.Tokenizer.Position + 4 <= this.Tokenizer.Source.Length) && this.Tokenizer.GetNextTokens(4) == "<!--") { int endCharIndex = this.Tokenizer.Source.IndexOf("->", this.Tokenizer.Position + 4); if (endCharIndex == -1) endCharIndex = this.Tokenizer.Source.Length; else endCharIndex += 2; this.ScannerResult.Add(new Occurrence(this.Tokenizer.Position, endCharIndex - this.Tokenizer.Position, this.xmlCommentNode)); this.Tokenizer.MoveTo(endCharIndex - 1); } // Match start identifier. else if ((this.Tokenizer.Position + 2 <= this.Tokenizer.Source.Length) && this.Tokenizer.GetNextTokens(2) == "<?") { this.ScannerResult.Add(new Occurrence(this.Tokenizer.Position, 2, this.xmlSpecialCharNode)); this.OnMatch(new MatchEventArgs(this.Tokenizer.Position, 2, null, null, null, MatchType.StartIdentifier)); this.Tokenizer.MoveTo(this.Tokenizer.Position + 1); this.identifierEnabled = true; } // Match end identifier. else if ((this.Tokenizer.Position + 2 <= this.Tokenizer.Source.Length) && this.Tokenizer.GetNextTokens(2) == "?>") { this.ScannerResult.Add(new Occurrence(this.Tokenizer.Position, 2, this.xmlSpecialCharNode)); this.OnMatch(new MatchEventArgs(this.Tokenizer.Position, 2, null, null, null, MatchType.EndIdentifier)); this.Tokenizer.MoveTo(this.Tokenizer.Position + 1); this.identifierEnabled = false; } // Match attributes. else if (this.identifierEnabled) { // TODO: Fix this. /*int length = this.MatchAttributes(1, new NameValueCollection()); if (length > -1) this.Tokenizer.MoveTo(this.Tokenizer.Position + length);*/ } // Match either a starting tag, such as "<asp:Label>", or a single tag, such as "<asp:Label />". else if ((this.Tokenizer.Position + 1 <= this.Tokenizer.Source.Length) && this.Tokenizer.GetNextTokens(1) == "<") { this.ScannerResult.Add(new Occurrence(this.Tokenizer.Position, 1, this.xmlSpecialCharNode)); // Match [special chars/namespace/]tag. int offset = 1; string ns = this.MatchNamespace(offset); if (ns.Length > 0) offset += ns.Length + 1; string tag = this.MatchTag(offset); if (tag.Length > 0) offset += tag.Length; // Match attributes. NameValueCollection attributes = new NameValueCollection(); if (tag.Length > 0) { int attributesLength = this.MatchAttributes(offset, attributes); if (attributesLength > -1) offset += attributesLength; } // Match end character(s) of the start/single tag, such as ">" or "/>". int endCharIndex = this.Tokenizer.Source.IndexOfAny("\0<>".ToCharArray(), this.Tokenizer.Position + offset); if (endCharIndex > -1) { if (this.Tokenizer.Source.Substring(endCharIndex, 1).IndexOfAny("\0<".ToCharArray()) == -1) { if (this.Tokenizer.Source[endCharIndex - 1] == '/') { this.ScannerResult.Add(new Occurrence(endCharIndex - 1, 2, this.xmlSpecialCharNode)); this.OnMatch(new MatchEventArgs(this.Tokenizer.Position, endCharIndex + 1, ns, tag, attributes, MatchType.StandaloneTag)); } else { this.ScannerResult.Add(new Occurrence(endCharIndex, 1, this.xmlSpecialCharNode)); this.OnMatch(new MatchEventArgs(this.Tokenizer.Position, endCharIndex + 1, ns, tag, attributes, MatchType.StartTag)); } } this.Tokenizer.MoveTo(endCharIndex - 1); } else this.Tokenizer.MoveTo(this.Tokenizer.Position + offset); } if (!isMatch) { if (this.Child != null) { this.Child.Scan(token); } } } } /// <summary> /// Matches a namespace. /// </summary> /// <param name="offset">The offset from which the search can begin.</param> /// <returns>The matched namespace.</returns> private string MatchNamespace(int offset) { if ((this.Tokenizer.Position + offset) < this.Tokenizer.Source.Length && !char.IsNumber(this.Tokenizer.Source, this.Tokenizer.Position + offset)) { for (int i = this.Tokenizer.Position + offset; i < this.Tokenizer.Source.Length; i++) { if (!char.IsLetter(this.Tokenizer.Source, i)) { if (this.Tokenizer.Source[i] == ':') { int length = i - (this.Tokenizer.Position + offset); if (length > 0) this.ScannerResult.Add(new Occurrence(this.Tokenizer.Position + offset, length, this.xmlNamespaceNode)); return this.Tokenizer.Source.Substring(this.Tokenizer.Position + offset, length); } else return String.Empty; } } } return String.Empty; } /// <summary> /// Matches a tag. /// </summary> /// <param name="offset">The offset from which the search can begin.</param> /// <returns>The matched tag.</returns> private string MatchTag(int offset) { if ((this.Tokenizer.Position + offset) < this.Tokenizer.Source.Length && !char.IsNumber(this.Tokenizer.Source, this.Tokenizer.Position + offset)) { for (int i = this.Tokenizer.Position + offset; i < this.Tokenizer.Source.Length; i++) { char ch = this.Tokenizer.Source[i]; if (ch != '.' && !char.IsLetterOrDigit(ch)) { int length = i - (this.Tokenizer.Position + offset); if (length > 0) this.ScannerResult.Add(new Occurrence(this.Tokenizer.Position + offset, length, this.xmlTagNode)); return this.Tokenizer.Source.Substring(this.Tokenizer.Position + offset, length); } } this.ScannerResult.Add(new Occurrence(this.Tokenizer.Position + offset, this.Tokenizer.Source.Length - (this.Tokenizer.Position + offset), this.xmlTagNode)); return this.Tokenizer.Source.Substring(this.Tokenizer.Position + offset, this.Tokenizer.Source.Length - (this.Tokenizer.Position + offset)); } return String.Empty; } /// <summary> /// Matches an attributes. /// </summary> /// <param name="offset">The offset from which the search can begin.</param> /// <param name="attributes">The matched attributes.</param> /// <returns>The length of the matched attribute value.</returns> private int MatchAttributes(int offset, NameValueCollection attributes) { // NOTE: This method should be reimplemented. The regexp won't work properly when an attribute without a value is entered, e.g.: <?xml a="b"?> int lastCharIndex = this.Tokenizer.Source.Length; // Get end char of the tag (">"). char stringType = '\0'; for (int i = this.Tokenizer.Position + offset; i < this.Tokenizer.Source.Length; i++) { if (this.Tokenizer.Source[i] == '\"' || this.Tokenizer.Source[i] == '\'') { if (stringType == '\0') stringType = this.Tokenizer.Source[i]; else if (stringType == this.Tokenizer.Source[i]) stringType = '\0'; } else if (stringType == '\0' && this.Tokenizer.Source[i] == '>') { lastCharIndex = i; if (this.Tokenizer.Source[i - 1] == '/') lastCharIndex--; break; } } MatchCollection matches = Regex.Matches(this.Tokenizer.Source.Substring(this.Tokenizer.Position + offset, lastCharIndex - (this.Tokenizer.Position + offset)), @"( (?'name'\w+) \s* (?'attGroup' = \s* (?'value' [^\s""'/\?>]+ | ""[^""]*"" | '[^']*')){0,1} \s* )*", RegexOptions.ExplicitCapture|RegexOptions.IgnorePatternWhitespace|RegexOptions.Compiled); int length = -1; for (int i = 0; i < matches.Count; i++) { for (int j = 0; j < matches[i].Groups["name"].Captures.Count; j++) { if (matches[i].Groups["name"].Captures[j].Length > 0) { this.ScannerResult.Add(new Occurrence(this.Tokenizer.Position + offset + matches[i].Groups["name"].Captures[j].Index, matches[i].Groups["name"].Captures[j].Length, this.xmlAttributeNameNode)); if (j < matches[i].Groups["value"].Captures.Count && matches[i].Groups["value"].Captures[j].Length > 0) { this.ScannerResult.Add(new Occurrence(this.Tokenizer.Position + offset + matches[i].Groups["value"].Captures[j].Index, matches[i].Groups["value"].Captures[j].Length, this.xmlAttributeValueNode)); length = matches[i].Groups["value"].Captures[j].Index + matches[i].Groups["value"].Captures[j].Length; } else length = matches[i].Groups["name"].Captures[j].Index + matches[i].Groups["name"].Captures[j].Length; if (matches[i].Groups["name"].Captures[j].Length > 0 && j < matches[i].Groups["value"].Captures.Count && matches[i].Groups["value"].Captures[j].Length > 0) attributes.Add(matches[i].Groups["name"].Captures[j].Value, matches[i].Groups["value"].Captures[j].Value); } } } return length; } /// <summary> /// Raises the <see cref="Wilco.SyntaxHighlighting.XmlScanner.Match"/> event. /// </summary> /// <param name="e">An <see cref="System.EventArgs"/> object that contains the event data.</param> protected void OnMatch(MatchEventArgs e) { if (this.Match != null) this.Match(this, e); } /// <summary> /// Resets the scanner. /// </summary> public override void Reset() { this.identifierEnabled = false; } } }
Verlic/BlueMoon
Source/Wilco.SyntaxHighlighting/Engine/Scanner/Implementation/XmlScanner.cs
C#
gpl-2.0
26,019
<?php get_header(); ?> <div id="contentwrap"> <div id="infoblock"> <h2>Latest Blog Posts</h2> </div> <?php if (have_posts()): while (have_posts()): the_post(); ?> <div class="post"> <h2 class="title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2> <p class="subtitle"><?php the_time('jS M y') ?>. <?php comments_popup_link('0 Comments', '1 Comment', '% Comments'); ?></p> </div> <?php endwhile; else: ?> <div id="infoblock"> <h2>Page Not Found</h2> </div> <div class="post"> <p>Sorry, The page you are looking for cannot be found!</p> </div> <?php endif; ?> <?php if (mopr_check_pagination()): ?> <div id="indexpostfoot"> <p><?php posts_nav_link(' &#183; ', 'Previous Page', 'Next Page'); ?></p> </div> <?php endif; ?> <div id="pageblock"> <h2>Blog Pages</h2> </div> <div class="page"> <ol id="pages"> <?php wp_list_pages('title_li='); ?> </ol> </div> </div> <?php get_footer(); ?>
AznStyle/to
wp-content/plugins/mobilepress/themes/iphone/index.php
PHP
gpl-2.0
1,108
package com.netease.xmpp.websocket.handler; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.handler.codec.http.HttpHeaders.Names; import org.jboss.netty.handler.codec.http.HttpHeaders.Values; import org.jboss.netty.handler.codec.http.websocket.WebSocketFrame; import org.jboss.netty.handler.codec.http.websocket.WebSocketFrameDecoder; import org.jboss.netty.handler.codec.http.websocket.WebSocketFrameEncoder; import org.jboss.netty.util.CharsetUtil; import org.jivesoftware.multiplexer.spi.ClientFailoverDeliverer; import com.netease.xmpp.websocket.CMWebSocketConnection; import com.netease.xmpp.websocket.codec.Hybi10WebSocketFrameDecoder; import com.netease.xmpp.websocket.codec.Hybi10WebSocketFrameEncoder; import com.netease.xmpp.websocket.codec.Pong; import sun.misc.BASE64Encoder; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.concurrent.Executor; import static org.jboss.netty.handler.codec.http.HttpHeaders.isKeepAlive; import static org.jboss.netty.handler.codec.http.HttpHeaders.setContentLength; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONNECTION; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.ORIGIN; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SEC_WEBSOCKET_KEY1; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SEC_WEBSOCKET_KEY2; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SEC_WEBSOCKET_LOCATION; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SEC_WEBSOCKET_ORIGIN; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SEC_WEBSOCKET_PROTOCOL; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.UPGRADE; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.WEBSOCKET_LOCATION; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.WEBSOCKET_ORIGIN; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.WEBSOCKET_PROTOCOL; import static org.jboss.netty.handler.codec.http.HttpHeaders.Values.WEBSOCKET; import static org.jboss.netty.handler.codec.http.HttpMethod.GET; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1; public class NettyWebSocketChannelHandler extends SimpleChannelUpstreamHandler { private static final MessageDigest SHA_1; static { try { SHA_1 = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("SHA-1 not supported on this platform"); } } private static final String ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private static final BASE64Encoder encoder = new BASE64Encoder(); private static final Charset ASCII = Charset.forName("ASCII"); protected final Executor executor; protected final WebSocketHandler handler; protected CMWebSocketConnection webSocketConnection; public NettyWebSocketChannelHandler(Executor executor, WebSocketHandler handler) { this.handler = handler; this.executor = executor; } @Override public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception { Object msg = e.getMessage(); if (msg instanceof HttpRequest) { handleHttpRequest(ctx, (HttpRequest) msg); } else if (msg instanceof WebSocketFrame) { handleWebSocketFrame(ctx, (WebSocketFrame) msg); } } @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { executor.execute(new Runnable() { @Override public void run() { try { handler.onClose(webSocketConnection); } catch (Exception e1) { e1.printStackTrace(); } } }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, final ExceptionEvent e) throws Exception { System.out.println("EXCEPTION"); e.getChannel().close(); e.getCause().printStackTrace(); } private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception { // Allow only GET . if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Serve the WebSocket handshake request. if (Values.UPGRADE.equalsIgnoreCase(req.getHeader(CONNECTION)) && WEBSOCKET.equalsIgnoreCase(req.getHeader(Names.UPGRADE))) { // Create the WebSocket handshake response. HttpResponse res = new DefaultHttpResponse(HTTP_1_1, new HttpResponseStatus(101, "Web Socket Protocol Handshake")); res.addHeader(Names.UPGRADE, WEBSOCKET); res.addHeader(CONNECTION, Values.UPGRADE); prepareConnection(req, res, ctx); try { handler.onOpen(this.webSocketConnection); } catch (Exception e) { // TODO e.printStackTrace(); } } } private void handleWebSocketFrame(ChannelHandlerContext ctx, final WebSocketFrame frame) { try { if (frame instanceof Pong) { handler.onPong(webSocketConnection, frame.getTextData()); } else { if (frame.isText()) { handler.onMessage(webSocketConnection, frame.getTextData()); } else { handler.onMessage(webSocketConnection, frame.getBinaryData().array()); } } } catch (Throwable t) { // TODO t.printStackTrace(); } } private void prepareConnection(HttpRequest req, HttpResponse res, ChannelHandlerContext ctx) { this.webSocketConnection = new CMWebSocketConnection(ctx.getChannel(), new ClientFailoverDeliverer()); if (isHybi10WebSocketRequest(req)) { this.webSocketConnection.setVersion(WebSocketConnection.Version.HYBI_10); upgradeResponseHybi10(req, res); ctx.getChannel().write(res); adjustPipelineToHybi(ctx); } else if (isHixie76WebSocketRequest(req)) { this.webSocketConnection.setVersion(WebSocketConnection.Version.HIXIE_76); upgradeResponseHixie76(req, res); ctx.getChannel().write(res); adjustPipelineToHixie(ctx); } else { this.webSocketConnection.setVersion(WebSocketConnection.Version.HIXIE_75); upgradeResponseHixie75(req, res); ctx.getChannel().write(res); adjustPipelineToHixie(ctx); } } private void adjustPipelineToHixie(ChannelHandlerContext ctx) { ChannelPipeline p = ctx.getChannel().getPipeline(); p.remove("aggregator"); p.replace("decoder", "wsdecoder", new WebSocketFrameDecoder()); p.replace("handler", "wshandler", this); p.replace("encoder", "wsencoder", new WebSocketFrameEncoder()); } private void adjustPipelineToHybi(ChannelHandlerContext ctx) { ChannelPipeline p = ctx.getChannel().getPipeline(); p.remove("aggregator"); p.replace("decoder", "wsdecoder", new Hybi10WebSocketFrameDecoder()); p.replace("handler", "wshandler", this); p.replace("encoder", "wsencoder", new Hybi10WebSocketFrameEncoder()); } private boolean isHybi10WebSocketRequest(HttpRequest req) { return req.containsHeader("Sec-WebSocket-Version"); } private boolean isHixie76WebSocketRequest(HttpRequest req) { return req.containsHeader(SEC_WEBSOCKET_KEY1) && req.containsHeader(SEC_WEBSOCKET_KEY2); } private static synchronized String generateAccept(String key) { String s = key + ACCEPT_GUID; byte[] b = SHA_1.digest(s.getBytes(ASCII)); return encoder.encode(b); } private void upgradeResponseHybi10(HttpRequest req, HttpResponse res) { String version = req.getHeader("Sec-WebSocket-Version"); if (!"8".equals(version)) { res.setStatus(HttpResponseStatus.UPGRADE_REQUIRED); res.setHeader("Sec-WebSocket-Version", "8"); return; } String key = req.getHeader("Sec-WebSocket-Key"); if (key == null) { res.setStatus(HttpResponseStatus.BAD_REQUEST); return; } String accept = generateAccept(key); res.setStatus(new HttpResponseStatus(101, "Switching Protocols")); res.addHeader(UPGRADE, WEBSOCKET.toLowerCase()); res.addHeader(CONNECTION, UPGRADE); res.addHeader("Sec-WebSocket-Accept", accept); } private void upgradeResponseHixie76(HttpRequest req, HttpResponse res) { res.setStatus(new HttpResponseStatus(101, "Web Socket Protocol Handshake")); res.addHeader(UPGRADE, WEBSOCKET); res.addHeader(CONNECTION, UPGRADE); res.addHeader(SEC_WEBSOCKET_ORIGIN, req.getHeader(ORIGIN)); res.addHeader(SEC_WEBSOCKET_LOCATION, getWebSocketLocation(req)); String protocol = req.getHeader(SEC_WEBSOCKET_PROTOCOL); if (protocol != null) { res.addHeader(SEC_WEBSOCKET_PROTOCOL, protocol); } // Calculate the answer of the challenge. String key1 = req.getHeader(SEC_WEBSOCKET_KEY1); String key2 = req.getHeader(SEC_WEBSOCKET_KEY2); int a = (int) (Long.parseLong(key1.replaceAll("[^0-9]", "")) / key1.replaceAll("[^ ]", "") .length()); int b = (int) (Long.parseLong(key2.replaceAll("[^0-9]", "")) / key2.replaceAll("[^ ]", "") .length()); long c = req.getContent().readLong(); ChannelBuffer input = ChannelBuffers.buffer(16); input.writeInt(a); input.writeInt(b); input.writeLong(c); try { ChannelBuffer output = ChannelBuffers.wrappedBuffer(MessageDigest.getInstance("MD5") .digest(input.array())); res.setContent(output); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } private void upgradeResponseHixie75(HttpRequest req, HttpResponse res) { res.setStatus(new HttpResponseStatus(101, "Web Socket Protocol Handshake")); res.addHeader(UPGRADE, WEBSOCKET); res.addHeader(CONNECTION, HttpHeaders.Values.UPGRADE); res.addHeader(WEBSOCKET_ORIGIN, req.getHeader(ORIGIN)); res.addHeader(WEBSOCKET_LOCATION, getWebSocketLocation(req)); String protocol = req.getHeader(WEBSOCKET_PROTOCOL); if (protocol != null) { res.addHeader(WEBSOCKET_PROTOCOL, protocol); } } private String getWebSocketLocation(HttpRequest req) { return "ws://" + req.getHeader(HttpHeaders.Names.HOST) + req.getUri(); } private void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) { // Generate an error page if response status code is not OK (200). if (res.getStatus().getCode() != 200) { res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8)); setContentLength(res, res.getContent().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.getChannel().write(res); if (!isKeepAlive(req) || res.getStatus().getCode() != 200) { f.addListener(ChannelFutureListener.CLOSE); } } }
onlychoice/ws-xmpp-proxy
src/java/com/netease/xmpp/websocket/handler/NettyWebSocketChannelHandler.java
Java
gpl-2.0
12,857
<?php /** * DP Posts Widget * * Display posts in various ways you'd like. * * @package deTube * @subpackage Widgets * @since deTube 1.0 */ class DP_Widget_Posts extends WP_Widget { function __construct() { $widget_ops = array('classname' => 'widget-posts', 'description' => __( "Display posts in various ways you'd like.", 'dp') ); parent::__construct('dp-widget-posts', __('DP Posts Widget', 'dp'), $widget_ops); $this->alt_option_name = 'alt_dp_widget_posts'; add_action( 'save_post', array(&$this, 'flush_widget_cache') ); add_action( 'deleted_post', array(&$this, 'flush_widget_cache') ); add_action( 'switch_theme', array(&$this, 'flush_widget_cache') ); } function widget($args, $instance) { $cache = wp_cache_get('dp_widget_posts', 'widget'); if ( !is_array($cache) ) $cache = array(); if ( ! isset( $args['widget_id'] ) ) $args['widget_id'] = $this->id; if ( isset( $cache[ $args['widget_id'] ] ) ) { echo $cache[ $args['widget_id'] ]; return; } $style = isset($instance['style']) ? $instance['style'] : 'list'; extract($args); ob_start(); $title = apply_filters('widget_title', empty($instance['title']) ? __('Recent Posts', 'dp') : $instance['title'], $instance, $this->id_base); $query_args = $instance; $query_args['no_found_rows'] = true; $query_args = dp_parse_query_args($query_args); $r = new WP_Query( apply_filters( 'dp_widget_posts_args', $query_args ) ); if ($r->have_posts()) : ?> <?php echo $before_widget; ?> <?php if ( $title ) echo $before_title . $title . $after_title; ?> <ul class="<?php echo 'post-'.$style; ?>"> <?php while ($r->have_posts()) : $r->the_post(); $item_format = is_video() ? 'video' : 'post'; ?> <li class="item cf <?php echo 'item-'.$item_format; ?>"> <?php $image_size = ($style == 'list-full') ? 'custom-medium' : 'custom-small'; dp_thumb_html($image_size); ?> <div class="data"> <h4 class="title"><a href="<?php the_permalink() ?>" title="<?php echo esc_attr(get_the_title()); ?>"><?php the_title(); ?></a></h4> <p class="meta"> <span class="author"><?php _e('Added by', 'dp'); ?> <?php the_author_posts_link(); ?></span> <span class="time"><?php printf(__('%s ago', 'dp'), human_time(get_the_time('U'))); ?></span> </p> <p class="stats"><?php echo dp_get_post_stats(); ?></p> </div> </li> <?php endwhile; ?> </ul> <?php echo $after_widget; ?> <?php // Reset the global $the_post as this query will have stomped on it wp_reset_postdata(); endif; $cache[$args['widget_id']] = ob_get_flush(); wp_cache_set('dp_widget_posts', $cache, 'widget'); } function update( $new_instance, $old_instance ) { $new_instance['title'] = strip_tags($new_instance['title']); $new_instance['posts_per_page'] = (int) $new_instance['posts_per_page']; $new_instance['current_cat'] = isset($new_instance['current_cat']); $new_instance['current_author'] = isset($new_instance['current_author']); $this->flush_widget_cache(); $alloptions = wp_cache_get( 'alloptions', 'options' ); if ( isset($alloptions['alt_dp_widget_posts']) ) delete_option('alt_dp_widget_posts'); return $new_instance; } function flush_widget_cache() { wp_cache_delete('dp_widget_posts', 'widget'); } function form( $instance ) { $defaults = array( 'title' => __('Recent Posts', 'dp'), 'posts_per_page' => 6, 'orderby' => 'date', 'order' => 'desc', 'style' => 'list', 'cat' => '', 'current_cat' => true, 'current_author' => true, 'post__in' => '', 'style' => 'list', // list, list-full, grid-2 or grid-3 ); $instance = wp_parse_args( (array) $instance, $defaults ); // Styles $styles = array( 'list' => __( 'List with Thumbnail', 'dp' ), 'list-full' => __( 'List with Full Width Thumbnail', 'dp' ), 'grid-2' => __( '2 Columns Grid', 'dp' ), 'grid-3' => __( '3 Columns Grid', 'dp' ) ); $dropdown_categories = wp_dropdown_categories(array( 'echo' => 0, 'name' => $this->get_field_name( 'cat' ), 'selected' => $instance['cat'], 'show_option_all' => __('All', 'dp'), 'class' => 'widefat' )); $dropdown_sort_types = dp_dropdown_sort_types(array( 'echo' => 0, 'name' => $this->get_field_name( 'orderby' ), 'selected' => $instance['orderby'], 'class' => 'widefat' )); $dropdown_order_types = dp_dropdown_order_types(array( 'echo' => 0, 'name' => $this->get_field_name( 'order' ), 'selected' => $instance['order'], 'class' => 'widefat' )); ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'dp') ?></label> <input type="text" class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'posts_per_page' ); ?>"><?php _e('Number:', 'dp') ?></label> <input type="text" class="widefat" id="<?php echo $this->get_field_id( 'posts_per_page' ); ?>" name="<?php echo $this->get_field_name( 'posts_per_page' ); ?>" value="<?php echo $instance['posts_per_page']; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'orderby' ); ?>"><?php _e('Orderby:', 'dp') ?></label> <?php echo $dropdown_sort_types; ?> </p> <p> <label for="<?php echo $this->get_field_id( 'order' ); ?>"><?php _e('Order:', 'dp') ?></label> <?php echo $dropdown_order_types; ?> </p> <p> <label for="<?php echo $this->get_field_id( 'cat' ); ?>"><?php _e('Category:', 'dp') ?></label> <?php echo $dropdown_categories; ?> </p> <p><input id="<?php echo $this->get_field_id('current_cat'); ?>" name="<?php echo $this->get_field_name('current_cat'); ?>" type="checkbox" <?php checked(!empty($instance['current_cat']) ? $instance['current_cat'] : 0); ?> />&nbsp;<label for="<?php echo $this->get_field_id('current_cat'); ?>"><?php _e('Limit posts by current category on category archive pages?', 'dp'); ?></label></p> <p><input id="<?php echo $this->get_field_id('current_author'); ?>" name="<?php echo $this->get_field_name('current_author'); ?>" type="checkbox" <?php checked(!empty($instance['current_author']) ? $instance['current_author'] : 0); ?> />&nbsp;<label for="<?php echo $this->get_field_id('current_author'); ?>"><?php _e('Limit posts by current author on author archive pages?', 'dp'); ?></label></p> <p> <label for="<?php echo $this->get_field_id( 'post__in' ); ?>"><?php _e('Includes:', 'dp') ?></label> <input type="text" class="widefat" id="<?php echo $this->get_field_id( 'post__in' ); ?>" name="<?php echo $this->get_field_name( 'post__in' ); ?>" value="<?php echo $instance['post__in']; ?>" /> </p> <p class="description"> <?php _e('If you want to display specific posts, enter post ids to here, separate ids with commas, (e.g. 1,2,3,4). <br />if this field is not empty, category will be ignored. <br/>If you want to display posts sort by the order of your enter IDs, set "Sort" field as <strong>None</strong>.', 'dp'); ?> </p> <p> <label for="<?php echo $this->get_field_id( 'style' ); ?>"><?php _e('Style:', 'dp') ?></label> <select class="widefat" id="<?php echo $this->get_field_id( 'style' ); ?>" name="<?php echo $this->get_field_name( 'style' ); ?>"> <?php foreach ( $styles as $option_value => $option_label ) { ?> <option value="<?php echo $option_value; ?>" <?php selected( $instance['style'], $option_value ); ?>><?php echo $option_label; ?></option> <?php } ?> </select> </p> <?php } } // Register Widget add_action('widgets_init', 'register_dp_widget_posts'); function register_dp_widget_posts() { register_widget('DP_Widget_Posts'); }
bradryan13/MLS
wp-content/themes/yoo_nano2_wp/inc/widget-posts.php
PHP
gpl-2.0
7,808
package com.dynamo2.myerp.crm.dao.entities; // Generated Mar 20, 2012 11:10:03 AM by Hibernate Tools 3.4.0.CR1 import static javax.persistence.GenerationType.IDENTITY; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; /** * Person generated by hbm2java */ @Entity @Table(name = "person", catalog = "mycrm") public class Person implements java.io.Serializable { private static final long serialVersionUID = 1L; private Long id; private String firstName; private String lastName; private Date birthday; private String gender; private String idType; private String idNum; private String phone; private String mobile; private String email; private Date created; private String lastModifiedBy; private String createdBy; private Date lastModified; public Person() { } public Person(Date lastModified) { this.lastModified = lastModified; } public Person(String firstName, String lastName, Date birthday, String gender, String idType, String idNum, String phone, String mobile, String email, Date created, String lastModifiedBy, String createdBy, Date lastModified, String title) { this.firstName = firstName; this.lastName = lastName; this.birthday = birthday; this.gender = gender; this.idType = idType; this.idNum = idNum; this.phone = phone; this.mobile = mobile; this.email = email; this.created = created; this.lastModifiedBy = lastModifiedBy; this.createdBy = createdBy; this.lastModified = lastModified; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column(name = "first_name", length = 45) public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name = "last_name", length = 45) public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "birthday", length = 19) public Date getBirthday() { return this.birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Column(name = "gender", length = 45) public String getGender() { return this.gender; } public void setGender(String gender) { this.gender = gender; } @Column(name = "id_type", length = 45) public String getIdType() { return this.idType; } public void setIdType(String idType) { this.idType = idType; } @Column(name = "id_num", length = 45) public String getIdNum() { return this.idNum; } public void setIdNum(String idNum) { this.idNum = idNum; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "created", length = 19) public Date getCreated() { return this.created; } public void setCreated(Date created) { this.created = created; } @Column(name = "last_modified_by", length = 45) public String getLastModifiedBy() { return this.lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } @Column(name = "created_by", length = 45) public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "last_modified", nullable = false, length = 19) public Date getLastModified() { return this.lastModified; } public void setLastModified(Date lastModified) { this.lastModified = lastModified; } @Column(name = "phone") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Column(name = "mobile") public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } @Column(name = "email") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Transient public String getRealName() { return lastName + " " + firstName; } }
dynamo2/tianma
mycrm/src/main/java/com/dynamo2/myerp/crm/dao/entities/Person.java
Java
gpl-2.0
4,328
#include "operators.h" #define ROI_SIZE (100) Operator::Operator(cvb::CvID id):id_(id) { prev_label_ = cur_label_ = BACKGROUND; action_angle_ = -1.0; } void Operator::Process(const cv::Mat &frame) { ac_.ClassifyFrame(frame, &cur_label_); if ((cur_label_ == prev_label_)) consistency_cnt_ ++; else consistency_cnt_ = 0; prev_label_ = cur_label_; if (consistency_cnt_ < WINDOW_LENGTH) cur_label_ = BACKGROUND; oe_.Evaluate(frame, (int)cur_label_, &action_angle_); } void Operators::UpdateOperators() { //remove deleted tracks for (OperatorsMap::const_iterator it = ops_.begin(); it!=ops_.end(); ++it) { cvb::CvID op_id = it->second->get_id(); if (tracks_.count(op_id) == 0) { OperatorsMap::const_iterator next_op = it; int track_id = it->first; for (std::vector<int>::iterator track_it = track_id_queue_.begin(); track_it != track_id_queue_.end(); ++track_it) if (*track_it == track_id) { track_id_queue_.erase(track_it); break; } delete it->second; std::advance(next_op, 1); if (next_op == ops_.end()) { ops_.erase(it->first); break; } ops_.erase(it->first); it = next_op; } } //add new tracks for (cvb::CvTracks::const_iterator it = tracks_.begin(); it!=tracks_.end(); ++it) { cvb::CvID track_id = it->second->id; if (ops_.count(track_id) == 0) { Operator *op = new Operator(track_id); ops_.insert(CvIDOperator(track_id, op)); track_id_queue_.push_back(track_id); } } } void Operators::StoreROI(const cv::Mat &frame, const char* output_path_char) { static int cnt = 0; fs::path output_path; int dim = ROI_SIZE; output_path = fs::path(output_path_char); //CHECK(fs::exists(output_path)); for (cvb::CvTracks::const_iterator it=tracks_.begin(); it!=tracks_.end(); ++it) { // Store 25 percent of potential operators if ((rand() % 100) <= 25) { cv::Mat op = cv::Mat::zeros(dim, dim, frame.type()); cvb::CvTrack *track = (*it).second; cv::Rect r1,r2; cv::Mat tmp; char filename[50]; sprintf(filename, "_object_%03d.jpg", cnt++); r1 = cv::Rect(cv::Point(std::max<int>(0, (int)track->centroid.x - dim/2), std::max<int>(0, (int)track->centroid.y - dim/2)), cv::Point(std::min<int>(frame.cols, (int)track->centroid.x + dim/2), std::min<int>(frame.rows, (int)track->centroid.y + dim/2))); tmp = frame(r1); r2 = cv::Rect((dim - tmp.cols)/2, (dim - tmp.rows)/2, tmp.cols, tmp.rows); tmp.copyTo(op(r2)); cv::imwrite(output_path.string() + std::string(filename), op); } }//for (cvb::CvTracks::const_iterator it=opTracks.begin(); it!=opTracks.end(); ++it) } void Operators::ExtractROI(const cv::Mat &frame, std::vector<OperatorROI> *roi, int max_operators=1) { for (cvb::CvTracks::const_iterator it=tracks_.begin(); it!=tracks_.end(); ++it) { cv::Mat op = cv::Mat::zeros(ROI_SIZE, ROI_SIZE, frame.type()); cvb::CvTrack *track = (*it).second; bool processed_track = false; for (int i = 0; i < max_operators; i++) if (track->id == track_id_queue_[i]) { processed_track = true; break; } if (processed_track && (track->lifetime > 5)) { cv::Rect r1,r2; cv::Mat tmp; r1 = cv::Rect(cv::Point(std::max<int>(0, (int)track->centroid.x - ROI_SIZE/2), std::max<int>(0, (int)track->centroid.y - ROI_SIZE/2)), cv::Point(std::min<int>(frame.cols, (int)track->centroid.x + ROI_SIZE/2), std::min<int>(frame.rows, (int)track->centroid.y + ROI_SIZE/2))); tmp = frame(r1); r2 = cv::Rect((ROI_SIZE - tmp.cols)/2, (ROI_SIZE - tmp.rows)/2, tmp.cols, tmp.rows); tmp.copyTo(op(r2)); roi->push_back(OperatorROI(track, op)); }//if (track->lifetime > 5) }//for (cvb::CvTracks::const_iterator it=opTracks.begin(); it!=opTracks.end(); ++it) }
elialshan/mav_gesture_control
src/detection/operators.cpp
C++
gpl-2.0
4,383
/* * Created on Dec 7, 2004 * * This is the object given to the web-form. * It's a mapping between the report as seen from the JSP-code to the * way it's used in the service and domain layers. */ package no.abmu.abmstatistikk.annualstatistic.service; import java.beans.XMLEncoder; import java.io.OutputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.validation.Errors; import no.abmu.abmstatistikk.annualstatistic.domain.Answer; import no.abmu.abmstatistikk.annualstatistic.domain.Report; import no.abmu.abmstatistikk.annualstatistic.domain.Schema; /** * @author Henning Kulander <hennikul@linpro.no> * */ public class SchemaReport { private static final Log logger = (Log) LogFactory.getLog(SchemaReport.class); private Schema schema; private Report report; private ReportHelper reportHelper; private Class[] fieldClasses; protected Map field; private Map comment; private SchemaReport virtualSchemaReport; public SchemaReport(Report report) { this.report = report; this.reportHelper = new ReportHelper(report); this.schema = report.getSchema(); Set answers = report.getAnswers(); field = new HashMap(); comment = new HashMap(); if (answers != null) { Iterator answerIterator = answers.iterator(); int i = 0; fieldClasses = new Class[answers.size()+1]; while (answerIterator.hasNext()) { Answer answer = (Answer) answerIterator.next(); field.put(answer.getField().getName(), answer); comment.put(answer.getField().getName(), answer.getComment()); i++; } fieldClasses[i] = Report.class; } else { logger.error("No answers for current report!"); } } /* (non-Javadoc) * @see no.abmu.abmstatistikk.util.DynamicBeanFactory.BeanAdapter#setProperty(java.lang.String, java.lang.Object) */ public Map getField() { return field; } public void setField(Map newfield) { field = newfield; } public void setProperty(String name, Object value) { if (name.startsWith("field")) { String fieldName = name.substring(5); logger.debug("Setting answer for field "+fieldName+" to "+value); Answer answer = reportHelper.getAnswerByFieldName(fieldName); if (answer != null) { String stringValue = (String) value; answer.setValue(stringValue); return; } } else if (name.startsWith("comment")) { String fieldName = name.substring(7); logger.debug("Setting comment for field "+fieldName+" to "+value); Answer answer = reportHelper.getAnswerByFieldName(fieldName); if (answer != null) { String stringComment = (String) value; answer.setComment(stringComment); return; } } logger.error("setProperty called for unhandled property "+name); logger.error(" - Current schema is "+report.getSchema().getShortname()); } /* (non-Javadoc) * @see no.abmu.abmstatistikk.util.DynamicBeanFactory.BeanAdapter#getProperty(java.lang.String) */ public Object getProperty(String name) { if (name.startsWith("field")) { String fieldName = name.substring(5); logger.debug("Returning answer for field "+fieldName); Answer answer = reportHelper.getAnswerByFieldName(fieldName); if (answer != null) { logger.debug("Value is "+answer.getValue()); return answer; } else { logger.error("Trying to get unexisting answer for field " +fieldName); } } else if (name.equals("report")) { return report; } return null; } /** * @return */ public Class[] getFieldClasses() { return fieldClasses; } /** * @return the report associated with the schemareport. */ public Report getReport() { return report; } /** * @param errors */ public void validate(Errors errors, String schemaName) { validate(errors, schemaName, null); } /** * @param errors : Spring errors object where errors are registered. * @param schemaName : Name of the schema used from JSP * @param fieldKeys : Set of key-names to validate, normally keys in * one page */ public void validate(Errors errors, String schemaName, Set fieldKeys) { if (fieldKeys == null) { /* Validate all fields */ fieldKeys = field.keySet(); } /* Call setProperty for all fields to update values in report object */ Iterator fieldKeysIterator = fieldKeys.iterator(); while (fieldKeysIterator.hasNext()) { String key = (String) fieldKeysIterator.next(); Answer unstoredAnswer = (Answer) field.get(key); String unstoredComment = (String) comment.get(key); if (unstoredComment != null) { if (unstoredComment.equals("")) { unstoredComment = null; } logger.debug("Found comment for "+key+": "+unstoredComment); setProperty("comment"+key, unstoredComment); } if (unstoredAnswer != null) { String value = unstoredAnswer.getValue(); if (value != null && value.equals("")) { value = null; } if (unstoredAnswer.getPassedvalidation().equals(new Integer(1))){ logger.debug("Field "+key+" was marked as validated."); value = null; // Checkboxes are not returned when cleared. unstoredAnswer.setPassedvalidation(new Integer(0)); } logger.debug("Updating field "+key+" with value "+value +" has passed validation? " +unstoredAnswer.getPassedvalidation()); setProperty("field"+key, value); } else { /* Checkboxes are reset when hidden _FIELD input is used */ unstoredAnswer = (Answer) getProperty("field"+key); if (unstoredAnswer == null) { logger.error("No answer object for field "+key +" in schema "+schemaName +" This should be an unchecked checkbox."); } else { unstoredAnswer.setValue(null); field.put(key, unstoredAnswer); } } } /* Autocalculate autocalculated field with new values */ reportHelper.autoCalculate(); /* Iterate through all fields and validate updated answer for field */ fieldKeysIterator = fieldKeys.iterator(); while (fieldKeysIterator.hasNext()) { String key = (String) fieldKeysIterator.next(); Answer storedAnswer = (Answer) getProperty("field"+key); if (storedAnswer != null) { AnswerHelper answerHelper = new AnswerHelper(storedAnswer); String error = answerHelper.validate(); if (error != null) { logger.debug("Error: "+ error+" for field "+key +" "+errors.getObjectName()); errors.rejectValue("field['"+key+"']", error, "Unknown error: "+error); errors.rejectValue("field"+key, error, "Unknown error: "+error); if (error.startsWith("schema.error.change")) { errors.rejectValue("comment['"+key+"']", error, "Unknown error: "+error); errors.rejectValue("comment"+key, error, "Unknown error: "+error); } } } else { logger.error("Couldn't find stored answer for field "+key+ " in schema "+schemaName); } } /* If there were no errors, mark all answers as validated to fix * problem clearing checkboxes. */ if (!errors.hasErrors() || errors.hasErrors()) { fieldKeysIterator = fieldKeys.iterator(); while (fieldKeysIterator.hasNext()) { String key = (String) fieldKeysIterator.next(); logger.debug("Setting "+key+" as validated."); Answer validatedAnswer = (Answer) getProperty("field"+key); validatedAnswer.setPassedvalidation(new Integer(1)); } } } public void dumpAsXML(OutputStream out) { XMLEncoder e = new XMLEncoder(out); Map stringMap = new HashMap(); Schema schema = report.getSchema(); stringMap.put("schematype", schema.getShortname()); stringMap.put("valid_from", schema.getStartdate()); stringMap.put("valid_to", schema.getStopdate()); stringMap.put("organisation_id", new Long(report.getOrganisationid())); Set fields = field.keySet(); Iterator fieldIterator = fields.iterator(); while (fieldIterator.hasNext()) { String fieldName = (String) fieldIterator.next(); Answer fieldAnswer = (Answer) field.get(fieldName); stringMap.put(fieldName, fieldAnswer.getValue()); } e.writeObject(stringMap); e.close(); } /** * @return Returns the comment. */ public Map getComment() { return comment; } /** * @param comment The comment to set. */ public void setComment(Map comment) { this.comment = comment; } /** * @return Returns the virtualSchemaReport. */ public SchemaReport getVirtualSchemaReport() { return virtualSchemaReport; } /** * @param virtualSchemaReport The virtualSchemaReport to set. */ public void setVirtualSchemaReport(SchemaReport virtualSchemaReport) { this.virtualSchemaReport = virtualSchemaReport; } }
NationalLibraryOfNorway/Bibliotekstatistikk
old-and-depricated/annualstatistic/src/main/java/no/abmu/abmstatistikk/annualstatistic/service/SchemaReport.java
Java
gpl-2.0
10,238
def hamming(s,t): dist = 0 for x in range(len(s)): if s[x]!=t[x]: dist+=1 return dist
adijo/rosalind
old/hamming_distance.py
Python
gpl-2.0
100
<?php /** * Created by PhpStorm. * User: Paul * Date: 22/02/2015 * Time: 22:15 */ namespace MyCrm\Modules\LibertaVisualBuilder\Lib; class FormsXmlTools { public function testAndCreateXmlDef($module_name, $form_name) { $form_name = str_replace(".html", "", $form_name); if (!file_exists($_SERVER["DOCUMENT_ROOT"] . install_path . 'src/MyCrm/Modules/' . $module_name . '/Data/Views_xml/' . $form_name . ".xml")) { $this->createXmlDef($module_name, $form_name); } } public function createXmlDef($module_name, $form_name) { $form_name = str_replace(".html", "", $form_name); $xml = new \DOMDocument(); $xml_form = $xml->createElement("Form"); $xml_form_name = $xml->createElement("Name"); $xml_form_name->nodeValue = $form_name; $xml_form->appendChild($xml_form_name); $xml_components = $xml->createElement("Components"); $xml_form->appendChild($xml_components); $xml->appendChild($xml_form); $xml->save($_SERVER["DOCUMENT_ROOT"] . install_path . 'src/MyCrm/Modules/' . $module_name . '/Data/Views_xml/' . $form_name . ".xml"); } public function addXmlComponentDef($module_name, $form_name, $entity, $query_name, $component, $fields) { $form_name = str_replace(".html", "", $form_name); $xml = new \DOMDocument(); $xml->load($_SERVER["DOCUMENT_ROOT"] . install_path . 'src/MyCrm/Modules/' . $module_name . '/Data/Views_xml/' . $form_name . ".xml"); $components = $xml->getElementsByTagName("Components"); foreach ($components as $c) { $xml_component = $xml->createElement("Component"); /** Component name */ $xml_component_name = $xml->createElement("Name"); $xml_component_name->nodeValue = $component['name']; $xml_component->appendChild($xml_component_name); /** Component type */ $xml_component_type = $xml->createElement("Type"); $xml_component_type->nodeValue = $component['type']; $xml_component->appendChild($xml_component_type); /** Entity / Repository query binding */ $xml_component_entity = $xml->createElement("Entity"); $xml_component_entity->nodeValue = $entity; $xml_component->appendChild($xml_component_entity); /** Component query binding */ $xml_component_query_binding = $xml->createElement("QueryBinding"); $xml_component_query_binding->nodeValue = $query_name; $xml_component->appendChild($xml_component_query_binding); /** Component fields */ $xml_component_fields = $xml->createElement("Fields"); $xml_component->appendChild($xml_component_fields); foreach ($fields as $field) { $field_name = $field['field']; $field_type = $field['fieldType']; $field_entity = $field['entity']; /** Field */ $xml_component_field = $xml->createElement("Field"); $component_field = $xml->createElement("Name"); $component_field->nodeValue = $field_name; $component_type = $xml->createElement("Type"); $component_type->nodeValue = $field_type; $component_entity = $xml->createElement("Entity"); $component_entity->nodeValue = $field_entity; $xml_component_field->appendChild($component_field); $xml_component_field->appendChild($component_type); $xml_component_field->appendChild($component_entity); $xml_component_fields->appendChild($xml_component_field); } $c->appendChild($xml_component); } $xml->save($_SERVER["DOCUMENT_ROOT"] . install_path . 'src/MyCrm/Modules/' . $module_name . '/Data/Views_xml/' . $form_name . ".xml"); } public function removeXmlComponent($module_name, $form_name, $component_name) { $form_name = str_replace(".html", "", $form_name); $xml = new \DOMDocument(); $xml->load($_SERVER["DOCUMENT_ROOT"] . install_path . 'src/MyCrm/Modules/' . $module_name . '/Data/Views_xml/' . $form_name . ".xml"); $components = $xml->getElementsByTagName("Components"); foreach ($components as $c) { foreach ($c->childNodes as $cn) { foreach ($cn->childNodes as $ccn) { if ($ccn->nodeName == "Name") { if ($ccn->nodeValue == $component_name) { $c->removeChild($cn); break; } } } } } $xml->save($_SERVER["DOCUMENT_ROOT"] . install_path . 'src/MyCrm/Modules/' . $module_name . '/Data/Views_xml/' . $form_name . ".xml"); } public function createFormXmlBindings($module_name, $form_name) { /** Parse XML */ $form_name = str_replace(".html", "", $form_name); $xml = new \DOMDocument(); $xml->load($_SERVER["DOCUMENT_ROOT"] . install_path . 'src/MyCrm/Modules/' . $module_name . '/Data/Views_xml/' . $form_name . ".xml"); /** Open form file */ $page = file_get_contents($_SERVER["DOCUMENT_ROOT"] . install_path . 'src/MyCrm/Modules/' . $module_name . '/Views/' . $form_name . ".html"); /** Traitment for each components */ $components = $xml->getElementsByTagName("Components"); $_replace = true; $_type = ""; $_name = ""; foreach ($components as $c) { foreach ($c->childNodes as $cn) { if ($cn->nodeName == "Component") { foreach ($cn->childNodes as $ccn) { /** Get field html ID / Name */ if ($ccn->nodeName == "Name") { $_name = $ccn->nodeValue; } /** Replace html content by type */ if ($ccn->nodeName == "Type") { if ($ccn->nodeValue == "datatable") { $_replace = true; $_type = "datatable"; } } if ($ccn->nodeName == "Fields") { if ($_replace == true) { /** Datatable creation */ if ($_type == "datatable") { /** Process replace content by loop */ $html_dataTable = "{% for var in " . $_name . " %}"; $html_dataTable .= "<tr>"; foreach ($ccn->childNodes as $cccn) { if ($cccn->hasChildNodes()) { foreach ($cccn->childNodes as $field) { if ($field->nodeName == "Name") { /** Add fields by query xml */ $html_dataTable .= "<td>{{ var." . $field->nodeValue . " }}</td>"; } } } } $html_dataTable .= "</tr>"; $html_dataTable .= "{% endfor %}"; /** Replace content with datatable fields */ $page = str_replace("<!-- " . $_name . " -->", $html_dataTable, $page); } /** Other creations / replacements... */ } } } } } } /** Write new html file */ $file = fopen($_SERVER["DOCUMENT_ROOT"] . install_path . 'src/MyCrm/Modules/' . $module_name . '/Views/' . $form_name . ".html", "w"); fwrite($file, $page); fclose($file); } public function getFormXmlControllers($module_name, $form_name) { /** Parse XML */ $form_name = str_replace(".html", "", $form_name); $xml = new \DOMDocument(); $xml->load($_SERVER["DOCUMENT_ROOT"] . install_path . 'src/MyCrm/Modules/' . $module_name . '/Data/Views_xml/' . $form_name . ".xml"); $components = $xml->getElementsByTagName("Components"); $_name = ""; $_entity = ""; $_query_binding = ""; $tab = array(); foreach ($components as $c) { foreach ($c->childNodes as $cn) { if ($cn->nodeName == "Component") { foreach ($cn->childNodes as $ccn) { if ($ccn->nodeName == "Name") { $_name = $ccn->nodeValue; } else if ($ccn->nodeName == "Entity") { $_entity = $ccn->nodeValue; } else if ($ccn->nodeName == "QueryBinding") { $_query_binding = $ccn->nodeValue; $tab[] = array("name" => $_name, "entity" => $_entity, "QueryBinding" => $_query_binding); } } } } } return $tab; } }
paulcoiffier/Mobissime-Liberta
src/MyCrm/Modules/LibertaVisualBuilder/Lib/FormsXmlTools.php
PHP
gpl-2.0
9,685
<?php /** * @package mail_edit.php * @author John Doe <john.doe@example.com> * @since 2009-02-18 * @version 2012-10-23 */ /* 2/18/09 initial release 2/28/09 added email addr validation 7/19/10 title handling corrected 7/28/10 Added inclusion of startup.inc.php for checking of network status and setting of file name variables to support no-maps versions of scripts. 8/30/10 finished addr correction 3/15/11 changed stylesheet.php to stylesheet.php 10/23/12 Added code for messaging (SMS Gateway) */ error_reporting(E_ALL); @session_start(); require_once($_SESSION['fip']); //7/28/10 require_once './incs/messaging.inc.php'; $tick_id = ((isset($_GET['ticket_id'])) && ($_GET['ticket_id'] != "")) ? $_GET['ticket_id'] : 0; if (empty($_POST)) { $query = "SELECT `id`, `scope` FROM `$GLOBALS[mysql_prefix]ticket` WHERE `id` = {$_GET['ticket_id']} LIMIT 1"; $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename( __FILE__), __LINE__); $row = mysql_fetch_array($result); $title = substr(stripslashes($row['scope']), 0, 60); unset($result); } $title = (isset($row)) ? substr(stripslashes($row['scope']), 0, 60): $_POST['frm_title']; // 7/19/10 ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <HTML> <HEAD> <TITLE><?php print gettext('Email re');?>: <?php print $title; ?></TITLE> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"> <META HTTP-EQUIV="Expires" CONTENT="0"> <META HTTP-EQUIV="Cache-Control" CONTENT="NO-CACHE"> <META HTTP-EQUIV="Pragma" CONTENT="NO-CACHE"> <META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript"> <LINK REL="StyleSheet" HREF="stylesheet.php?version=<?php print time();?>" TYPE="text/css"/> <!-- 3/15/11 --> <SCRIPT> /** * * @returns {unresolved} */ String.prototype.trim = function () { return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1"); }; /** * * @param {type} lines * @returns {undefined} */ function reSizeScr(lines) { window.resizeTo(640,((lines * 18)+260)); // derived via trial/error (more of the latter, mostly) } /** * * @param {type} str * @returns {Boolean} */ function addrcheck(str) { var at="@"; var dot="."; var lat=str.indexOf(at); var lstr=str.length; var ldot=str.indexOf(dot); if (str.indexOf(at)==-1) {return false;} if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) {return false;} if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) {return false;} if (str.indexOf(at,(lat+1))!=-1) {return false;} if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) {return false;} if (str.indexOf(dot,(lat+2))==-1) {return false;} if (str.indexOf(" ")!=-1) {return false;} return true; } var temp; var lines; /** * * @param {type} theForm * @returns {Boolean} */ function do_val(theForm) { // 2/28/09, 10/23/12 if ((theForm.frm_use_smsg) && (theForm.frm_use_smsg == 0)) { if (theForm.frm_addrs.value == "") { var sep = ""; theForm.frm_addrs.value = theForm.frm_addrs.value + sep + theForm.frm_theothers.value; } else { var sep = ","; theForm.frm_addrs.value = theForm.frm_addrs.value + sep + theForm.frm_theothers.value; } theForm.frm_smsgaddrs.value = ""; } if ((theForm.frm_addrs.value.trim() == "") && (theForm.frm_smsgaddrs.value.trim() == "")) { alert("<?php print gettext('Addressee required');?>"); return false; } if (theForm.frm_addrs.value.trim() != "") { temp = theForm.frm_addrs.value.trim().split("|"); // explode to array var emerr = false; for (i=0; i<temp.length; i++) { // check each addr if (!(addrcheck(temp[i].trim()))) { emerr = true; } } if (emerr) { alert("<?php print gettext('Valid addressee email required');?>"); return false; } } if (theForm.frm_text.value.trim() == "") { alert("<?php print gettext('Message text required');?>"); return false; } theForm.submit(); } /** * * @param {type} message * @returns {undefined} */ function set_message(message) { // 10/23/12 var randomnumber=Math.floor(Math.random()*99999999); var tick_id = <?php print $tick_id;?>; var url = './ajax/get_replacetext.php?tick=' + tick_id + '&version=' + randomnumber + '&text=' + encodeURIComponent(message); sendRequest (url,replacetext_cb, ""); function replacetext_cb(req) { var the_text=JSON.decode(req.responseText); if (the_text[0] == "") { var replacement_text = message; } else { var replacement_text = the_text[0]; } document.mail_form.frm_text.value += replacement_text; } // end function replacetext_cb() } // end function set_message(message) <?php if (empty($_POST)) { // dump($_GET); $to_str = "ashore4@verizon.net"; // $smsgaddrs = ((isset($_GET['smsgaddrs'])) && ($_GET['smsgaddrs'] != "")) ? $_GET['smsgaddrs'] : $smsgaddrs; $smsgaddrs = ""; $text = mail_it ($_GET['addrs'], $smsgaddrs, $_GET['text'], $_GET['ticket_id'], 1, TRUE) ; // returns msg text **ONLY** // 4/24/12 // dump($text); $temp = explode("\n", $text); $finished_str = ((get_variable('call_board')==1))? "location.href = 'board.php'": "window.close();"; // 8/30/10 ?> </SCRIPT> </HEAD> <BODY onLoad = "reSizeScr(<?php print count($temp);?>);"><CENTER> <?php $use_messaging = get_variable('use_messaging'); $the_other = ((isset($_GET['other'])) && ($_GET['other'] != "")) ? $_GET['other'] : ""; ?> <H3><?php print gettext('Revise message to suit');?></H3> <FORM NAME="mail_frm" METHOD="post" ACTION = "<?php print basename( __FILE__); ?>"> <TABLE ALIGN='center' BORDER=0> <TR CLASS='even'> <TD COLSPAN=2><TEXTAREA NAME="frm_text" COLS=60 ROWS=<?php print count($temp); ?>><?php print $text ;?></TEXTAREA></TD> </TR> <TR VALIGN = 'TOP' CLASS='even'> <!-- 10/23/12 --> <TD ALIGN='right' CLASS="td_label"><?php print gettext('Standard Message');?>: </TD><TD> <!-- 10/23/12 --> <SELECT NAME='signals' onChange = 'set_message(this.options[this.selectedIndex].text);'> <!-- 11/17/10, 10/23/12 --> <OPTION VALUE=0 SELECTED><?php print gettext('Select');?></OPTION> <!-- 10/23/12 --> <?php // dump(__LINE__); $query1 = "SELECT * FROM `$GLOBALS[mysql_prefix]std_msgs` ORDER BY `id` ASC"; $result1 = mysql_query($query1) or do_error($query1, 'mysql query failed', mysql_error(),basename( __FILE__), __LINE__); while ($row1 = stripslashes_deep(mysql_fetch_assoc($result1))) { print "\t<OPTION VALUE='{$row1['id']}'>{$row1['message']}</OPTION>\n"; } ?> </SELECT> <BR /> </TD> </TR> <TR CLASS='even'> <TD><?php print gettext('Addressed to');?>: </TD> <TD><INPUT TYPE='text' NAME='frm_addrs' size='60' VALUE='<?php print $_GET['addrs'];?>'></TD> <!-- 10/23/12 --> </TR> <?php if ((get_variable('use_messaging') == 2) || (get_variable('use_messaging') == 3)) { // 10/23/12 $smsgaddrs = ((isset($_GET['smsgaddrs'])) && ($_GET['smsgaddrs'] != "")) ? $_GET['smsgaddrs'] : ""; ?> <TR CLASS='even'><TD><?php get_provider_name(get_msg_variable('smsg_provider'));?> <?php print gettext('Addresses');?>: </TD> <TD><INPUT TYPE='text' NAME='frm_smsgaddrs' size='60' VALUE='<?php print $smsgaddrs;?>' /></TD> </TR> <TR CLASS='even'><TD><?php print gettext('Use');?> <?php get_provider_name(get_msg_variable('smsg_provider'));?>?: </TD> <!-- 10/23/12 --> <TD><INPUT TYPE='checkbox' NAME='frm_use_smsg' VALUE="0" /></TD> <!-- 10/23/12 --> </TR> <INPUT TYPE="hidden" NAME = 'frm_theothers' VALUE="<?php print $the_other;?>"/> <!-- 10/23/12 --> <?php } else { ?> <INPUT TYPE="hidden" NAME = 'frm_smsgaddrs' VALUE=""/> <!-- 10/23/12 --> <INPUT TYPE='hidden' NAME = 'frm_use_smsg' VALUE = "0"/> <!-- 10/23/12 --> <INPUT TYPE="hidden" NAME = 'frm_theothers' VALUE="<?php print $the_other;?>"/> <!-- 10/23/12 --> <?php } ?> <TR CLASS='odd'> <TD COLSPAN=2 ALIGN = 'center'> <INPUT TYPE="hidden" NAME = 'ticket_id' VALUE="<?php print $_GET['ticket_id'];?>"/> <!-- 10/23/12 --> <INPUT TYPE="hidden" NAME = 'frm_title' VALUE="<?php print $row['scope'];?>"/> <INPUT TYPE="button" VALUE="<?php print gettext('OK - mail this');?>" onClick = "do_val(document.mail_frm);"/>&nbsp;&nbsp;&nbsp;&nbsp; <INPUT TYPE="button" VALUE="<?php print gettext('Reset');?>" onClick = "document.mail_frm.reset();"/>&nbsp;&nbsp;&nbsp;&nbsp; <INPUT TYPE="button" VALUE="<?php print gettext('Dont send');?>" onClick = "if (confirm('Confirm_do_not_send?')) {<?php print $finished_str;?>}"/> </TD> </TR> </TABLE> </FORM> <?php } // end if (empty($_POST)) else { $the_responders = array(); $the_emails = explode('|',$_POST['frm_addrs']); $the_sms = ((isset($_POST['frm_smsgaddrs'])) && ($_POST['frm_smsgaddrs'] != "")) ? explode(',', $_POST['frm_smsgaddrs']) : ""; $email_addresses = ($_POST['frm_addrs'] != "") ? $_POST['frm_addrs'] : ""; $smsg_addresses = ((isset($_POST['frm_use_smsg'])) && ($_POST['frm_use_smsg'] == 1) && ($_POST['frm_smsgaddrs'] != "")) ? $_POST['frm_smsgaddrs'] : ""; foreach ($the_emails as $val) { $the_responders[] = get_resp_id2($val); } if (($_POST['frm_use_smsg']) && ($_POST['frm_use_smsg'] == 1)) { foreach ($the_sms as $val2) { $the_responders[] = get_resp_id($val2); } } $the_resp_ids = array_unique($the_responders); $resps = substr(implode(',', $the_resp_ids), 0 -2); $count = do_send ($email_addresses, $smsg_addresses, "Tickets CAD", $_POST['frm_text'], $_POST['ticket_id'], $resps ); // - ($to_str, $to_smsr, $subject_str, $text_str, %ticket_id, $responder_id ) ?> </SCRIPT> </HEAD> <BODY onLoad = "setTimeout('window.close()',6000);"><CENTER> <BR /><BR /><H3><?php print gettext('Emailing dispatch notifications');?></H3><BR /><BR /> <P><?php print $count;?> <?php print gettext('Message(s) sent');?></P> <?php } // end else ?> </BODY> </HTML>
khoegenauer/tickets-cad
mail_edit.php
PHP
gpl-2.0
10,577
<?php include 'common/base.php'; // Server connection $userId = 0002; $newUser = "Nick"; $newPass = "pass"; $newEmail = "Nick@nick.com"; //$dateCreated = ""; echo $userID; // $sql = "INSERT INTO users(`userid`, `username`, `password`, `email`, `datecreated`) // VALUES ('0002', '$newUser', '$newPass', '$newEmail', '$datecreated')"; // if(mysqli_query($con, $sql)) { // echo "New User Created Successfully"; // } // else { // echo "Error: " .$sql . "<br>" . msqli_error($conn); // } include 'common/close.php'; ?>
BearAlliance/Croquet-Tracker
server/newUser.php
PHP
gpl-2.0
539
/************************************************************************************* Extended WPF Toolkit Copyright (C) 2007-2013 Nequeo Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license For more features, controls, and fast professional support, pick up the Plus Edition at http://Nequeo.com/wpf_toolkit Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids ***********************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Interop; using System.Windows.Controls; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Input; using System.Windows.Data; using System.Windows.Media; using Nequeo.Wpf.Docker.Layout; using System.Diagnostics; using System.Windows.Threading; namespace Nequeo.Wpf.Docker.Controls { public class LayoutAutoHideWindowControl : HwndHost, ILayoutControl { static LayoutAutoHideWindowControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(LayoutAutoHideWindowControl), new FrameworkPropertyMetadata(typeof(LayoutAutoHideWindowControl))); UIElement.FocusableProperty.OverrideMetadata(typeof(LayoutAutoHideWindowControl), new FrameworkPropertyMetadata(true)); Control.IsTabStopProperty.OverrideMetadata(typeof(LayoutAutoHideWindowControl), new FrameworkPropertyMetadata(true)); VisibilityProperty.OverrideMetadata(typeof(LayoutAutoHideWindowControl), new FrameworkPropertyMetadata(Visibility.Hidden)); } internal LayoutAutoHideWindowControl() { } internal void Show(LayoutAnchorControl anchor) { if (_model != null) throw new InvalidOperationException(); _anchor = anchor; _model = anchor.Model as LayoutAnchorable; _side = (anchor.Model.Parent.Parent as LayoutAnchorSide).Side; _manager = _model.Root.Manager; CreateInternalGrid(); _model.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_model_PropertyChanged); Visibility = System.Windows.Visibility.Visible; InvalidateMeasure(); UpdateWindowPos(); } internal void Hide() { if (_model == null) return; _model.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(_model_PropertyChanged); RemoveInternalGrid(); _anchor = null; _model = null; _manager = null; Visibility = System.Windows.Visibility.Hidden; } LayoutAnchorControl _anchor; LayoutAnchorable _model; public ILayoutElement Model { get { return _model; } } HwndSource _internalHwndSource = null; IntPtr parentWindowHandle; protected override System.Runtime.InteropServices.HandleRef BuildWindowCore(System.Runtime.InteropServices.HandleRef hwndParent) { parentWindowHandle = hwndParent.Handle; _internalHwndSource = new HwndSource(new HwndSourceParameters() { ParentWindow = hwndParent.Handle, WindowStyle = Win32Helper.WS_CHILD | Win32Helper.WS_VISIBLE | Win32Helper.WS_CLIPSIBLINGS | Win32Helper.WS_CLIPCHILDREN, Width = 0, Height = 0, }); _internalHost_ContentRendered = false; _internalHwndSource.ContentRendered += _internalHwndSource_ContentRendered; _internalHwndSource.RootVisual = _internalHostPresenter; AddLogicalChild(_internalHostPresenter); Win32Helper.BringWindowToTop(_internalHwndSource.Handle); return new HandleRef(this, _internalHwndSource.Handle); } private bool _internalHost_ContentRendered = false; void _internalHwndSource_ContentRendered(object sender, EventArgs e) { _internalHost_ContentRendered = true; } protected override IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == Win32Helper.WM_WINDOWPOSCHANGING) { if (_internalHost_ContentRendered) Win32Helper.SetWindowPos(_internalHwndSource.Handle, Win32Helper.HWND_TOP, 0, 0, 0, 0, Win32Helper.SetWindowPosFlags.IgnoreMove | Win32Helper.SetWindowPosFlags.IgnoreResize); } return base.WndProc(hwnd, msg, wParam, lParam, ref handled); } protected override void DestroyWindowCore(System.Runtime.InteropServices.HandleRef hwnd) { if (_internalHwndSource != null) { _internalHwndSource.ContentRendered -= _internalHwndSource_ContentRendered; _internalHwndSource.Dispose(); _internalHwndSource = null; } } public override void OnApplyTemplate() { base.OnApplyTemplate(); } ContentPresenter _internalHostPresenter = new ContentPresenter(); Grid _internalGrid = null; LayoutAnchorableControl _internalHost = null; AnchorSide _side; LayoutGridResizerControl _resizer = null; DockingManager _manager; void _model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "IsAutoHidden") { if (!_model.IsAutoHidden) { _manager.HideAutoHideWindow(_anchor); } } } void CreateInternalGrid() { _internalGrid = new Grid() { FlowDirection = System.Windows.FlowDirection.LeftToRight}; _internalGrid.SetBinding(Grid.BackgroundProperty, new Binding("Background") { Source = this }); _internalHost = new LayoutAnchorableControl() { Model = _model, Style = AnchorableStyle }; _internalHost.SetBinding(FlowDirectionProperty, new Binding("Model.Root.Manager.FlowDirection") { Source = this }); KeyboardNavigation.SetTabNavigation(_internalGrid, KeyboardNavigationMode.Cycle); _resizer = new LayoutGridResizerControl(); _resizer.DragStarted += new System.Windows.Controls.Primitives.DragStartedEventHandler(OnResizerDragStarted); _resizer.DragDelta += new System.Windows.Controls.Primitives.DragDeltaEventHandler(OnResizerDragDelta); _resizer.DragCompleted += new System.Windows.Controls.Primitives.DragCompletedEventHandler(OnResizerDragCompleted); if (_side == AnchorSide.Right) { _internalGrid.ColumnDefinitions.Add(new ColumnDefinition(){ Width = new GridLength(_manager.GridSplitterWidth)}); _internalGrid.ColumnDefinitions.Add(new ColumnDefinition(){ Width = _model.AutoHideWidth == 0.0 ? new GridLength(_model.AutoHideMinWidth) : new GridLength(_model.AutoHideWidth, GridUnitType.Pixel)}); Grid.SetColumn(_resizer, 0); Grid.SetColumn(_internalHost, 1); _resizer.Cursor = Cursors.SizeWE; HorizontalAlignment = System.Windows.HorizontalAlignment.Right; VerticalAlignment = System.Windows.VerticalAlignment.Stretch; } else if (_side == AnchorSide.Left) { _internalGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = _model.AutoHideWidth == 0.0 ? new GridLength(_model.AutoHideMinWidth) : new GridLength(_model.AutoHideWidth, GridUnitType.Pixel), }); _internalGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(_manager.GridSplitterWidth) }); Grid.SetColumn(_internalHost, 0); Grid.SetColumn(_resizer, 1); _resizer.Cursor = Cursors.SizeWE; HorizontalAlignment = System.Windows.HorizontalAlignment.Left; VerticalAlignment = System.Windows.VerticalAlignment.Stretch; } else if (_side == AnchorSide.Top) { _internalGrid.RowDefinitions.Add(new RowDefinition() { Height = _model.AutoHideHeight == 0.0 ? new GridLength(_model.AutoHideMinHeight) : new GridLength(_model.AutoHideHeight, GridUnitType.Pixel), }); _internalGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(_manager.GridSplitterHeight) }); Grid.SetRow(_internalHost, 0); Grid.SetRow(_resizer, 1); _resizer.Cursor = Cursors.SizeNS; VerticalAlignment = System.Windows.VerticalAlignment.Top; HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; } else if (_side == AnchorSide.Bottom) { _internalGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(_manager.GridSplitterHeight) }); _internalGrid.RowDefinitions.Add(new RowDefinition() { Height = _model.AutoHideHeight == 0.0 ? new GridLength(_model.AutoHideMinHeight) : new GridLength(_model.AutoHideHeight, GridUnitType.Pixel), }); Grid.SetRow(_resizer, 0); Grid.SetRow(_internalHost, 1); _resizer.Cursor = Cursors.SizeNS; VerticalAlignment = System.Windows.VerticalAlignment.Bottom; HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; } _internalGrid.Children.Add(_resizer); _internalGrid.Children.Add(_internalHost); _internalHostPresenter.Content = _internalGrid; } void RemoveInternalGrid() { _resizer.DragStarted -= new System.Windows.Controls.Primitives.DragStartedEventHandler(OnResizerDragStarted); _resizer.DragDelta -= new System.Windows.Controls.Primitives.DragDeltaEventHandler(OnResizerDragDelta); _resizer.DragCompleted -= new System.Windows.Controls.Primitives.DragCompletedEventHandler(OnResizerDragCompleted); _internalHostPresenter.Content = null; } protected override bool HasFocusWithinCore() { return false; } #region Resizer Border _resizerGhost = null; Window _resizerWindowHost = null; Vector _initialStartPoint; void ShowResizerOverlayWindow(LayoutGridResizerControl splitter) { _resizerGhost = new Border() { Background = splitter.BackgroundWhileDragging, Opacity = splitter.OpacityWhileDragging }; var areaElement = _manager.GetAutoHideAreaElement(); var modelControlActualSize = this._internalHost.TransformActualSizeToAncestor(); Point ptTopLeftScreen = areaElement.PointToScreenDPIWithoutFlowDirection(new Point()); var managerSize = areaElement.TransformActualSizeToAncestor(); Size windowSize; if (_side == AnchorSide.Right || _side == AnchorSide.Left) { windowSize = new Size( managerSize.Width - 25.0 + splitter.ActualWidth, managerSize.Height); _resizerGhost.Width = splitter.ActualWidth; _resizerGhost.Height = windowSize.Height; ptTopLeftScreen.Offset(25, 0.0); } else { windowSize = new Size( managerSize.Width, managerSize.Height - _model.AutoHideMinHeight - 25.0 + splitter.ActualHeight); _resizerGhost.Height = splitter.ActualHeight; _resizerGhost.Width = windowSize.Width; ptTopLeftScreen.Offset(0.0, 25.0); } _initialStartPoint = splitter.PointToScreenDPIWithoutFlowDirection(new Point()) - ptTopLeftScreen; if (_side == AnchorSide.Right || _side == AnchorSide.Left) { Canvas.SetLeft(_resizerGhost, _initialStartPoint.X); } else { Canvas.SetTop(_resizerGhost, _initialStartPoint.Y); } Canvas panelHostResizer = new Canvas() { HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch }; panelHostResizer.Children.Add(_resizerGhost); _resizerWindowHost = new Window() { ResizeMode = ResizeMode.NoResize, WindowStyle = System.Windows.WindowStyle.None, ShowInTaskbar = false, AllowsTransparency = true, Background = null, Width = windowSize.Width, Height = windowSize.Height, Left = ptTopLeftScreen.X, Top = ptTopLeftScreen.Y, ShowActivated = false, Owner = Window.GetWindow(this), Content = panelHostResizer }; _resizerWindowHost.Show(); } void HideResizerOverlayWindow() { if (_resizerWindowHost != null) { _resizerWindowHost.Close(); _resizerWindowHost = null; } } internal bool IsResizing { get; private set; } void OnResizerDragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) { LayoutGridResizerControl splitter = sender as LayoutGridResizerControl; var rootVisual = this.FindVisualTreeRoot() as Visual; var trToWnd = TransformToAncestor(rootVisual); Vector transformedDelta = trToWnd.Transform(new Point(e.HorizontalChange, e.VerticalChange)) - trToWnd.Transform(new Point()); double delta; if (_side == AnchorSide.Right || _side == AnchorSide.Left) delta = Canvas.GetLeft(_resizerGhost) - _initialStartPoint.X; else delta = Canvas.GetTop(_resizerGhost) - _initialStartPoint.Y; if (_side == AnchorSide.Right) { if (_model.AutoHideWidth == 0.0) _model.AutoHideWidth = _internalHost.ActualWidth - delta; else _model.AutoHideWidth -= delta; _internalGrid.ColumnDefinitions[1].Width = new GridLength(_model.AutoHideWidth, GridUnitType.Pixel); } else if (_side == AnchorSide.Left) { if (_model.AutoHideWidth == 0.0) _model.AutoHideWidth = _internalHost.ActualWidth + delta; else _model.AutoHideWidth += delta; _internalGrid.ColumnDefinitions[0].Width = new GridLength(_model.AutoHideWidth, GridUnitType.Pixel); } else if (_side == AnchorSide.Top) { if (_model.AutoHideHeight == 0.0) _model.AutoHideHeight = _internalHost.ActualHeight + delta; else _model.AutoHideHeight += delta; _internalGrid.RowDefinitions[0].Height = new GridLength(_model.AutoHideHeight, GridUnitType.Pixel); } else if (_side == AnchorSide.Bottom) { if (_model.AutoHideHeight == 0.0) _model.AutoHideHeight = _internalHost.ActualHeight - delta; else _model.AutoHideHeight -= delta; _internalGrid.RowDefinitions[1].Height = new GridLength(_model.AutoHideHeight, GridUnitType.Pixel); } HideResizerOverlayWindow(); IsResizing = false; InvalidateMeasure(); } void OnResizerDragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e) { LayoutGridResizerControl splitter = sender as LayoutGridResizerControl; var rootVisual = this.FindVisualTreeRoot() as Visual; var trToWnd = TransformToAncestor(rootVisual); Vector transformedDelta = trToWnd.Transform(new Point(e.HorizontalChange, e.VerticalChange)) - trToWnd.Transform(new Point()); if (_side == AnchorSide.Right || _side == AnchorSide.Left) { if (FrameworkElement.GetFlowDirection(_internalHost) == System.Windows.FlowDirection.RightToLeft) transformedDelta.X = -transformedDelta.X; Canvas.SetLeft(_resizerGhost, MathHelper.MinMax(_initialStartPoint.X + transformedDelta.X, 0.0, _resizerWindowHost.Width - _resizerGhost.Width)); } else { Canvas.SetTop(_resizerGhost, MathHelper.MinMax(_initialStartPoint.Y + transformedDelta.Y, 0.0, _resizerWindowHost.Height - _resizerGhost.Height)); } } void OnResizerDragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e) { var resizer = sender as LayoutGridResizerControl; ShowResizerOverlayWindow(resizer); IsResizing = true; } #endregion protected override System.Collections.IEnumerator LogicalChildren { get { if (_internalHostPresenter == null) return new UIElement[] { }.GetEnumerator(); return new UIElement[] { _internalHostPresenter }.GetEnumerator(); } } protected override Size MeasureOverride(Size constraint) { if (_internalHostPresenter == null) return base.MeasureOverride(constraint); _internalHostPresenter.Measure(constraint); //return base.MeasureOverride(constraint); return _internalHostPresenter.DesiredSize; } protected override Size ArrangeOverride(Size finalSize) { if (_internalHostPresenter == null) return base.ArrangeOverride(finalSize); _internalHostPresenter.Arrange(new Rect(finalSize)); return base.ArrangeOverride(finalSize);// new Size(_internalHostPresenter.ActualWidth, _internalHostPresenter.ActualHeight); } #region Background /// <summary> /// Background Dependency Property /// </summary> public static readonly DependencyProperty BackgroundProperty = DependencyProperty.Register("Background", typeof(Brush), typeof(LayoutAutoHideWindowControl), new FrameworkPropertyMetadata((Brush)null)); /// <summary> /// Gets or sets the Background property. This dependency property /// indicates background of the autohide childwindow. /// </summary> public Brush Background { get { return (Brush)GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } #endregion internal bool IsWin32MouseOver { get { var ptMouse = new Win32Helper.Win32Point(); if (!Win32Helper.GetCursorPos(ref ptMouse)) return false; Point location = this.PointToScreenDPI(new Point()); Rect rectWindow = this.GetScreenArea(); if (rectWindow.Contains(new Point(ptMouse.X, ptMouse.Y))) return true; var manager = Model.Root.Manager; var anchor = manager.FindVisualChildren<LayoutAnchorControl>().Where(c => c.Model == Model).FirstOrDefault(); if (anchor == null) return false; location = anchor.PointToScreenDPI(new Point()); if (anchor.IsMouseOver) return true; return false; } } #region AnchorableStyle /// <summary> /// AnchorableStyle Dependency Property /// </summary> public static readonly DependencyProperty AnchorableStyleProperty = DependencyProperty.Register("AnchorableStyle", typeof(Style), typeof(LayoutAutoHideWindowControl), new FrameworkPropertyMetadata((Style)null)); /// <summary> /// Gets or sets the AnchorableStyle property. This dependency property /// indicates the style to apply to the LayoutAnchorableControl hosted in this auto hide window. /// </summary> public Style AnchorableStyle { get { return (Style)GetValue(AnchorableStyleProperty); } set { SetValue(AnchorableStyleProperty, value); } } #endregion } }
drazenzadravec/nequeo
Source/Components/Wpf/Nequeo.Wpf.Toolkit.Docker/Nequeo.Wpf.Toolkit.Docker/Controls/LayoutAutoHideWindowControl.cs
C#
gpl-2.0
21,395
<?php /** footer.php * * @author Konstantin Obenland * @package The Bootstrap * @since 1.0.0 - 05.02.2012 */ tha_footer_before(); ?> <footer> <div id="footer" class="clearfix"> <div id="footer-wrapper"> <div class="container"> <div class="row"> <div class="footerNav"> <div class="span7"> <ul class="footerMenu clearfix"> <li><a href="#">CONTACT</a></li> <li><a href="#">CAREERS</a></li> <li><a href="#">BLOG</a></li> <li><a href="#">AGENCIES</a></li> <li><a href="#">START-UPS</a></li> </ul> </div> <div class="span4 socialMenu clearfix"> <div class="connect">Let's Connect</div> <ul class="social-icons clearfix"> <li><a href="#" title="Facebook"></a> </li> <li><a href="#" class="twitt" title="Twitter"></a> </li> <li><a href="#" class="in" title="Linkedin"></a> </li> </ul> </div> </div> </div> <div class="row contactInfo"> <div class="span6 copyright"> <div class="grid emailSign"> <input type="text" class="email" placeholder="get email updates (monthly or so)"><button type="submit" value="" class="emailInput" href="#"> </button> </div> <div> <div class="footerLogo"></div> <address> <div>World class innovation in development, design and consulting. </div> <div class="row"> <div class="span3 addressBlock"> <ul class="add addInfo"> <li>Raleigh, NC, USA</li> <li>Pune, India </li> <li>Waterloo, ON, Canada</li> </ul> </div> <div class="span3 contactBlock"> <ul class="add"> <li><span class="email"></span><a href="mailto:contact@weboniselab.com"> contact@weboniselab.com</a></li> <li><span class="phone"></span>727-210-5206  (USA & Canada)</li> <li><span class="phone"></span>+91 203-024-6161 (India)</li> </ul> </div> </div> </address> </div> </div><!-- end of .copyright --> <div class="span6 twitterBlock"> <div class="twiiterHeading"><span></span>@webonise</div> <div class="clear"></div> <div class="grid"> <div class="twitterPanel"> <div class="tweets"><div class="content_tweets"> </div></div> <script type='text/javascript'> jQuery(".content_tweets").miniTwitter({username: ['webonise'], limit: 1}); </script> </div> </div> </div> </div> </div> </div><!-- end #footer-wrapper --> </div><!-- end #footer --> <div class="powered"> <!-- <a href="--><?php //echo esc_url(__('http://themeid.com/responsive-theme/','responsive')); ?><!--" title="--><?php //esc_attr_e('Responsive Theme', 'responsive'); ?><!--">--> <!-- --><?php //printf('Responsive Theme'); ?><!--</a>--> <!-- --><?php //esc_attr_e('powered by', 'responsive'); ?><!-- <a href="--><?php //echo esc_url(__('http://wordpress.org/','responsive')); ?><!--" title="--><?php //esc_attr_e('WordPress', 'responsive'); ?><!--">--> <!-- --><?php //printf('WordPress'); ?><!--</a>--> © 2013 Webonise, Inc </div><!-- end .powered --> </footer> <?php tha_footer_after(); ?> </div><!-- #page --> </div><!-- .container --> <!-- <?php printf( __( '%d queries. %s seconds.', 'the-bootstrap' ), get_num_queries(), timer_stop(0, 3) ); ?> --> <?php wp_footer(); ?> </body> </html> <?php /* End of file footer.php */ /* Location: ./wp-content/themes/the-bootstrap/footer.php */
sagar-webonise/wordpress
wp-content/themes/the-bootstrap/footer.php
PHP
gpl-2.0
4,571
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2013 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ /*! @file * A test for callbacks around fork in jit mode. */ #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include "pin.H" #include <iostream> #include <fstream> using namespace std; INT32 Usage() { cerr << "This pin tool registers callbacks around fork().\n" "\n"; cerr << KNOB_BASE::StringKnobSummary(); cerr << endl; return -1; } pid_t parent_pid; PIN_LOCK lock; VOID BeforeFork(THREADID threadid, const CONTEXT* ctxt, VOID * arg) { PIN_GetLock(&lock, threadid+1); cerr << "TOOL: Before fork." << endl; PIN_ReleaseLock(&lock); parent_pid = PIN_GetPid(); } VOID AfterForkInParent(THREADID threadid, const CONTEXT* ctxt, VOID * arg) { PIN_GetLock(&lock, threadid+1); cerr << "TOOL: After fork in parent." << endl; PIN_ReleaseLock(&lock); if (PIN_GetPid() != parent_pid) { cerr << "PIN_GetPid() fails in parent process" << endl; exit(-1); } } VOID AfterForkInChild(THREADID threadid, const CONTEXT* ctxt, VOID * arg) { PIN_GetLock(&lock, threadid+1); cerr << "TOOL: After fork in child." << endl; PIN_ReleaseLock(&lock); if ((PIN_GetPid() == parent_pid) || (getppid() != parent_pid)) { cerr << "PIN_GetPid() fails in child process" << endl; exit(-1); } } int main(INT32 argc, CHAR **argv) { PIN_InitSymbols(); if( PIN_Init(argc,argv) ) { return Usage(); } // Initialize the pin lock PIN_InitLock(&lock); // Register a notification handler that is called when the application // forks a new process. PIN_AddForkFunction(FPOINT_BEFORE, BeforeFork, 0); PIN_AddForkFunction(FPOINT_AFTER_IN_PARENT, AfterForkInParent, 0); PIN_AddForkFunction(FPOINT_AFTER_IN_CHILD, AfterForkInChild, 0); // Never returns PIN_StartProgram(); return 0; }
cyjseagull/SHMA
zsim-nvmain/pin_kit/source/tools/ManualExamples/fork_jit_tool.cpp
C++
gpl-2.0
3,436
// // lat - AttributeEditorWidget.cs // Author: Loren Bandiera // Copyright 2006 MMG Security, Inc. // // 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 // // 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. // // using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using Gtk; using GLib; using Novell.Directory.Ldap; using Novell.Directory.Ldap.Utilclass; namespace lat { public class AttributeEditorWidget : Gtk.VBox { ScrolledWindow sw; Button applyButton; TreeView tv; ListStore store; Connection conn; string currentDN; bool displayAll; List<string> allAttrs; NameValueCollection currentAttributes; public AttributeEditorWidget() : base () { sw = new ScrolledWindow (); sw.HscrollbarPolicy = PolicyType.Automatic; sw.VscrollbarPolicy = PolicyType.Automatic; store = new ListStore (typeof (string), typeof(string)); store.SetSortColumnId (0, SortType.Ascending); tv = new TreeView (); tv.Model = store; TreeViewColumn col; col = tv.AppendColumn ("Name", new CellRendererText (), "text", 0); col.SortColumnId = 0; CellRendererText cell = new CellRendererText (); cell.Editable = true; cell.Edited += new EditedHandler (OnAttributeEdit); tv.AppendColumn ("Value", cell, "text", 1); tv.KeyPressEvent += new KeyPressEventHandler (OnKeyPress); tv.ButtonPressEvent += new ButtonPressEventHandler (OnRightClick); tv.RowActivated += new RowActivatedHandler (OnRowActivated); sw.AddWithViewport (tv); HButtonBox hb = new HButtonBox (); hb.Layout = ButtonBoxStyle.End; applyButton = new Button (); applyButton.Label = "Apply"; applyButton.Image = new Gtk.Image (Stock.Apply, IconSize.Button); applyButton.Clicked += new EventHandler (OnApplyClicked); applyButton.Sensitive = false; hb.Add (applyButton); this.PackStart (sw, true, true, 0); this.PackStart (hb, false, false, 5); this.ShowAll (); } void OnApplyClicked (object o, EventArgs args) { List<LdapModification> modList = new List<LdapModification> (); NameValueCollection newAttributes = new NameValueCollection (); foreach (object[] row in this.store) { string newValue = row[1].ToString(); if (newValue == "" || newValue == null) continue; newAttributes.Add (row[0].ToString(), newValue); } foreach (string key in newAttributes.AllKeys) { string[] newValues = newAttributes.GetValues(key); string[] oldValues = currentAttributes.GetValues (key); LdapAttribute la = new LdapAttribute (key, newValues); if (oldValues == null) { LdapModification lm = new LdapModification (LdapModification.ADD, la); modList.Add (lm); } else { foreach (string nv in newValues) { bool foundMatch = false; foreach (string ov in oldValues) if (ov == nv) foundMatch = true; if (!foundMatch) { LdapModification lm = new LdapModification (LdapModification.REPLACE, la); modList.Add (lm); } } } } foreach (string key in currentAttributes.AllKeys) { string[] newValues = newAttributes.GetValues (key); if (newValues == null) { string[] oldValues = currentAttributes.GetValues (key); LdapAttribute la = new LdapAttribute (key, oldValues); LdapModification lm = new LdapModification (LdapModification.DELETE, la); modList.Add (lm); } else { LdapAttribute la = new LdapAttribute (key, newValues); LdapModification lm = new LdapModification (LdapModification.REPLACE, la); modList.Add (lm); } } Util.ModifyEntry (conn, currentDN, modList.ToArray()); } void OnAttributeEdit (object o, EditedArgs args) { TreeIter iter; if (!store.GetIterFromString (out iter, args.Path)) return; string oldText = (string) store.GetValue (iter, 1); if (oldText == args.NewText) return; store.SetValue (iter, 1, args.NewText); applyButton.Sensitive = true; } public void Show (Connection connection, LdapEntry entry, bool showAll) { displayAll = showAll; conn = connection; currentDN = entry.DN; currentAttributes = new NameValueCollection (); // FIXME: crashes after an apply if I don't re-create the store; store = new ListStore (typeof (string), typeof(string)); store.SetSortColumnId (0, SortType.Ascending); tv.Model = store; // store.Clear (); allAttrs = new List<string> (); LdapAttribute a = entry.getAttribute ("objectClass"); for (int i = 0; i < a.StringValueArray.Length; i++) { string o = (string) a.StringValueArray[i]; store.AppendValues ("objectClass", o); currentAttributes.Add ("objectClass", o); string[] attrs = conn.Data.GetAllAttributes (o); if (attrs != null) { foreach (string at in attrs) if (!allAttrs.Contains (at)) allAttrs.Add (at); } else { Log.Debug("Could not retrieve any attribute for objectClass " + o); } } LdapAttributeSet attributeSet = entry.getAttributeSet (); // Fedora Directory Server supports an Access Control Item (ACI) // but it is not listed as "allowed attribute" for any objectClass // found in Fedora's LDAP schema. if (showAll && conn.Settings.ServerType == LdapServerType.FedoraDirectory) { LdapEntry[] acientries = conn.Data.Search( currentDN, LdapConnection.SCOPE_BASE, "objectclass=*", new string[] {"aci"} ); if (acientries.Length > 0) { LdapEntry acientry = acientries[0]; LdapAttribute aciattr = acientry.getAttribute("aci"); if (aciattr != null) if (attributeSet.Add(aciattr) == false) Log.Debug ("Could not add ACI attribute."); } } foreach (LdapAttribute attr in attributeSet) { if (allAttrs.Contains (attr.Name)) allAttrs.Remove (attr.Name); if (attr.Name.ToLower() == "objectclass") continue; try { foreach (string s in attr.StringValueArray) { store.AppendValues (attr.Name, s); currentAttributes.Add (attr.Name, s); } } catch (ArgumentOutOfRangeException e) { // FIXME: this only happens with gmcs store.AppendValues (attr.Name, ""); Log.Debug ("Show attribute arugment out of range: {0}", attr.Name); Log.Debug (e.Message); } } if (!showAll) return; foreach (string n in allAttrs) store.AppendValues (n, ""); } void InsertAttribute () { string attrName; TreeModel model; TreeIter iter; if (!tv.Selection.GetSelected (out model, out iter)) return; attrName = (string) store.GetValue (iter, 0); if (attrName == null) return; SchemaParser sp = conn.Data.GetAttributeTypeSchema (attrName); if (!sp.Single) { TreeIter newRow = store.InsertAfter (iter); store.SetValue (newRow, 0, attrName); applyButton.Sensitive = true; } else { HIGMessageDialog dialog = new HIGMessageDialog ( null, 0, Gtk.MessageType.Info, Gtk.ButtonsType.Ok, "Unable to insert value", "Multiple values not supported by this attribute"); dialog.Run (); dialog.Destroy (); } } void DeleteAttribute () { TreeModel model; TreeIter iter; if (!tv.Selection.GetSelected (out model, out iter)) return; store.Remove (ref iter); applyButton.Sensitive = true; } void OnKeyPress (object o, KeyPressEventArgs args) { switch (args.Event.Key) { case Gdk.Key.Insert: case Gdk.Key.KP_Insert: InsertAttribute (); break; case Gdk.Key.Delete: case Gdk.Key.KP_Delete: DeleteAttribute (); break; default: break; } } [ConnectBefore] void OnRightClick (object o, ButtonPressEventArgs args) { if (args.Event.Button == 3) DoPopUp (); } void RunViewerPlugin (AttributeViewPlugin avp, string attributeName) { LdapEntry le = conn.Data.GetEntry (currentDN); LdapAttribute la = le.getAttribute (attributeName); bool existing = false; if (la != null) existing = true; LdapAttribute newla = new LdapAttribute (attributeName); switch (avp.DataType) { case ViewerDataType.Binary: if (existing) avp.OnActivate (attributeName, SupportClass.ToByteArray (la.ByteValue)); else avp.OnActivate (attributeName, new byte[0]); break; case ViewerDataType.String: if (existing) avp.OnActivate (attributeName, la.StringValue); else avp.OnActivate (attributeName, ""); break; } if (avp.ByteValue != null) newla.addBase64Value (System.Convert.ToBase64String (avp.ByteValue, 0, avp.ByteValue.Length)); else if (avp.StringValue != null) newla.addValue (avp.StringValue); else return; LdapModification lm; if (existing) lm = new LdapModification (LdapModification.REPLACE, newla); else lm = new LdapModification (LdapModification.ADD, newla); List<LdapModification> modList = new List<LdapModification> (); modList.Add (lm); Util.ModifyEntry (conn, currentDN, modList.ToArray()); this.Show (conn, conn.Data.GetEntry (currentDN), displayAll); } void OnRowActivated (object o, RowActivatedArgs args) { TreePath path = args.Path; TreeIter iter; if (store.GetIter (out iter, path)) { string name = null; name = (string) store.GetValue (iter, 0); foreach (AttributeViewPlugin avp in Global.Plugins.AttributeViewPlugins) { foreach (string an in avp.AttributeNames) if (an.ToLower() == name.ToLower()) if (conn.AttributeViewers.Contains (avp.GetType().ToString())) RunViewerPlugin (avp, name); } } } void OnInsertActivate (object o, EventArgs args) { InsertAttribute (); } void OnDeleteActivate (object o, EventArgs args) { DeleteAttribute (); } public string GetAttributeName () { TreeModel model; TreeIter iter; string name; if (tv.Selection.GetSelected (out model, out iter)) { name = (string) store.GetValue (iter, 0); return name; } return null; } byte[] ReadFileBytes (string fileName) { List<byte> fileBytes = new List<byte> (); try { FileStream fs = File.OpenRead (fileName); byte[] buf = new byte[4096]; int ret = 0; do { ret = fs.Read (buf, 0, buf.Length); for (int i = 0; i < ret; i++) fileBytes.Add (buf[i]); } while (ret != 0); fs.Close (); } catch (Exception e) { Log.Debug (e); HIGMessageDialog dialog = new HIGMessageDialog ( null, 0, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, "Add binary value error", e.Message); dialog.Run (); dialog.Destroy (); } return fileBytes.ToArray(); } void OnAddBinaryValueActivate (object o, EventArgs args) { FileChooserDialog fcd = new FileChooserDialog ( Mono.Unix.Catalog.GetString ("Select file to add as binary attribute"), Gtk.Stock.Open, null, FileChooserAction.Open); fcd.AddButton (Gtk.Stock.Cancel, ResponseType.Cancel); fcd.AddButton (Gtk.Stock.Open, ResponseType.Ok); fcd.SelectMultiple = false; ResponseType response = (ResponseType) fcd.Run(); if (response == ResponseType.Ok) { byte[] fileBytes = ReadFileBytes (fcd.Filename); if (fileBytes.Length == 0) return; string attributeName = GetAttributeName (); string attributeValue = Base64.encode (SupportClass.ToSByteArray (fileBytes)); LdapEntry le = conn.Data.GetEntry (currentDN); LdapAttribute la = le.getAttribute (attributeName); bool existing = false; if (la != null) existing = true; LdapAttribute newla = new LdapAttribute (attributeName); newla.addBase64Value (attributeValue); LdapModification lm; if (existing) lm = new LdapModification (LdapModification.REPLACE, newla); else lm = new LdapModification (LdapModification.ADD, newla); List<LdapModification> modList = new List<LdapModification> (); modList.Add (lm); Util.ModifyEntry (conn, currentDN, modList.ToArray()); this.Show (conn, conn.Data.GetEntry (currentDN), displayAll); } fcd.Destroy(); } void WriteBytesToFile (string fileName, byte[] fileBytes) { try { FileStream fs = File.OpenWrite (fileName); fs.Write (fileBytes, 0, fileBytes.Length); fs.Close (); } catch (Exception e) { Log.Debug (e); HIGMessageDialog dialog = new HIGMessageDialog ( null, 0, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, "Save binary attribute error", e.Message); dialog.Run (); dialog.Destroy (); } } void OnSaveBinaryValueActivate (object o, EventArgs args) { FileChooserDialog fcd = new FileChooserDialog ( Mono.Unix.Catalog.GetString ("Save binary as"), Gtk.Stock.Save, null, FileChooserAction.Save); fcd.AddButton (Gtk.Stock.Cancel, ResponseType.Cancel); fcd.AddButton (Gtk.Stock.Save, ResponseType.Ok); fcd.SelectMultiple = false; ResponseType response = (ResponseType) fcd.Run(); if (response == ResponseType.Ok) { string attributeName = GetAttributeName (); LdapEntry le = conn.Data.GetEntry (currentDN); LdapAttribute la = le.getAttribute (attributeName); WriteBytesToFile (fcd.Filename, SupportClass.ToByteArray (la.ByteValue)); } fcd.Destroy (); } void OnAddObjectClassActivate (object o, EventArgs args) { AddObjectClassDialog dlg = new AddObjectClassDialog (conn); foreach (string s in dlg.ObjectClasses) { string[] req = conn.Data.GetRequiredAttrs (s); store.AppendValues ("objectClass", s); if (req == null) continue; foreach (string r in req) { if (allAttrs.Contains (r)) allAttrs.Remove (r); string m = currentAttributes[r]; if (m == null) { store.AppendValues (r, ""); currentAttributes.Add (r, ""); } } } } void DoPopUp() { Menu popup = new Menu(); ImageMenuItem addBinaryValueItem = new ImageMenuItem ("Add binary value..."); addBinaryValueItem.Image = new Gtk.Image (Stock.Open, IconSize.Menu); addBinaryValueItem.Activated += new EventHandler (OnAddBinaryValueActivate); addBinaryValueItem.Show (); popup.Append (addBinaryValueItem); ImageMenuItem newObjectClassItem = new ImageMenuItem ("Add object class(es)..."); newObjectClassItem.Image = new Gtk.Image (Stock.Add, IconSize.Menu); newObjectClassItem.Activated += new EventHandler (OnAddObjectClassActivate); newObjectClassItem.Show (); popup.Append (newObjectClassItem); ImageMenuItem deleteItem = new ImageMenuItem ("Delete attribute"); deleteItem.Image = new Gtk.Image (Stock.Delete, IconSize.Menu); deleteItem.Activated += new EventHandler (OnDeleteActivate); deleteItem.Show (); popup.Append (deleteItem); ImageMenuItem newItem = new ImageMenuItem ("Insert attribute"); newItem.Image = new Gtk.Image (Stock.New, IconSize.Menu); newItem.Activated += new EventHandler (OnInsertActivate); newItem.Show (); popup.Append (newItem); ImageMenuItem saveBinaryValueItem = new ImageMenuItem ("Save binary value..."); saveBinaryValueItem.Image = new Gtk.Image (Stock.Save, IconSize.Menu); saveBinaryValueItem.Activated += new EventHandler (OnSaveBinaryValueActivate); saveBinaryValueItem.Show (); popup.Append (saveBinaryValueItem); popup.Popup(null, null, null, 3, Gtk.Global.CurrentEventTime); } } }
MrJoe/lat
lat/AttributeEditorWidget.cs
C#
gpl-2.0
16,363
<?php ?> <div id="page-wrapper"> <div id="page"> <div id="header"><div class="container section header clearfix"> <?php if ($logo): ?> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo" class="logo"> <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" /> </a> <?php endif; ?> <div id="log-in-out"> <?php if(!$logged_in) print l('log in', 'user/login',array('query' => drupal_get_destination())); ?> <span style="color:#fff;"> <?php global $user; if ($logged_in) { $var = l($user->name, 'user/'.$user->uid); echo "You are logged in as " . $var . "<br>"; } ?> </span> <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Secondary menu'))); ?> </div> <?php if ($site_name || $site_slogan): ?> <div id="name-and-slogan"> <?php if ($site_name): ?> <?php if ($title): ?> <div id="site-name"><strong> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a> </strong></div> <?php else: /* Use h1 when the content title is empty */ ?> <h1 id="site-name"> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a> </h1> <?php endif; ?> <?php endif; ?> <?php if ($site_slogan): ?> <div id="site-slogan"><?php print $site_slogan; ?></div> <?php endif; ?> </div> <!-- /#name-and-slogan --> <?php endif; ?> <?php print render($page['header']); ?> </div><!-- /.section .header --> </div> <!-- /#header --> <?php if($main_menu || $page['superfish_menu'] ): ?> <div id="navigation"> <div class="container navigation section"> <?php if($page['superfish_menu']) { print render($page['superfish_menu']); } else { print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'clearfix')))); } ?> </div><!-- /.section .navigation --> </div> <!-- /#navigation --> <?php endif; ?> <div id="banner-wrap" class="slider-content <?php if(!$page['banner']) print 'empty' ?>"> <?php if ($page['banner']): ?> <div id="banner" class="clearfix"> <div class="container region"> <?php print render ($page['banner']); ?> </div> </div> <?php endif; ?> </div> <div id="main-wrapper"> <?php print $messages; ?> <?php if ($page['preface_one'] || $page['preface_two'] || $page['preface_three']): ?> <div id="preface" class="clearfix"> <div class="container preface clearfix"> <?php if ($page['preface_one']): ?> <div class="section preface-one<?php print' preface-'. $preface; ?>"> <div class="gutter"> <?php print render($page['preface_one']); ?> </div> </div> <?php endif; ?> <?php if ($page['preface_two']): ?> <div class="section preface-two<?php print' preface-'. $preface; ?>"> <div class="gutter"> <?php print render($page['preface_two']); ?> </div> </div> <?php endif; ?> <?php if ($page['preface_three']): ?> <div class="section preface-three<?php print' preface-'. $preface; ?>"> <div class="gutter"> <?php print render($page['preface_three']); ?> </div> </div> <?php endif; ?> </div> </div> <?php endif; ?> <div id="content-wrap" class="container content-wrap clearfix"> <div id="main" class="main clearfix"> <div id="content" class="blog-title column clear-fix"> <?php if ($page['sidebar_first']): ?> <div id="first-sidebar" class="column sidebar first-sidebar"> <div class="section"> <div class="gutter"> <?php print render($page['sidebar_first']); ?> </div> </div><!-- /.section --> </div><!-- /#sidebar-first --> <?php endif; ?> <div class="page-content content-column section"> <div class="gutter"> <?php if ($breadcrumb): ?> <div id="breadcrumb" class="container"><?php print $breadcrumb; ?></div> <?php endif; ?> <?php if ($page['highlighted']): ?><div id="highlighted"><?php print render($page['highlighted']); ?></div><?php endif; ?> <a id="main-content"></a> <?php print render($title_prefix); ?> <?php if ($title): ?><h1 class="title" id="page-title"><?php print $title; ?></h1><?php endif; ?> <?php print render($title_suffix); ?> <?php if ($tabs): ?><div class="tabs"><?php print render($tabs); ?></div><?php endif; ?> <?php print render($page['help']); ?> <?php if ($action_links): ?><ul class="action-links"><?php print render($action_links); ?></ul><?php endif; ?> <?php print render($page['content']); ?> <?php print $feed_icons; ?> </div> </div><!-- /.section .content .gutter --> </div> <!-- /#content --> </div><!-- /#main --> <?php if ($page['sidebar_second']): ?> <div id="second-sidebar" class="column sidebar second-sidebar"> <div class="section"> <div class="gutter"> <?php print render($page['sidebar_second']); ?> </div><!-- /.gutter --> </div><!-- /.section --> </div> <!-- /#sidebar-second --> <?php endif; ?> </div> <!-- /#main-wrapper --> </div><!-- /#content-main --> </div><!-- /#page --> <div id="footer"> <?php if ($page['bottom_one'] || $page['bottom_two'] || $page['bottom_three'] || $page['bottom_four']): ?> <div id="bottom" class="container clearfix"> <?php if ($page['bottom_one']): ?> <div class="region bottom bottom-one<?php print ' bottom-' . $bottom; ?>"> <div class="gutter"> <?php print render($page['bottom_one']); ?> </div> </div> <?php endif; ?> <?php if ($page['bottom_two']): ?> <div class="region bottom bottom-two<?php print ' bottom-' . $bottom; ?>"> <div class="gutter"> <?php print render($page['bottom_two']); ?> </div> </div> <?php endif; ?> <?php if ($page['bottom_three']): ?> <div class="region bottom bottom-three<?php print ' bottom-' . $bottom; ?>"> <div class="gutter"> <?php print render($page['bottom_three']); ?> </div> </div> <?php endif; ?> <?php if ($page['bottom_four']): ?> <div class="region bottom bottom-four<?php print ' bottom-'. $bottom; ?>"> <div class="gutter"> <?php print render($page['bottom_four']); ?> </div> </div> <?php endif; ?> </div> <?php endif; ?> <div class="container section footer"> <?php print render($page['footer']); ?> <div id="levelten"><?php print l('Drupal Theme', 'http://www.leveltendesign.com/'); ?> by LevelTen Interactive</div> </div><!-- /.section --> </div> <!-- /#footer --> </div> <!-- /#page-wrapper -->
NathanSF/drupal_filmfest
sites/all/themes/jackson/templates/page--blog.tpl.php
PHP
gpl-2.0
8,182
<?php include("includes/head.inc.php"); ?> <body> <!-- Headwrap Include --> <?php include("includes/masthead.inc.php"); ?> <div id="mainwrap"> <!-- TopNav Include --> <?php include("includes/topnav.inc.php"); ?> <div id="main"> <!-- Breadcrumb Include --> <?php include("includes/breadcrumb.inc.php"); ?> <!-- Announcement Include --> <?php include("includes/announcement.inc.php"); ?> <div id="content"> <?php // echo error message if is sent back in GET from CRUD if(isset($_SESSION['errors'])){ // move nested errors array to new array $errors = $_SESSION['errors']; } /* "Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal." */ $_SESSION['errors'] = array(); ?> <fieldset id="tableFieldset"> <legend>User Management</legend> <?php if(isset($errors['Success'])){echo "<span class=\"error\">".$errors['Success']."</span><br/>";}?> <?php if(isset($errors['Fail'])){echo "<span class=\"error\">".$errors['Fail']."</span><br/>";}?> <div id="toolbar"> <button class="show_hide">Add User</button> <button onclick="editUser()">Edit User</button> <button onclick="delUser()">Remove User</button> </div> <!-- begin devices form --> <div id="userAddDiv" class="mainformDiv"> <form id="userAdd" method="post" action="lib/crud/userprocess.php" enctype="multipart/form-data" class="myform stylizedForm stylized"> <div style="width:300px; margin-bottom:10px;"> <label for="username"><font color="red">*</font> Username: </label> <input name="username" id="username" tabindex='1'> <div class="spacer"></div> <?php // echo error message if is sent back in GET from CRUD if(isset($errors['username'])){echo "<span class=\"error\">".$errors['username']."</span>";} ?> <label for="password"><font color="red">*</font> Password:</label> <input name="password" id="password" type="password" tabindex='2'> <div class="spacer"></div> <?php // echo error message if is sent back in GET from CRUD if(isset($errors['password'])){echo "<br /><span class=\"error\">".$errors['password']."</span>";} ?> <label for="passconf"><font color="red">*</font> Password Confirm:</label> <input name="passconf" id="passconf" type="password" tabindex='3'> <div class="spacer"></div> <?php // echo error message if is sent back in GET from CRUD if(isset($errors['passconf'])){echo "<br /><span class=\"error\">".$errors['passconf']."</span>";} ?> <label for="email"><font color="red">*</font> E-mail:</label> <input name="email" id="email" size="40" tabindex='4'> <div class="spacer"></div> <?php // echo error message if is sent back in GET from CRUD if(isset($errors['email'])){echo "<br /><span class=\"error\">".$errors['email']."</span>";} ?> <label for="ulevelid"><font color="red">*</font> User Level:</label> <select name="ulevelid" id="ulevelid" tabindex='5'> <option value="1" selected>User</option> <option value="9">Admin</option> </select> <div class="spacer"></div> <input type="hidden" id="add" name="add" value="add"> <input type="hidden" id="editid" name="editid" value=""> <button id="save" tabindex='6' type="submit">Save</button> <button class="show_hide" type="button" tabindex='7'>Close</button><?php /* type="button" to remove default form submit function which when pressed can cause the form action attr to take place */ ?> <div class="spacer"></div> </div> </form> </div> <!-- End mainformDiv --> <div id="table"> <?php /* full table stored off in different script */ include("useradmin.inc.php"); ?> </div> </fieldset> </div><!-- End Content --> <div style="clear:both;"></div> </div><!-- End Main --> <!-- JS script Include --> <script type="text/JavaScript" src="js/useradmin.js"></script> <!-- Footer Include --> <?php include("includes/footer.inc.php"); ?> </div> <!-- End Mainwrap --> </body> </html>
cogini/rconfig
www/useradmin.php
PHP
gpl-2.0
4,287
// Copyright 2013 Shaun Simpson shauns2029@gmail.com package uk.co.immutablefix.wifireset; import java.net.InetAddress; import java.net.UnknownHostException; import android.os.AsyncTask; public class NetTask extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... params) { InetAddress addr = null; try { addr = InetAddress.getByName(params[0]); } catch (UnknownHostException e) { } if (addr != null) return addr.getHostAddress(); else return null; } }
shaun2029/Wifi-Reset
src/uk/co/immutablefix/wifireset/NetTask.java
Java
gpl-2.0
628
package com.cheng.zenofdesignpatterns.patterns.state.liftstate; /** * 在电梯门开启的状态下能做什么事情 */ public class OpenningState extends LiftState { // 开启当然可以关闭了,我就想测试一下电梯门开关功能 @Override public void close() { // 状态修改 super.context.setLiftState(LiftContext.closeingState); // 动作委托为CloseState来执行 super.context.getLiftState().close(); } // 打开电梯门 @Override public void open() { System.out.println("电梯门开启..."); } // 门开着电梯就想跑,这电梯,吓死你! @Override public void run() { // do nothing; } // 开门还不停止? public void stop() { // do nothing; } }
DIY-green/AndroidStudyDemo
DesignPatternStudy/src/main/java/com/cheng/zenofdesignpatterns/patterns/state/liftstate/OpenningState.java
Java
gpl-2.0
725
#include "diffusion.hpp" #include "support_classes.hpp" template <int dim> kappa_inv_class<dim, Eigen::MatrixXd> Diffusion<dim>::kappa_inv{}; template <int dim> tau_func_class<dim> Diffusion<dim>::tau_func{}; template <int dim> u_func_class<dim> Diffusion<dim>::u_func{}; template <int dim> q_func_class<dim, dealii::Tensor<1, dim> > Diffusion<dim>::q_func{}; template <int dim> divq_func_class<dim> Diffusion<dim>::divq_func{}; template <int dim> f_func_class<dim> Diffusion<dim>::f_func{}; template <int dim> dirichlet_BC_func_class<dim> Diffusion<dim>::dirichlet_bc_func{}; template <int dim> neumann_BC_func_class<dim> Diffusion<dim>::Neumann_BC_func{}; template <int dim> solver_options Diffusion<dim>::required_solver_options() { return solver_options::spd_matrix; } template <int dim> solver_type Diffusion<dim>::required_solver_type() { return solver_type::implicit_petsc_aij; } template <int dim> unsigned Diffusion<dim>::get_num_dofs_per_node() { return 1; } /*! * The move constrcutor of the derived class should call the move * constructor of the base class using std::move. Otherwise the copy * constructor will be called. */ template <int dim> Diffusion<dim>::Diffusion(Diffusion &&inp_cell) noexcept : GenericCell<dim>(std::move(inp_cell)), model(inp_cell.model) { } template <int dim> Diffusion<dim>::Diffusion(typename GenericCell<dim>::dealiiCell &inp_cell, const unsigned &id_num_, const unsigned &poly_order_, hdg_model<dim, Diffusion> *model_) : GenericCell<dim>(inp_cell, id_num_, poly_order_), model(model_) { } template <int dim> void Diffusion<dim>::assign_BCs(const bool &at_boundary, const unsigned &i_face, const dealii::Point<dim> &face_center) { /* Example 1 */ /* if (at_boundary) { if (fabs(face_center[0]) > 1. - 1.e-4) { this->BCs[i_face] = GenericCell<dim>::BC::essential; this->dof_names_on_faces[i_face].resize(1, 0); } else { this->BCs[i_face] = GenericCell<dim>::BC::essential; this->dof_names_on_faces[i_face].resize(1, 0); } } else { this->dof_names_on_faces[i_face].resize(1, 1); } */ /* End of example 1 */ /* Francois's Example 1 */ if (at_boundary && face_center[0] < 1000) { this->BCs[i_face] = GenericCell<dim>::BC::essential; this->dof_names_on_faces[i_face].resize(1, 0); } else { this->dof_names_on_faces[i_face].resize(1, 1); } /* End of example 1 */ } template <int dim> Diffusion<dim>::~Diffusion() { } template <int dim> void Diffusion<dim>::assign_initial_data() { } template <int dim> void Diffusion<dim>::calculate_matrices() { const unsigned n_faces = this->n_faces; const unsigned n_cell_basis = this->n_cell_bases; const unsigned n_face_basis = this->n_face_bases; const unsigned elem_quad_size = this->elem_quad_bundle->size(); std::vector<dealii::DerivativeForm<1, dim, dim> > d_forms = this->cell_quad_fe_vals->get_inverse_jacobians(); std::vector<dealii::Point<dim> > quad_pt_locs = this->cell_quad_fe_vals->get_quadrature_points(); std::vector<double> cell_JxW = this->cell_quad_fe_vals->get_JxW_values(); mtl::mat::compressed2D<dealii::Tensor<2, dim> > d_forms_mat( elem_quad_size, elem_quad_size, elem_quad_size); { mtl::mat::inserter<mtl::compressed2D<dealii::Tensor<2, dim> > > ins( d_forms_mat); for (unsigned int i1 = 0; i1 < elem_quad_size; ++i1) ins[i1][i1] << d_forms[i1]; } mtl::mat::dense2D<dealii::Tensor<1, dim> > grad_Ni_x( this->the_elem_basis->bases_grads_at_quads * d_forms_mat); A = eigen3mat::Zero(dim * n_cell_basis, dim * n_cell_basis); B = eigen3mat::Zero(dim * n_cell_basis, n_cell_basis); C = eigen3mat::Zero(dim * n_cell_basis, n_faces * n_face_basis); D = eigen3mat::Zero(n_cell_basis, n_cell_basis); E = eigen3mat::Zero(n_cell_basis, n_faces * n_face_basis); H = eigen3mat::Zero(n_faces * n_face_basis, n_faces * n_face_basis); H2 = eigen3mat::Zero(n_faces * n_face_basis, n_faces * n_face_basis); M = eigen3mat::Zero(n_cell_basis, n_cell_basis); eigen3mat Ni_div, NjT, Ni_vec; for (unsigned i1 = 0; i1 < this->elem_quad_bundle->size(); ++i1) { Ni_div = eigen3mat::Zero(dim * n_cell_basis, 1); NjT = this->the_elem_basis->get_func_vals_at_iquad(i1); Ni_vec = eigen3mat::Zero(dim * n_cell_basis, dim); for (unsigned i_dim = 0; i_dim < dim; ++i_dim) Ni_vec.block(n_cell_basis * i_dim, i_dim, n_cell_basis, 1) = NjT.transpose(); for (unsigned i_poly = 0; i_poly < n_cell_basis; ++i_poly) { dealii::Tensor<1, dim> N_grads_X = grad_Ni_x[i_poly][i1]; for (unsigned i_dim = 0; i_dim < dim; ++i_dim) Ni_div(n_cell_basis * i_dim + i_poly, 0) = N_grads_X[i_dim]; } eigen3mat kappa_inv_ = kappa_inv.value(quad_pt_locs[i1], quad_pt_locs[i1]); A += cell_JxW[i1] * Ni_vec * kappa_inv_ * Ni_vec.transpose(); M += cell_JxW[i1] * NjT.transpose() * NjT; B += cell_JxW[i1] * Ni_div * NjT; } eigen3mat normal(dim, 1); std::vector<dealii::Point<dim - 1> > Face_Q_Points = this->face_quad_bundle->get_points(); for (unsigned i_face = 0; i_face < n_faces; ++i_face) { this->reinit_face_fe_vals(i_face); eigen3mat C_on_face = eigen3mat::Zero(dim * n_cell_basis, n_face_basis); eigen3mat E_on_face = eigen3mat::Zero(n_cell_basis, n_face_basis); eigen3mat H_on_face = eigen3mat::Zero(n_face_basis, n_face_basis); eigen3mat H2_on_face = eigen3mat::Zero(n_face_basis, n_face_basis); std::vector<dealii::Point<dim> > projected_face_Q_points( this->face_quad_bundle->size()); dealii::QProjector<dim>::project_to_face( *(this->face_quad_bundle), i_face, projected_face_Q_points); std::vector<dealii::Point<dim> > normals = this->face_quad_fe_vals->get_normal_vectors(); std::vector<double> Face_JxW = this->face_quad_fe_vals->get_JxW_values(); std::vector<dealii::Point<2> > quads_loc = this->face_quad_fe_vals->get_quadrature_points(); eigen3mat NjT_Face = eigen3mat::Zero(1, n_face_basis); eigen3mat Nj_vec; eigen3mat Nj = eigen3mat::Zero(n_cell_basis, 1); for (unsigned i_Q_face = 0; i_Q_face < this->face_quad_bundle->size(); ++i_Q_face) { Nj_vec = eigen3mat::Zero(dim * n_cell_basis, dim); std::vector<double> N_valus = this->the_elem_basis->value(projected_face_Q_points[i_Q_face]); const std::vector<double> &half_range_face_basis = this->the_face_basis->value(Face_Q_Points[i_Q_face], this->half_range_flag[i_face]); for (unsigned i_polyface = 0; i_polyface < n_face_basis; ++i_polyface) NjT_Face(0, i_polyface) = half_range_face_basis[i_polyface]; for (unsigned i_poly = 0; i_poly < n_cell_basis; ++i_poly) { Nj(i_poly, 0) = N_valus[i_poly]; for (unsigned i_dim = 0; i_dim < dim; ++i_dim) Nj_vec(i_dim * n_cell_basis + i_poly, i_dim) = N_valus[i_poly]; } for (unsigned i_dim = 0; i_dim < dim; ++i_dim) normal(i_dim, 0) = normals[i_Q_face](i_dim); double tau_ = tau_func.value(quads_loc[i_Q_face], normals[i_Q_face]); C_on_face += Face_JxW[i_Q_face] * Nj_vec * normal * NjT_Face; D += Face_JxW[i_Q_face] * tau_ * Nj * Nj.transpose(); E_on_face += Face_JxW[i_Q_face] * tau_ * Nj * NjT_Face; H_on_face += Face_JxW[i_Q_face] * tau_ * NjT_Face.transpose() * NjT_Face; H2_on_face += Face_JxW[i_Q_face] * NjT_Face.transpose() * NjT_Face; } H.block(i_face * n_face_basis, i_face * n_face_basis, n_face_basis, n_face_basis) = H_on_face; H2.block(i_face * n_face_basis, i_face * n_face_basis, n_face_basis, n_face_basis) = H2_on_face; C.block(0, i_face * n_face_basis, dim * n_cell_basis, n_face_basis) = C_on_face; E.block(0, i_face * n_face_basis, n_cell_basis, n_face_basis) = E_on_face; } } template <int dim> void Diffusion<dim>::calculate_postprocess_matrices() { const unsigned n_cell_basis = this->n_cell_bases; const unsigned elem_quad_size = this->elem_quad_bundle->size(); const unsigned n_cell_basis1 = pow(this->poly_order + 2, dim); std::vector<dealii::DerivativeForm<1, dim, dim> > d_forms = this->cell_quad_fe_vals->get_inverse_jacobians(); std::vector<dealii::Point<dim> > quad_pt_locs = this->cell_quad_fe_vals->get_quadrature_points(); std::vector<double> cell_JxW = this->cell_quad_fe_vals->get_JxW_values(); mtl::mat::compressed2D<dealii::Tensor<2, dim> > d_forms_mat( elem_quad_size, elem_quad_size, elem_quad_size); { mtl::mat::inserter<mtl::compressed2D<dealii::Tensor<2, dim> > > ins( d_forms_mat); for (unsigned int i1 = 0; i1 < elem_quad_size; ++i1) ins[i1][i1] << d_forms[i1]; } mtl::mat::dense2D<dealii::Tensor<1, dim> > grad_Ni_x( model->manager->postprocess_cell_basis.bases_grads_at_quads * d_forms_mat); DM_star = eigen3mat::Zero(n_cell_basis1, n_cell_basis1); DB2 = eigen3mat::Zero(n_cell_basis1, dim * n_cell_basis); Eigen::MatrixXd Ni_grad, Ni_vecT; for (unsigned i_quad = 0; i_quad < elem_quad_size; ++i_quad) { Ni_grad = Eigen::MatrixXd::Zero(n_cell_basis1, dim); Ni_vecT = Eigen::MatrixXd::Zero(dim, dim * n_cell_basis); for (unsigned i_poly = 0; i_poly < n_cell_basis1; ++i_poly) { dealii::Tensor<1, dim> grad_Ni_at_iquad = grad_Ni_x[i_poly][i_quad]; for (unsigned i_dim = 0; i_dim < dim; ++i_dim) Ni_grad(i_poly, i_dim) = grad_Ni_at_iquad[i_dim]; } for (unsigned i_dim = 0; i_dim < dim; ++i_dim) Ni_vecT.block(i_dim, i_dim * n_cell_basis, 1, n_cell_basis) = this->the_elem_basis->get_func_vals_at_iquad(i_quad); DM_star += cell_JxW[i_quad] * Ni_grad * Ni_grad.transpose(); Eigen::MatrixXd kappa_inv_ = kappa_inv.value(quad_pt_locs[i_quad], quad_pt_locs[i_quad]); DB2 += cell_JxW[i_quad] * Ni_grad * kappa_inv_ * Ni_vecT; } } template <int dim> void Diffusion<dim>::assemble_globals(const solver_update_keys &keys_) { unsigned n_polys = this->n_cell_bases; unsigned n_polyfaces = this->n_face_bases; const std::vector<double> &Q_Weights = this->elem_quad_bundle->get_weights(); const std::vector<double> &Face_Q_Weights = this->face_quad_bundle->get_weights(); this->reinit_cell_fe_vals(); calculate_matrices(); Eigen::FullPivLU<eigen3mat> lu_of_A(A); eigen3mat Ainv = lu_of_A.inverse(); eigen3mat BT_Ainv = B.transpose() * Ainv; Eigen::FullPivLU<eigen3mat> lu_of_BT_Ainv_B_plus_D(BT_Ainv * B + D); std::vector<int> row_nums(this->n_faces * this->n_face_bases, -1); std::vector<int> col_nums(this->n_faces * this->n_face_bases, -1); std::vector<double> cell_mat; for (unsigned i_face = 0; i_face < this->n_faces; ++i_face) for (unsigned i_polyface = 0; i_polyface < this->n_face_bases; ++i_polyface) { unsigned i_num = i_face * this->n_face_bases + i_polyface; int global_dof_number; if (this->dofs_ID_in_all_ranks[i_face].size() > 0) { global_dof_number = this->dofs_ID_in_all_ranks[i_face][0] * this->n_face_bases + i_polyface; row_nums[i_num] = global_dof_number; col_nums[i_num] = global_dof_number; } } eigen3mat f_vec = eigen3mat::Zero(n_polys, 1); for (unsigned i_face = 0; i_face < this->n_faces && keys_; ++i_face) { for (unsigned i_polyface = 0; i_polyface < n_polyfaces; ++i_polyface) { eigen3mat uhat_vec = eigen3mat::Zero(this->n_faces * n_polyfaces, 1); uhat_vec(i_face * n_polyfaces + i_polyface, 0) = 1.0; eigen3mat u_vec = lu_of_BT_Ainv_B_plus_D.solve( M * f_vec + BT_Ainv * C * uhat_vec + E * uhat_vec); eigen3mat q_vec = lu_of_A.solve(B * u_vec - C * uhat_vec); eigen3mat jth_col = -1 * (C.transpose() * q_vec + E.transpose() * u_vec - H * uhat_vec); cell_mat.insert( cell_mat.end(), jth_col.data(), jth_col.data() + jth_col.size()); } } if (keys_ & update_mat) model->solver->push_to_global_mat(row_nums, col_nums, cell_mat, ADD_VALUES); if (keys_ & update_rhs) { eigen3mat gD_vec(this->n_face_bases, 1); eigen3mat gN_vec = eigen3mat::Zero(n_polyfaces * this->n_faces, 1); eigen3mat uhat_vec = eigen3mat::Zero(n_polyfaces * this->n_faces, 1); for (unsigned i_face = 0; i_face < this->n_faces; ++i_face) { if (this->BCs[i_face] == GenericCell<dim>::essential) { this->reinit_face_fe_vals(i_face); if (this->half_range_flag[i_face] == 0) { mtl::vec::dense_vector<double> gD_mtl; this->project_essential_BC_to_face( dirichlet_bc_func, *(this->the_face_basis), Face_Q_Weights, gD_mtl); for (unsigned i_dof = 0; i_dof < this->n_face_bases; ++i_dof) gD_vec(i_dof, 0) = gD_mtl[i_dof]; } else std::cout << "There is something wrong dude!\n"; uhat_vec.block(i_face * n_polyfaces, 0, n_polyfaces, 1) = gD_vec; } if (this->BCs[i_face] == GenericCell<dim>::flux_bc) { this->reinit_face_fe_vals(i_face); eigen3mat gN_vec_face(n_polyfaces, 1); if (this->half_range_flag[i_face] == 0) { mtl::vec::dense_vector<double> gN_mtl; this->project_flux_BC_to_face( Neumann_BC_func, *(this->the_face_basis), Face_Q_Weights, gN_mtl); for (unsigned i_dof = 0; i_dof < this->n_face_bases; ++i_dof) gN_vec_face(i_dof, 0) = gN_mtl[i_dof]; gN_vec.block(i_face * n_polyfaces, 0, n_polyfaces, 1) = gN_vec_face; } } } eigen3mat f_vec(this->n_cell_bases, 1); mtl::vec::dense_vector<double> f_mtl; this->project_to_elem_basis( f_func, *(this->the_elem_basis), Q_Weights, f_mtl); for (unsigned i_poly = 0; i_poly < this->n_cell_bases; ++i_poly) f_vec(i_poly, 0) = f_mtl[i_poly]; std::vector<double> rhs_col; eigen3mat u_vec = lu_of_BT_Ainv_B_plus_D.solve( M * f_vec + BT_Ainv * C * uhat_vec + E * uhat_vec); eigen3mat q_vec = lu_of_A.solve(B * u_vec - C * uhat_vec); eigen3mat jth_col = 1 * (C.transpose() * q_vec + E.transpose() * u_vec - H * uhat_vec) - H2 * gN_vec; rhs_col.assign(jth_col.data(), jth_col.data() + jth_col.rows()); /* Now, we assemble the calculated column. */ model->solver->push_to_rhs_vec(row_nums, rhs_col, ADD_VALUES); } if (keys_ & update_sol) { std::vector<double> exact_uhat_vec; eigen3mat face_exact_uhat_vec(this->n_face_bases, 1); for (unsigned i_face = 0; i_face < this->n_faces; ++i_face) { this->reinit_face_fe_vals(i_face); mtl::vec::dense_vector<double> face_exact_uhat_mtl; this->project_essential_BC_to_face(dirichlet_bc_func, *(this->the_face_basis), Face_Q_Weights, face_exact_uhat_mtl); for (unsigned i_dof = 0; i_dof < this->n_face_bases; ++i_dof) face_exact_uhat_vec(i_dof, 0) = face_exact_uhat_mtl[i_dof]; exact_uhat_vec.insert(exact_uhat_vec.end(), face_exact_uhat_vec.data(), face_exact_uhat_vec.data() + face_exact_uhat_vec.rows()); /* Now, we assemble the exact solution. */ model->solver->push_to_exact_sol(row_nums, exact_uhat_vec, INSERT_VALUES); } } wreck_it_Ralph(A); wreck_it_Ralph(B); wreck_it_Ralph(C); wreck_it_Ralph(D); wreck_it_Ralph(E); wreck_it_Ralph(H); wreck_it_Ralph(H2); wreck_it_Ralph(M); } template <int dim> template <typename T> double Diffusion<dim>::compute_internal_dofs( const double *const local_uhat_vec, eigen3mat &u_vec, eigen3mat &q_vec, const poly_space_basis<T, dim> &output_basis) { unsigned n_polys = this->n_cell_bases; unsigned n_polyfaces = this->n_face_bases; const std::vector<double> &Q_Weights = this->elem_quad_bundle->get_weights(); const std::vector<double> &Face_Q_Weights = this->face_quad_bundle->get_weights(); /* Now we attach the fe_values to the current object. */ this->reinit_cell_fe_vals(); calculate_matrices(); Eigen::FullPivLU<eigen3mat> lu_of_A(A); eigen3mat Ainv = lu_of_A.inverse(); eigen3mat BT_Ainv = B.transpose() * Ainv; Eigen::FullPivLU<eigen3mat> lu_of_BT_Ainv_B_plus_D(BT_Ainv * B + D); eigen3mat exact_f_vec(this->n_cell_bases, 1); mtl::vec::dense_vector<double> exact_f_mtl; this->project_to_elem_basis( f_func, *(this->the_elem_basis), Q_Weights, exact_f_mtl); for (unsigned i_poly = 0; i_poly < this->n_cell_bases; ++i_poly) exact_f_vec(i_poly, 0) = exact_f_mtl[i_poly]; eigen3mat solved_uhat_vec = eigen3mat::Zero(n_polyfaces * this->n_faces, 1); for (unsigned i_face = 0; i_face < this->n_faces; ++i_face) { if (this->dofs_ID_in_this_rank[i_face].size() == 0) { eigen3mat face_uhat_vec(this->n_face_bases, 1); this->reinit_face_fe_vals(i_face); mtl::vec::dense_vector<double> face_uhat_mtl; this->project_essential_BC_to_face(dirichlet_bc_func, *(this->the_face_basis), Face_Q_Weights, face_uhat_mtl); for (unsigned i_dof = 0; i_dof < this->n_face_bases; ++i_dof) face_uhat_vec(i_dof, 0) = face_uhat_mtl[i_dof]; solved_uhat_vec.block(i_face * n_polyfaces, 0, n_polyfaces, 1) = face_uhat_vec; } else { for (unsigned i_polyface = 0; i_polyface < n_polyfaces; ++i_polyface) { int global_dof_number = this->dofs_ID_in_this_rank[i_face][0] * n_polyfaces + i_polyface; solved_uhat_vec(i_face * n_polyfaces + i_polyface, 0) = local_uhat_vec[global_dof_number]; } } } u_vec = lu_of_BT_Ainv_B_plus_D.solve( M * exact_f_vec + BT_Ainv * C * solved_uhat_vec + E * solved_uhat_vec); q_vec = B * u_vec - C * solved_uhat_vec; q_vec = lu_of_A.solve(q_vec); /* * Here, we use a postprocessing technique to obtain a higher order * approximation to u. */ calculate_postprocess_matrices(); eigen3mat RHS_vec_of_ustar = -DB2 * q_vec; DM_star(0, 0) = 1; RHS_vec_of_ustar(0, 0) = u_vec(0); ustar = DM_star.ldlt().solve(RHS_vec_of_ustar); eigen3mat nodal_u = output_basis.get_dof_vals_at_quads(u_vec); eigen3mat nodal_q(dim * n_polys, 1); for (unsigned i_dim = 0; i_dim < dim; ++i_dim) { nodal_q.block(i_dim * n_polys, 0, n_polys, 1) = output_basis.get_dof_vals_at_quads( q_vec.block(i_dim * n_polys, 0, n_polys, 1)); } unsigned n_local_dofs = nodal_u.rows(); /* Now we calculate the refinement critera */ unsigned i_cell = this->id_num; for (unsigned i_local_dofs = 0; i_local_dofs < n_local_dofs; ++i_local_dofs) { double temp_val = 0; for (unsigned i_dim = 0; i_dim < dim; ++i_dim) { temp_val += std::pow(nodal_q(i_dim * n_local_dofs + i_local_dofs, 0), 2); } this->refn_local_nodal->assemble(i_cell * n_local_dofs + i_local_dofs, sqrt(temp_val)); } for (unsigned i_local_unknown = 0; i_local_unknown < n_local_dofs; ++i_local_unknown) { { unsigned idx1 = (i_cell * n_local_dofs) * (dim + 1) + i_local_unknown; this->cell_local_nodal->assemble(idx1, nodal_u(i_local_unknown, 0)); } for (unsigned i_dim = 0; i_dim < dim; ++i_dim) { unsigned idx1 = (i_cell * n_local_dofs) * (dim + 1) + (i_dim + 1) * n_local_dofs + i_local_unknown; this->cell_local_nodal->assemble( idx1, nodal_q(i_dim * n_local_dofs + i_local_unknown, 0)); } } wreck_it_Ralph(A); wreck_it_Ralph(B); wreck_it_Ralph(C); wreck_it_Ralph(D); wreck_it_Ralph(E); wreck_it_Ralph(H); wreck_it_Ralph(H2); wreck_it_Ralph(M); wreck_it_Ralph(DM_star); wreck_it_Ralph(DB2); return 0.; } template <int dim> void Diffusion<dim>::internal_vars_errors(const eigen3mat &u_vec, const eigen3mat &q_vec, double &u_error, double &q_error) { double error_q3 = this->get_error_in_cell(q_func, q_vec); double error_u3 = this->get_error_in_cell(u_func, u_vec); error_u3 = this->get_postprocessed_error_in_cell(u_func, ustar); u_error += error_u3; q_error += error_q3; } template <int dim> void Diffusion<dim>::ready_for_next_iteration() { } template <int dim> void Diffusion<dim>::ready_for_next_time_step() { } template <int dim> double Diffusion<dim>::get_postprocessed_error_in_cell( const TimeFunction<dim, double> &func, const Eigen::MatrixXd &input_vector, const double &time) { double error = 0; const std::vector<dealii::Point<dim> > &points_loc = this->cell_quad_fe_vals->get_quadrature_points(); const std::vector<double> &JxWs = this->cell_quad_fe_vals->get_JxW_values(); assert(points_loc.size() == JxWs.size()); assert(input_vector.rows() == model->manager->postprocess_cell_basis.n_polys); Eigen::MatrixXd values_at_Nodes = model->manager->postprocess_cell_basis.get_dof_vals_at_quads(input_vector); for (unsigned i_point = 0; i_point < JxWs.size(); ++i_point) { error += (func.value(points_loc[i_point], points_loc[i_point], time) - values_at_Nodes(i_point, 0)) * (func.value(points_loc[i_point], points_loc[i_point], time) - values_at_Nodes(i_point, 0)) * JxWs[i_point]; } return error; }
samiiali/nargil
elements/diffusion.cpp
C++
gpl-2.0
21,756
#include "ampi_base.h" #include <sstream> #include <ostream> #include "ampi.h" #include "mpi.h" /** * @brief AMPI_base::AMPI_base Initilize the class */ AMPI_base::AMPI_base(){ rParam=false; valid=true; } /** * @brief AMPI_base::AMPI_typeName This function is to be used by AMPI for * transmitting, receiving, and handling type names. It serves as a unique * identify for the class, and is required to be rewriten for inherited classes * @return The name of the class */ char* AMPI_base::AMPI_typeName(){ return "AMPI_base"; } /** * @brief AMPI_base::AMPI_locked this optional function is called when the class * has been transmitted and it will be modified by another machine. */ void AMPI_base::AMPI_locked() { return; } /** * @brief AMPI_base::AMPI_unlocked this optional function is called when the * class has been returned from a remote function call. */ void AMPI_base::AMPI_unlocked() { return; } /** * @brief AMPI_base::AMPI_send This is called by AMPI to send data from * the class to new copy on another machine. This can be left alone if using * AMPI_base::AMPI_input, however it is left virtual so advaced users may use * this function and MPI_Send to send the data more efficietly * @param dest The destination to be sent to * @param tag The MPI tag to send with * @param comm the MPI communicant * @return */ int AMPI_base::AMPI_send(int dest, int tag, MPI_Comm comm){ char *buf; int size; buf = AMPI_output(&size); MPI_Send(&size,1,MPI_INT,dest,AMPI::AMPI_TAG_SIZE, comm); MPI_Send(buf,size,MPI_CHAR,dest,tag,comm); return 0; } /** * @brief AMPI_base::AMPI_recv This is called by AMPI to receive new data from * another class on another machine. this can be left alone if using * AMPI_base::AMPI_input, however it is left virtual so advanced users my use * this function and MPI_Recv to recive the data more efficently * @param source The source of the data * @param tag The MPI tag that to receive from * @param comm The MPI communicant * @param status Pointer to an external status variable * @return */ int AMPI_base::AMPI_recv(int source, int tag, MPI_Comm comm, MPI_Status *status){ int size; MPI_Recv(&size,1,MPI_INT,source,AMPI::AMPI_TAG_SIZE,comm,status); char *buf = new char[size]; MPI_Recv(buf,size,MPI_CHAR,source,tag,comm,status); AMPI_input(buf,size); return 0; } /** * @brief AMPI_base::AMPI_input This function is called by the default * AMPI_base::AMPI_recv function to convert the character array received into * the inherited class's data format. Rewriting this function in the inherited * class is required unless using AMPI_base::AMPI_recv, however it should be * nearly identical to a function to read the class froma file. * @param buf The character array to read from * @param size the size of the array */ void AMPI_base::AMPI_input(char *buf, int size){ return; } /** * @brief AMPI_base::AMPI_output This function is called by the default * AMPI_base::AMPI_send function to convert the inherted class's data format to * a character array. Rewirting this function in the inherited class is * required unless using AMPI_base::AMPI_recv, however it should be nearly * identicle to a function to write the class to a file. * @param size pointer to and integer to store the size of the character array * @return the character array */ char* AMPI_base::AMPI_output(int *size){ return "NULL"; } /** * @brief AMPI_base::AMPI_returnParameter setting rP to true indecates to AMPI * that the class will be modified during a remote call and need to be sent back * @param rP * @return */ bool AMPI_base::AMPI_returnParameter(bool rP){ rParam=rP; return AMPI_returnParameter(); } /** * @brief AMPI_base::AMPI_returnParameter this indecates weather or not the * class will be returned after a remote call * @return true if the class will be returned */ bool AMPI_base::AMPI_returnParameter(){ return rParam; } void AMPI_base::Validate(){ valid=false; AMPI_locked(); } void AMPI_base::deValidate(){ valid=true; AMPI_unlocked(); } /** * @brief AMPI_base::AMPI_debug this function is used for debuging AMPI * it is not need for applications. */ void AMPI_base::AMPI_debug(){ std::cerr << AMPI_typeName() << ": " << rParam << valid << "\n"; }
PJMack/AMPI
ampi_base.cpp
C++
gpl-2.0
4,404
<?php /** * Template Name: samarbeidspartnere * * A custom page template for the room page * * * @package WordPress * @subpackage kvarteret * @since Kvarteret 1.0 */ get_header(); ?> <?php get_sidebar(); ?> <div id="content" role="main"> <h1 class="entry-title"><?php the_title(); ?></h1> <div class="entry-content"> <!-- This loops through all the children of the samarbeidspartnere page. --> <?php query_posts(array('post_parent' => 15, 'order' => 'ASC', 'order_by' => 'menu_order', 'post_type' => 'page', 'post_status' => 'published', 'posts_per_page' => -1)); while (have_posts()) { the_post(); ?> <div class="samarbeids_container"> <a id="<?php the_ID() ?>"></a> <h2><?php the_title(); ?></h2> <?php the_post_thumbnail('samarbeids-logo'); ?> <?php the_content(); ?> </div> <?php } ?> <!-- #content --> </div> </div><!-- #content --> <?php get_footer(); ?>
Amunds/kvarteret_theme
samarbeidspartnere.php
PHP
gpl-2.0
969
""" Windows Process Control winprocess.run launches a child process and returns the exit code. Optionally, it can: redirect stdin, stdout & stderr to files run the command as another user limit the process's running time control the process window (location, size, window state, desktop) Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32 extensions. This code is free for any purpose, with no warranty of any kind. -- John B. Dell'Aquila <jbd@alum.mit.edu> """ import win32api, win32process, win32security import win32event, win32con, msvcrt, win32gui def logonUser(loginString): """ Login as specified user and return handle. loginString: 'Domain\nUser\nPassword'; for local login use . or empty string as domain e.g. '.\nadministrator\nsecret_password' """ domain, user, passwd = loginString.split('\n') return win32security.LogonUser( user, domain, passwd, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT ) class Process: """ A Windows process. """ def __init__(self, cmd, login=None, hStdin=None, hStdout=None, hStderr=None, show=1, xy=None, xySize=None, desktop=None): """ Create a Windows process. cmd: command to run login: run as user 'Domain\nUser\nPassword' hStdin, hStdout, hStderr: handles for process I/O; default is caller's stdin, stdout & stderr show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...) xy: window offset (x, y) of upper left corner in pixels xySize: window size (width, height) in pixels desktop: lpDesktop - name of desktop e.g. 'winsta0\\default' None = inherit current desktop '' = create new desktop if necessary User calling login requires additional privileges: Act as part of the operating system [not needed on Windows XP] Increase quotas Replace a process level token Login string must EITHER be an administrator's account (ordinary user can't access current desktop - see Microsoft Q165194) OR use desktop='' to run another desktop invisibly (may be very slow to startup & finalize). """ si = win32process.STARTUPINFO() si.dwFlags = (win32con.STARTF_USESTDHANDLES ^ win32con.STARTF_USESHOWWINDOW) if hStdin is None: si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) else: si.hStdInput = hStdin if hStdout is None: si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE) else: si.hStdOutput = hStdout if hStderr is None: si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE) else: si.hStdError = hStderr si.wShowWindow = show if xy is not None: si.dwX, si.dwY = xy si.dwFlags ^= win32con.STARTF_USEPOSITION if xySize is not None: si.dwXSize, si.dwYSize = xySize si.dwFlags ^= win32con.STARTF_USESIZE if desktop is not None: si.lpDesktop = desktop procArgs = (None, # appName cmd, # commandLine None, # processAttributes None, # threadAttributes 1, # bInheritHandles win32process.CREATE_NEW_CONSOLE, # dwCreationFlags None, # newEnvironment None, # currentDirectory si) # startupinfo if login is not None: hUser = logonUser(login) win32security.ImpersonateLoggedOnUser(hUser) procHandles = win32process.CreateProcessAsUser(hUser, *procArgs) win32security.RevertToSelf() else: procHandles = win32process.CreateProcess(*procArgs) self.hProcess, self.hThread, self.PId, self.TId = procHandles def wait(self, mSec=None): """ Wait for process to finish or for specified number of milliseconds to elapse. """ if mSec is None: mSec = win32event.INFINITE return win32event.WaitForSingleObject(self.hProcess, mSec) def kill(self, gracePeriod=5000): """ Kill process. Try for an orderly shutdown via WM_CLOSE. If still running after gracePeriod (5 sec. default), terminate. """ win32gui.EnumWindows(self.__close__, 0) if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0: win32process.TerminateProcess(self.hProcess, 0) win32api.Sleep(100) # wait for resources to be released def __close__(self, hwnd, dummy): """ EnumWindows callback - sends WM_CLOSE to any window owned by this process. """ TId, PId = win32process.GetWindowThreadProcessId(hwnd) if PId == self.PId: win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) def exitCode(self): """ Return process exit code. """ return win32process.GetExitCodeProcess(self.hProcess) def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw): """ Run cmd as a child process and return exit code. mSec: terminate cmd after specified number of milliseconds stdin, stdout, stderr: file objects for child I/O (use hStdin etc. to attach handles instead of files); default is caller's stdin, stdout & stderr; kw: see Process.__init__ for more keyword options """ if stdin is not None: kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno()) if stdout is not None: kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno()) if stderr is not None: kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno()) child = Process(cmd, **kw) if child.wait(mSec) != win32event.WAIT_OBJECT_0: child.kill() raise WindowsError, 'process timeout exceeded' return child.exitCode() if __name__ == '__main__': # Pipe commands to a shell and display the output in notepad print 'Testing winprocess.py...' import tempfile timeoutSeconds = 15 cmdString = """\ REM Test of winprocess.py piping commands to a shell.\r REM This window will close in %d seconds.\r vol\r net user\r _this_is_a_test_of_stderr_\r """ % timeoutSeconds cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile() cmd.write(cmdString) cmd.seek(0) print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd, stdout=out, stderr=out) cmd.close() print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name, show=win32con.SW_MAXIMIZE, mSec=timeoutSeconds*1000) out.close()
alexei-matveev/ccp1gui
jobmanager/winprocess.py
Python
gpl-2.0
7,039
<?php defined('_JEXEC') or die('Direct Access to this location is not allowed.'); echo $this->loadTemplate('header'); ?> <div class="sectiontableheader"> <?php echo (!$this->category->cid) ? JText::_('JGS_COMMON_NEW_CATEGORY') : JText::_('JGS_EDITCATEGORY_MODIFY_CATEGORY'); ?> </div> <form action="<?php echo JRoute::_('index.php?task=savecategory'); ?>" method="post" name="usercatForm"> <div class="jg_editpicture"> <div class="jg_uprow"> <div class="jg_uptext"> <?php echo JText::_('JGS_COMMON_TITLE'); ?> </div> <input class="inputbox" type="text" name="name" size="25" value="<?php echo $this->category->name; ?>" /> </div> <div class="jg_uprow"> <div class="jg_uptext"> <?php echo JText::_('JGS_COMMON_ALIAS'); ?> </div> <input class="inputbox" type="text" name="alias" size="25" value="<?php echo $this->category->alias; ?>" /> </div> <div class="jg_uprow"> <div class="jg_uptext"> <?php echo JText::_('JGS_COMMON_PARENT_CATEGORY'); ?> </div> <?php echo $this->lists['catgs']; ?> </div> <div class="jg_uprow"> <div class="jg_uptext"> <?php echo JText::_('JGS_COMMON_DESCRIPTION'); ?> </div> <textarea name="description" rows="5" cols="40" class="inputbox"><?php echo htmlspecialchars($this->category->description, ENT_QUOTES, 'UTF-8'); ?></textarea> </div> <?php if($this->lists['access']): ?> <div class="jg_uprow"> <div class="jg_uptext"> <?php echo JText::_('JGS_EDITCATEGORY_ACCESS'); ?> </div> <?php echo $this->lists['access'];?> </div> <?php endif; ?> <div class="jg_uprow"> <div class="jg_uptext"> <?php echo JText::_('JGS_COMMON_PUBLISHED'); ?> </div> <?php echo $this->lists['published']; ?> </div> <div class="jg_uprow"> <div class="jg_uptext"> <?php echo JText::_('JGS_EDITCATEGORY_ORDERING'); ?> </div> <?php echo $this->lists['ordering'];?> </div> <?php if($this->category->cid): ?> <div class="jg_uprow"> <div class="jg_uptext"> <?php echo JText::_('JGS_EDITCATEGORY_THUMBNAIL'); ?> </div> <?php echo $this->lists['thumbs']; ?> </div> <div class="jg_uprow"> <div class="jg_uptext"> <?php echo JText::_('JGS_COMMON_THUMBNAIL_PREVIEW'); ?> </div> <img src="<?php echo $this->category->catimage_src; ?>" name="imagelib" border="1" alt="<?php echo JText::_('JGS_COMMON_THUMBNAIL_PREVIEW'); ?>" /> </div> <?php endif; ?> <div class="jg_txtrow"> <input type="button" name="button" value="<?php echo JText::_('JGS_COMMON_SAVE'); ?>" onclick = "javascript:submit_button();" class="button" /> <input type="button" name="button" value="<?php echo JText::_('JGS_COMMON_CANCEL'); ?>" onclick = "javascript:location.href='<?php echo JRoute::_('index.php?view=usercategories', false); ?>';" class="button" /> <input type="hidden" name="cid" value="<?php echo $this->category->cid; ?>"> </div> </div> </form> <?php echo $this->loadTemplate('footer');
jahama/cbhondarribia.com
components/com_joomgallery/views/editcategory/tmpl/default.php
PHP
gpl-2.0
3,121
<div class="resultadosdebusqueda"> <h2>Ups! por ahora no tenemos viajes de ese tipo</h2> <p>Intenta buscar fechas similares, o diferentes destinos para poder llegar hacia donde necesitas.</p> </div>
ludwind/boletos_debus01
wp-content/plugins/profi-search-filter/templates/template-1-noresult.php
PHP
gpl-2.0
199
package de.metas.inoutcandidate.modelvalidator; /* * #%L * de.metas.swat.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import org.adempiere.ad.modelvalidator.annotations.ModelChange; import org.adempiere.ad.modelvalidator.annotations.Validator; import org.compiere.model.I_M_InOutLine; import org.compiere.model.ModelValidator; @Validator(I_M_InOutLine.class) public class M_InOutLine_Shipment { @ModelChange( timings = { ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE, ModelValidator.TYPE_AFTER_NEW }, ifColumnsChanged = I_M_InOutLine.COLUMNNAME_MovementQty) public void onMovementQtyChange(final I_M_InOutLine inOutLine) { // All code from here was moved to de.metas.handlingunits.model.validator.M_InOutLine.onMovementQtyChange(I_M_InOutLine) // because we need to be aware if this is about HUs or not.... // TODO: implement a generic approach is applies the algorithm without actually going through HUs stuff } }
klst-com/metasfresh
de.metas.swat/de.metas.swat.base/src/main/java/de/metas/inoutcandidate/modelvalidator/M_InOutLine_Shipment.java
Java
gpl-2.0
1,640
<?php /* * This file is part of SeAT * * Copyright (C) 2015 to 2022 Leon Jacobs * * 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. */ namespace Seat\Eveapi\Jobs\Corporation; use Seat\Eveapi\Jobs\AbstractAuthCorporationJob; use Seat\Eveapi\Models\Corporation\CorporationFacility; /** * Class Facilities. * * @package Seat\Eveapi\Jobs\Corporation */ class Facilities extends AbstractAuthCorporationJob { /** * @var string */ protected $method = 'get'; /** * @var string */ protected $endpoint = '/corporations/{corporation_id}/facilities/'; /** * @var int */ protected $version = 'v2'; /** * @var string */ protected $scope = 'esi-corporations.read_facilities.v1'; /** * @var array */ protected $roles = ['Factory_Manager']; /** * @var array */ protected $tags = ['corporation', 'industry']; /** * Execute the job. * * @return void * * @throws \Throwable */ public function handle() { $facilities = $this->retrieve([ 'corporation_id' => $this->getCorporationId(), ]); if ($facilities->isCachedLoad() && CorporationFacility::where('corporation_id', $this->getCorporationId())->count() > 0) return; collect($facilities)->each(function ($facility) { CorporationFacility::firstOrNew([ 'corporation_id' => $this->getCorporationId(), 'facility_id' => $facility->facility_id, ])->fill([ 'type_id' => $facility->type_id, 'system_id' => $facility->system_id, ])->save(); }); CorporationFacility::where('corporation_id', $this->getCorporationId()) ->whereNotIn('facility_id', collect($facilities)->pluck('facility_id')->all()) ->delete(); } }
eveseat/eveapi
src/Jobs/Corporation/Facilities.php
PHP
gpl-2.0
2,589
/* * The Fascinator - Portal * Copyright (C) 2008-2011 University of Southern Queensland * * 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. */ package com.googlecode.fascinator.portal.services; import com.googlecode.fascinator.portal.Portal; import java.io.File; import java.util.List; import java.util.Map; import java.util.Set; public interface PortalManager { public static final String DEFAULT_PORTAL_NAME = "default"; public static final String DEFAULT_SKIN = "default"; public static final String DEFAULT_DISPLAY = "default"; public static final String DEFAULT_PORTAL_HOME = "portal"; public static final String DEFAULT_PORTAL_HOME_DEV = "src/main/config/portal"; public Map<String, Portal> getPortals(); public Portal getDefault(); public File getHomeDir(); public Portal get(String name); public boolean exists(String name); public void add(Portal portal); public void remove(String name); public void save(Portal portal); public void reharvest(String objectId); public void reharvest(Set<String> objectIds); public String getDefaultPortal(); public String getDefaultDisplay(); public List<String> getSkinPriority(); }
the-fascinator/fascinator-portal
src/main/java/com/googlecode/fascinator/portal/services/PortalManager.java
Java
gpl-2.0
1,896
<?php function showSearchEngine() { global $srv, $stgs; $output = "<?xml version=\"1.0\"?>"; $output .= "<OpenSearchDescription xmlns=\"http://a9.com/-/spec/opensearch/1.1/\">"; $output .= "<ShortName>".$stgs->getConf('sitename')."&#8217;s Search</ShortName>"; $output .= "<Description>"; $output .= $stgs->getConf('sitename')."&#8217;s Search Engine"; $output .= "</Description>"; $output .= "<Image width=\"16\" height=\"16\">".$srv->getPath("media/phaneticon.png")."</Image>"; $output .= "<Url type=\"text/html\" method=\"get\" template=\"".$srv->buildUrl("?search={searchTerms}", True)."\"/>"; $output .= "<Url type=\"application/x-suggestions+json\" method=\"GET\" template=\"".$srv->buildUrl("?search={searchTerms}", True)."\"/>"; $output .= "</OpenSearchDescription>"; echo $output; } function checkIfSearch() { global $srv; //if ( isset($_POST["searchPosts"]) ) $_GET['search'] = $_POST["searchQuery"]; if ( isset($_GET["search"])) { $searchArray = parseSearch($_GET["search"]); foreach ($searchArray as $type => $query) { if ($query{0} == " ") $query = substr($query, 1); switch($type) { case "title": $queryWhere .= " AND p.title like '%".fixApostrofe($query)."%'"; break; case "date": $queryWhere .= " AND p.date like '%".fixApostrofe($query)."%'"; break; case "author": $queryWhere .= " AND a.nickname like '%".fixApostrofe($query)."%'"; break; default: $queryWhere .= " AND p.text like '%".fixApostrofe($query)."%'"; break; } } } elseif (isset($_POST['advanceSearch'])) { if ($_POST['titleSearch']) $queryWhere .= " AND p.title like '%".fixApostrofe($_POST['titleSearch'])."%'"; elseif ($_POST['dateSearch']) $queryWhere .= " AND p.date like '%".fixApostrofe($_POST['dateSearch'])."%'"; elseif ($_POST['authorSearch']) $queryWhere .= " AND a.nickname like '%".fixApostrofe($_POST['authorSearch'])."%'"; elseif ($_POST['contentSearch']) $queryWhere .= " AND p.text like '%".fixApostrofe($_POST['contentSearch'])."%'"; } if(isset($queryWhere)) : return $queryWhere; endif; }
FlaPer87/phanet
modules/search/main.inc.php
PHP
gpl-2.0
2,117
namespace HazTech.ZUtil.Zip { using HazTech.ZUtil; using HazTech.ZUtil.Zlib; using Microsoft.CSharp; using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), Guid("ebc25cf6-9120-4283-b972-0e5520d00005")] public class ZipFile : IEnumerable<ZipEntry>, IEnumerable, IDisposable { private bool _addOperationCanceled; private Encoding _alternateEncoding; private ZipOption _alternateEncodingUsage; private int _BufferSize; private bool _CaseSensitiveRetrieval; private string _Comment; private HazTech.ZUtil.Zip.CompressionMethod _compressionMethod; private bool _contentsChanged; private static Encoding _defaultEncoding = Encoding.GetEncoding("IBM437"); private uint _diskNumberWithCd; private bool _disposed; private bool _emitNtfsTimes; private bool _emitUnixTimes; private EncryptionAlgorithm _Encryption; private Dictionary<string, ZipEntry> _entries; private bool _extractOperationCanceled; private bool _fileAlreadyExists; private bool _hasBeenSaved; internal bool _inExtractAll; private bool _JustSaved; private long _lengthOfReadStream; private long _locEndOfCDS; private int _maxBufferPairs; private int _maxOutputSegmentSize; private string _name; private uint _numberOfSegmentsForMostRecentSave; private uint _OffsetOfCentralDirectory; private long _OffsetOfCentralDirectory64; private bool? _OutputUsesZip64; private long _ParallelDeflateThreshold; internal string _Password; private string _readName; private Stream _readstream; private bool _ReadStreamIsOurs; private bool _saveOperationCanceled; private bool _SavingSfx; private TextWriter _StatusMessageTextWriter; private CompressionStrategy _Strategy; private string _TempFileFolder; private string _temporaryFileName; private ushort _versionMadeBy; private ushort _versionNeededToExtract; private Stream _writestream; internal Zip64Option _zip64; private List<ZipEntry> _zipEntriesAsList; private HazTech.ZUtil.Zip.ZipErrorAction _zipErrorAction; public static readonly int BufferSizeDefault = 0x8000; private object LOCK; internal ParallelDeflateOutputStream ParallelDeflater; private static ExtractorSettings[] SettingsList; public event EventHandler<AddProgressEventArgs> AddProgress; public event EventHandler<ExtractProgressEventArgs> ExtractProgress; public event EventHandler<ReadProgressEventArgs> ReadProgress; public event EventHandler<SaveProgressEventArgs> SaveProgress; public event EventHandler<ZipErrorEventArgs> ZipError; static ZipFile() { ExtractorSettings[] settingsArray = new ExtractorSettings[2]; ExtractorSettings settings = new ExtractorSettings { Flavor = SelfExtractorFlavor.WinFormsApplication, ReferencedAssemblies = new List<string> { "System.dll", "System.Windows.Forms.dll", "System.Drawing.dll" }, CopyThroughResources = new List<string> { "HazTech.ZUtil.Zip.WinFormsSelfExtractorStub.resources", "HazTech.ZUtil.Zip.Forms.PasswordDialog.resources", "HazTech.ZUtil.Zip.Forms.ZipContentsDialog.resources" }, ResourcesToCompile = new List<string> { "WinFormsSelfExtractorStub.cs", "WinFormsSelfExtractorStub.Designer.cs", "PasswordDialog.cs", "PasswordDialog.Designer.cs", "ZipContentsDialog.cs", "ZipContentsDialog.Designer.cs", "FolderBrowserDialogEx.cs" } }; settingsArray[0] = settings; ExtractorSettings settings2 = new ExtractorSettings { Flavor = SelfExtractorFlavor.ConsoleApplication, ReferencedAssemblies = new List<string> { "System.dll" }, CopyThroughResources = null, ResourcesToCompile = new List<string> { "CommandLineSelfExtractorStub.cs" } }; settingsArray[1] = settings2; SettingsList = settingsArray; } public ZipFile() { this._emitNtfsTimes = true; this._Strategy = CompressionStrategy.Default; this._compressionMethod = HazTech.ZUtil.Zip.CompressionMethod.Deflate; this._ReadStreamIsOurs = true; this.LOCK = new object(); this._locEndOfCDS = -1L; this._alternateEncoding = Encoding.GetEncoding("IBM437"); this._alternateEncodingUsage = ZipOption.Default; this._BufferSize = BufferSizeDefault; this._maxBufferPairs = 0x10; this._zip64 = Zip64Option.Default; this._lengthOfReadStream = -99L; this._InitInstance(null, null); } public ZipFile(string fileName) { this._emitNtfsTimes = true; this._Strategy = CompressionStrategy.Default; this._compressionMethod = HazTech.ZUtil.Zip.CompressionMethod.Deflate; this._ReadStreamIsOurs = true; this.LOCK = new object(); this._locEndOfCDS = -1L; this._alternateEncoding = Encoding.GetEncoding("IBM437"); this._alternateEncodingUsage = ZipOption.Default; this._BufferSize = BufferSizeDefault; this._maxBufferPairs = 0x10; this._zip64 = Zip64Option.Default; this._lengthOfReadStream = -99L; try { this._InitInstance(fileName, null); } catch (Exception exception) { throw new ZipException(string.Format("Could not read {0} as a zip file", fileName), exception); } } public ZipFile(Encoding encoding) { this._emitNtfsTimes = true; this._Strategy = CompressionStrategy.Default; this._compressionMethod = HazTech.ZUtil.Zip.CompressionMethod.Deflate; this._ReadStreamIsOurs = true; this.LOCK = new object(); this._locEndOfCDS = -1L; this._alternateEncoding = Encoding.GetEncoding("IBM437"); this._alternateEncodingUsage = ZipOption.Default; this._BufferSize = BufferSizeDefault; this._maxBufferPairs = 0x10; this._zip64 = Zip64Option.Default; this._lengthOfReadStream = -99L; this.AlternateEncoding = encoding; this.AlternateEncodingUsage = ZipOption.Always; this._InitInstance(null, null); } public ZipFile(string fileName, TextWriter statusMessageWriter) { this._emitNtfsTimes = true; this._Strategy = CompressionStrategy.Default; this._compressionMethod = HazTech.ZUtil.Zip.CompressionMethod.Deflate; this._ReadStreamIsOurs = true; this.LOCK = new object(); this._locEndOfCDS = -1L; this._alternateEncoding = Encoding.GetEncoding("IBM437"); this._alternateEncodingUsage = ZipOption.Default; this._BufferSize = BufferSizeDefault; this._maxBufferPairs = 0x10; this._zip64 = Zip64Option.Default; this._lengthOfReadStream = -99L; try { this._InitInstance(fileName, statusMessageWriter); } catch (Exception exception) { throw new ZipException(string.Format("{0} is not a valid zip file", fileName), exception); } } public ZipFile(string fileName, Encoding encoding) { this._emitNtfsTimes = true; this._Strategy = CompressionStrategy.Default; this._compressionMethod = HazTech.ZUtil.Zip.CompressionMethod.Deflate; this._ReadStreamIsOurs = true; this.LOCK = new object(); this._locEndOfCDS = -1L; this._alternateEncoding = Encoding.GetEncoding("IBM437"); this._alternateEncodingUsage = ZipOption.Default; this._BufferSize = BufferSizeDefault; this._maxBufferPairs = 0x10; this._zip64 = Zip64Option.Default; this._lengthOfReadStream = -99L; try { this.AlternateEncoding = encoding; this.AlternateEncodingUsage = ZipOption.Always; this._InitInstance(fileName, null); } catch (Exception exception) { throw new ZipException(string.Format("{0} is not a valid zip file", fileName), exception); } } public ZipFile(string fileName, TextWriter statusMessageWriter, Encoding encoding) { this._emitNtfsTimes = true; this._Strategy = CompressionStrategy.Default; this._compressionMethod = HazTech.ZUtil.Zip.CompressionMethod.Deflate; this._ReadStreamIsOurs = true; this.LOCK = new object(); this._locEndOfCDS = -1L; this._alternateEncoding = Encoding.GetEncoding("IBM437"); this._alternateEncodingUsage = ZipOption.Default; this._BufferSize = BufferSizeDefault; this._maxBufferPairs = 0x10; this._zip64 = Zip64Option.Default; this._lengthOfReadStream = -99L; try { this.AlternateEncoding = encoding; this.AlternateEncodingUsage = ZipOption.Always; this._InitInstance(fileName, statusMessageWriter); } catch (Exception exception) { throw new ZipException(string.Format("{0} is not a valid zip file", fileName), exception); } } private void _AddOrUpdateSelectedFiles(string selectionCriteria, string directoryOnDisk, string directoryPathInArchive, bool recurseDirectories, bool wantUpdate) { if ((directoryOnDisk == null) && Directory.Exists(selectionCriteria)) { directoryOnDisk = selectionCriteria; selectionCriteria = "*.*"; } else if (string.IsNullOrEmpty(directoryOnDisk)) { directoryOnDisk = "."; } while (directoryOnDisk.EndsWith(@"\")) { directoryOnDisk = directoryOnDisk.Substring(0, directoryOnDisk.Length - 1); } if (this.Verbose) { this.StatusMessageTextWriter.WriteLine("adding selection '{0}' from dir '{1}'...", selectionCriteria, directoryOnDisk); } ReadOnlyCollection<string> onlys = new FileSelector(selectionCriteria, this.AddDirectoryWillTraverseReparsePoints).SelectFiles(directoryOnDisk, recurseDirectories); if (this.Verbose) { this.StatusMessageTextWriter.WriteLine("found {0} files...", onlys.Count); } this.OnAddStarted(); AddOrUpdateAction action = wantUpdate ? AddOrUpdateAction.AddOrUpdate : AddOrUpdateAction.AddOnly; foreach (string str in onlys) { string str2 = (directoryPathInArchive == null) ? null : ReplaceLeadingDirectory(Path.GetDirectoryName(str), directoryOnDisk, directoryPathInArchive); if (File.Exists(str)) { if (wantUpdate) { this.UpdateFile(str, str2); } else { this.AddFile(str, str2); } } else { this.AddOrUpdateDirectoryImpl(str, str2, action, false, 0); } } this.OnAddCompleted(); } private void _initEntriesDictionary() { StringComparer comparer = this.CaseSensitiveRetrieval ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; this._entries = (this._entries == null) ? new Dictionary<string, ZipEntry>(comparer) : new Dictionary<string, ZipEntry>(this._entries, comparer); } private void _InitInstance(string zipFileName, TextWriter statusMessageWriter) { this._name = zipFileName; this._StatusMessageTextWriter = statusMessageWriter; this._contentsChanged = true; this.AddDirectoryWillTraverseReparsePoints = true; this.CompressionLevel = HazTech.ZUtil.Zlib.CompressionLevel.Default; this.ParallelDeflateThreshold = 0x80000L; this._initEntriesDictionary(); if (File.Exists(this._name)) { if (this.FullScan) { ReadIntoInstance_Orig(this); } else { ReadIntoInstance(this); } this._fileAlreadyExists = true; } } private ZipEntry _InternalAddEntry(ZipEntry ze) { ze._container = new ZipContainer(this); ze.CompressionMethod = this.CompressionMethod; ze.CompressionLevel = this.CompressionLevel; ze.ExtractExistingFile = this.ExtractExistingFile; ze.ZipErrorAction = this.ZipErrorAction; ze.SetCompression = this.SetCompression; ze.AlternateEncoding = this.AlternateEncoding; ze.AlternateEncodingUsage = this.AlternateEncodingUsage; ze.Password = this._Password; ze.Encryption = this.Encryption; ze.EmitTimesInWindowsFormatWhenSaving = this._emitNtfsTimes; ze.EmitTimesInUnixFormatWhenSaving = this._emitUnixTimes; this.InternalAddEntry(ze.FileName, ze); this.AfterAddEntry(ze); return ze; } private void _InternalExtractAll(string path, bool overrideExtractExistingProperty) { bool verbose = this.Verbose; this._inExtractAll = true; try { this.OnExtractAllStarted(path); int current = 0; foreach (ZipEntry entry in this._entries.Values) { if (verbose) { this.StatusMessageTextWriter.WriteLine("\n{1,-22} {2,-8} {3,4} {4,-8} {0}", new object[] { "Name", "Modified", "Size", "Ratio", "Packed" }); this.StatusMessageTextWriter.WriteLine(new string('-', 0x48)); verbose = false; } if (this.Verbose) { this.StatusMessageTextWriter.WriteLine("{1,-22} {2,-8} {3,4:F0}% {4,-8} {0}", new object[] { entry.FileName, entry.LastModified.ToString("yyyy-MM-dd HH:mm:ss"), entry.UncompressedSize, entry.CompressionRatio, entry.CompressedSize }); if (!string.IsNullOrEmpty(entry.Comment)) { this.StatusMessageTextWriter.WriteLine(" Comment: {0}", entry.Comment); } } entry.Password = this._Password; this.OnExtractEntry(current, true, entry, path); if (overrideExtractExistingProperty) { entry.ExtractExistingFile = this.ExtractExistingFile; } entry.Extract(path); current++; this.OnExtractEntry(current, false, entry, path); if (this._extractOperationCanceled) { break; } } if (!this._extractOperationCanceled) { foreach (ZipEntry entry in this._entries.Values) { if (entry.IsDirectory || entry.FileName.EndsWith("/")) { string fileOrDirectory = entry.FileName.StartsWith("/") ? Path.Combine(path, entry.FileName.Substring(1)) : Path.Combine(path, entry.FileName); entry._SetTimes(fileOrDirectory, false); } } this.OnExtractAllCompleted(path); } } finally { this._inExtractAll = false; } } private void _SaveSfxStub(string exeToGenerate, SelfExtractorSaveOptions options) { string str = null; string path = null; string str3 = null; string dir = null; try { if (File.Exists(exeToGenerate) && this.Verbose) { this.StatusMessageTextWriter.WriteLine("The existing file ({0}) will be overwritten.", exeToGenerate); } if (!exeToGenerate.EndsWith(".exe") && this.Verbose) { this.StatusMessageTextWriter.WriteLine("Warning: The generated self-extracting file will not have an .exe extension."); } dir = this.TempFileFolder ?? Path.GetDirectoryName(exeToGenerate); path = GenerateTempPathname(dir, "exe"); Assembly assembly = typeof(ZipFile).Assembly; using (CSharpCodeProvider provider = new CSharpCodeProvider()) { ExtractorSettings settings = null; foreach (ExtractorSettings settings2 in SettingsList) { if (settings2.Flavor == options.Flavor) { settings = settings2; break; } } if (settings == null) { throw new BadStateException(string.Format("While saving a Self-Extracting Zip, Cannot find that flavor ({0})?", options.Flavor)); } CompilerParameters parameters = new CompilerParameters(); parameters.ReferencedAssemblies.Add(assembly.Location); if (settings.ReferencedAssemblies != null) { foreach (string str5 in settings.ReferencedAssemblies) { parameters.ReferencedAssemblies.Add(str5); } } parameters.GenerateInMemory = false; parameters.GenerateExecutable = true; parameters.IncludeDebugInformation = false; parameters.CompilerOptions = ""; Assembly executingAssembly = Assembly.GetExecutingAssembly(); StringBuilder builder = new StringBuilder(); string str6 = GenerateTempPathname(dir, "cs"); using (ZipFile file = Read(executingAssembly.GetManifestResourceStream("HazTech.ZUtil.Zip.Resources.ZippedResources.zip"))) { str3 = GenerateTempPathname(dir, "tmp"); if (string.IsNullOrEmpty(options.IconFile)) { Directory.CreateDirectory(str3); ZipEntry entry = file["zippedFile.ico"]; if ((entry.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { entry.Attributes ^= FileAttributes.ReadOnly; } entry.Extract(str3); str = Path.Combine(str3, "zippedFile.ico"); parameters.CompilerOptions = parameters.CompilerOptions + string.Format("/win32icon:\"{0}\"", str); } else { parameters.CompilerOptions = parameters.CompilerOptions + string.Format("/win32icon:\"{0}\"", options.IconFile); } parameters.OutputAssembly = path; if (options.Flavor == SelfExtractorFlavor.WinFormsApplication) { parameters.CompilerOptions = parameters.CompilerOptions + " /target:winexe"; } if (!string.IsNullOrEmpty(options.AdditionalCompilerSwitches)) { parameters.CompilerOptions = parameters.CompilerOptions + " " + options.AdditionalCompilerSwitches; } if (string.IsNullOrEmpty(parameters.CompilerOptions)) { parameters.CompilerOptions = null; } if ((settings.CopyThroughResources != null) && (settings.CopyThroughResources.Count != 0)) { if (!Directory.Exists(str3)) { Directory.CreateDirectory(str3); } foreach (string str7 in settings.CopyThroughResources) { string filename = Path.Combine(str3, str7); ExtractResourceToFile(executingAssembly, str7, filename); parameters.EmbeddedResources.Add(filename); } } parameters.EmbeddedResources.Add(assembly.Location); builder.Append("// " + Path.GetFileName(str6) + "\n").Append("// --------------------------------------------\n//\n").Append("// This SFX source file was generated by DotNetZip ").Append(LibraryVersion.ToString()).Append("\n// at ").Append(DateTime.Now.ToString("yyyy MMMM dd HH:mm:ss")).Append("\n//\n// --------------------------------------------\n\n\n"); if (!string.IsNullOrEmpty(options.Description)) { builder.Append("[assembly: System.Reflection.AssemblyTitle(\"" + options.Description.Replace("\"", "") + "\")]\n"); } else { builder.Append("[assembly: System.Reflection.AssemblyTitle(\"DotNetZip SFX Archive\")]\n"); } if (!string.IsNullOrEmpty(options.ProductVersion)) { builder.Append("[assembly: System.Reflection.AssemblyInformationalVersion(\"" + options.ProductVersion.Replace("\"", "") + "\")]\n"); } string str9 = string.IsNullOrEmpty(options.Copyright) ? "Extractor: Copyright \x00a9 Dino Chiesa 2008-2011" : options.Copyright.Replace("\"", ""); if (!string.IsNullOrEmpty(options.ProductName)) { builder.Append("[assembly: System.Reflection.AssemblyProduct(\"").Append(options.ProductName.Replace("\"", "")).Append("\")]\n"); } else { builder.Append("[assembly: System.Reflection.AssemblyProduct(\"DotNetZip\")]\n"); } builder.Append("[assembly: System.Reflection.AssemblyCopyright(\"" + str9 + "\")]\n").Append(string.Format("[assembly: System.Reflection.AssemblyVersion(\"{0}\")]\n", LibraryVersion.ToString())); if (options.FileVersion != null) { builder.Append(string.Format("[assembly: System.Reflection.AssemblyFileVersion(\"{0}\")]\n", options.FileVersion.ToString())); } builder.Append("\n\n\n"); string defaultExtractDirectory = options.DefaultExtractDirectory; if (defaultExtractDirectory != null) { defaultExtractDirectory = defaultExtractDirectory.Replace("\"", "").Replace(@"\", @"\\"); } string postExtractCommandLine = options.PostExtractCommandLine; if (postExtractCommandLine != null) { postExtractCommandLine = postExtractCommandLine.Replace(@"\", @"\\").Replace("\"", "\\\""); } foreach (string str12 in settings.ResourcesToCompile) { using (Stream stream = file[str12].OpenReader()) { if (stream == null) { throw new ZipException(string.Format("missing resource '{0}'", str12)); } using (StreamReader reader = new StreamReader(stream)) { while (reader.Peek() >= 0) { string str13 = reader.ReadLine(); if (defaultExtractDirectory != null) { str13 = str13.Replace("@@EXTRACTLOCATION", defaultExtractDirectory); } str13 = str13.Replace("@@REMOVE_AFTER_EXECUTE", options.RemoveUnpackedFilesAfterExecute.ToString()).Replace("@@QUIET", options.Quiet.ToString()); if (!string.IsNullOrEmpty(options.SfxExeWindowTitle)) { str13 = str13.Replace("@@SFX_EXE_WINDOW_TITLE", options.SfxExeWindowTitle); } str13 = str13.Replace("@@EXTRACT_EXISTING_FILE", ((int) options.ExtractExistingFile).ToString()); if (postExtractCommandLine != null) { str13 = str13.Replace("@@POST_UNPACK_CMD_LINE", postExtractCommandLine); } builder.Append(str13).Append("\n"); } } builder.Append("\n\n"); } } } string str14 = builder.ToString(); CompilerResults results = provider.CompileAssemblyFromSource(parameters, new string[] { str14 }); if (results == null) { throw new SfxGenerationException("Cannot compile the extraction logic!"); } if (this.Verbose) { foreach (string str15 in results.Output) { this.StatusMessageTextWriter.WriteLine(str15); } } if (results.Errors.Count != 0) { using (TextWriter writer = new StreamWriter(str6)) { writer.Write(str14); writer.Write("\n\n\n// ------------------------------------------------------------------\n"); writer.Write("// Errors during compilation: \n//\n"); string fileName = Path.GetFileName(str6); foreach (CompilerError error in results.Errors) { writer.Write(string.Format("// {0}({1},{2}): {3} {4}: {5}\n//\n", new object[] { fileName, error.Line, error.Column, error.IsWarning ? "Warning" : "error", error.ErrorNumber, error.ErrorText })); } } throw new SfxGenerationException(string.Format("Errors compiling the extraction logic! {0}", str6)); } this.OnSaveEvent(ZipProgressEventType.Saving_AfterCompileSelfExtractor); using (Stream stream2 = File.OpenRead(path)) { byte[] buffer = new byte[0xfa0]; int count = 1; while (count != 0) { count = stream2.Read(buffer, 0, buffer.Length); if (count != 0) { this.WriteStream.Write(buffer, 0, count); } } } } this.OnSaveEvent(ZipProgressEventType.Saving_AfterSaveTempArchive); } finally { try { IOException exception; if (Directory.Exists(str3)) { try { Directory.Delete(str3, true); } catch (IOException exception1) { exception = exception1; this.StatusMessageTextWriter.WriteLine("Warning: Exception: {0}", exception); } } if (File.Exists(path)) { try { File.Delete(path); } catch (IOException exception2) { exception = exception2; this.StatusMessageTextWriter.WriteLine("Warning: Exception: {0}", exception); } } } catch (IOException) { } } } public ZipEntry AddDirectory(string directoryName) { return this.AddDirectory(directoryName, null); } public ZipEntry AddDirectory(string directoryName, string directoryPathInArchive) { return this.AddOrUpdateDirectoryImpl(directoryName, directoryPathInArchive, AddOrUpdateAction.AddOnly); } public ZipEntry AddDirectoryByName(string directoryNameInArchive) { ZipEntry entry = ZipEntry.CreateFromNothing(directoryNameInArchive); entry._container = new ZipContainer(this); entry.MarkAsDirectory(); entry.AlternateEncoding = this.AlternateEncoding; entry.AlternateEncodingUsage = this.AlternateEncodingUsage; entry.SetEntryTimes(DateTime.Now, DateTime.Now, DateTime.Now); entry.EmitTimesInWindowsFormatWhenSaving = this._emitNtfsTimes; entry.EmitTimesInUnixFormatWhenSaving = this._emitUnixTimes; entry._Source = ZipEntrySource.Stream; this.InternalAddEntry(entry.FileName, entry); this.AfterAddEntry(entry); return entry; } public ZipEntry AddEntry(string entryName, WriteDelegate writer) { ZipEntry ze = ZipEntry.CreateForWriter(entryName, writer); if (this.Verbose) { this.StatusMessageTextWriter.WriteLine("adding {0}...", entryName); } return this._InternalAddEntry(ze); } public ZipEntry AddEntry(string entryName, Stream stream) { ZipEntry ze = ZipEntry.CreateForStream(entryName, stream); ze.SetEntryTimes(DateTime.Now, DateTime.Now, DateTime.Now); if (this.Verbose) { this.StatusMessageTextWriter.WriteLine("adding {0}...", entryName); } return this._InternalAddEntry(ze); } public ZipEntry AddEntry(string entryName, string content) { return this.AddEntry(entryName, content, Encoding.Default); } public ZipEntry AddEntry(string entryName, byte[] byteContent) { if (byteContent == null) { throw new ArgumentException("bad argument", "byteContent"); } MemoryStream stream = new MemoryStream(byteContent); return this.AddEntry(entryName, stream); } public ZipEntry AddEntry(string entryName, OpenDelegate opener, CloseDelegate closer) { ZipEntry ze = ZipEntry.CreateForJitStreamProvider(entryName, opener, closer); ze.SetEntryTimes(DateTime.Now, DateTime.Now, DateTime.Now); if (this.Verbose) { this.StatusMessageTextWriter.WriteLine("adding {0}...", entryName); } return this._InternalAddEntry(ze); } public ZipEntry AddEntry(string entryName, string content, Encoding encoding) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream, encoding); writer.Write(content); writer.Flush(); stream.Seek(0L, SeekOrigin.Begin); return this.AddEntry(entryName, stream); } public ZipEntry AddFile(string fileName) { return this.AddFile(fileName, null); } public ZipEntry AddFile(string fileName, string directoryPathInArchive) { string nameInArchive = ZipEntry.NameInArchive(fileName, directoryPathInArchive); ZipEntry ze = ZipEntry.CreateFromFile(fileName, nameInArchive); if (this.Verbose) { this.StatusMessageTextWriter.WriteLine("adding {0}...", fileName); } return this._InternalAddEntry(ze); } public void AddFiles(IEnumerable<string> fileNames) { this.AddFiles(fileNames, null); } public void AddFiles(IEnumerable<string> fileNames, string directoryPathInArchive) { this.AddFiles(fileNames, false, directoryPathInArchive); } public void AddFiles(IEnumerable<string> fileNames, bool preserveDirHierarchy, string directoryPathInArchive) { if (fileNames == null) { throw new ArgumentNullException("fileNames"); } this._addOperationCanceled = false; this.OnAddStarted(); if (preserveDirHierarchy) { foreach (string str in fileNames) { if (this._addOperationCanceled) { break; } if (directoryPathInArchive != null) { string fullPath = Path.GetFullPath(Path.Combine(directoryPathInArchive, Path.GetDirectoryName(str))); this.AddFile(str, fullPath); } else { this.AddFile(str, null); } } } else { foreach (string str in fileNames) { if (this._addOperationCanceled) { break; } this.AddFile(str, directoryPathInArchive); } } if (!this._addOperationCanceled) { this.OnAddCompleted(); } } public ZipEntry AddItem(string fileOrDirectoryName) { return this.AddItem(fileOrDirectoryName, null); } public ZipEntry AddItem(string fileOrDirectoryName, string directoryPathInArchive) { if (File.Exists(fileOrDirectoryName)) { return this.AddFile(fileOrDirectoryName, directoryPathInArchive); } if (!Directory.Exists(fileOrDirectoryName)) { throw new FileNotFoundException(string.Format("That file or directory ({0}) does not exist!", fileOrDirectoryName)); } return this.AddDirectory(fileOrDirectoryName, directoryPathInArchive); } private ZipEntry AddOrUpdateDirectoryImpl(string directoryName, string rootDirectoryPathInArchive, AddOrUpdateAction action) { if (rootDirectoryPathInArchive == null) { rootDirectoryPathInArchive = ""; } return this.AddOrUpdateDirectoryImpl(directoryName, rootDirectoryPathInArchive, action, true, 0); } private ZipEntry AddOrUpdateDirectoryImpl(string directoryName, string rootDirectoryPathInArchive, AddOrUpdateAction action, bool recurse, int level) { if (this.Verbose) { this.StatusMessageTextWriter.WriteLine("{0} {1}...", (action == AddOrUpdateAction.AddOnly) ? "adding" : "Adding or updating", directoryName); } if (level == 0) { this._addOperationCanceled = false; this.OnAddStarted(); } if (this._addOperationCanceled) { return null; } string fileName = rootDirectoryPathInArchive; ZipEntry entry = null; if (level > 0) { int length = directoryName.Length; for (int i = level; i > 0; i--) { length = directoryName.LastIndexOfAny(@"/\".ToCharArray(), length - 1, length - 1); } fileName = directoryName.Substring(length + 1); fileName = Path.Combine(rootDirectoryPathInArchive, fileName); } if ((level > 0) || (rootDirectoryPathInArchive != "")) { entry = ZipEntry.CreateFromFile(directoryName, fileName); entry._container = new ZipContainer(this); entry.AlternateEncoding = this.AlternateEncoding; entry.AlternateEncodingUsage = this.AlternateEncodingUsage; entry.MarkAsDirectory(); entry.EmitTimesInWindowsFormatWhenSaving = this._emitNtfsTimes; entry.EmitTimesInUnixFormatWhenSaving = this._emitUnixTimes; if (!this._entries.ContainsKey(entry.FileName)) { this.InternalAddEntry(entry.FileName, entry); this.AfterAddEntry(entry); } fileName = entry.FileName; } if (!this._addOperationCanceled) { string[] files = Directory.GetFiles(directoryName); if (recurse) { foreach (string str2 in files) { if (this._addOperationCanceled) { break; } if (action == AddOrUpdateAction.AddOnly) { this.AddFile(str2, fileName); } else { this.UpdateFile(str2, fileName); } } if (!this._addOperationCanceled) { string[] directories = Directory.GetDirectories(directoryName); foreach (string str3 in directories) { FileAttributes attributes = File.GetAttributes(str3); if (this.AddDirectoryWillTraverseReparsePoints || ((attributes & FileAttributes.ReparsePoint) == 0)) { this.AddOrUpdateDirectoryImpl(str3, rootDirectoryPathInArchive, action, recurse, level + 1); } } } } } if (level == 0) { this.OnAddCompleted(); } return entry; } public void AddSelectedFiles(string selectionCriteria) { this.AddSelectedFiles(selectionCriteria, ".", null, false); } public void AddSelectedFiles(string selectionCriteria, bool recurseDirectories) { this.AddSelectedFiles(selectionCriteria, ".", null, recurseDirectories); } public void AddSelectedFiles(string selectionCriteria, string directoryOnDisk) { this.AddSelectedFiles(selectionCriteria, directoryOnDisk, null, false); } public void AddSelectedFiles(string selectionCriteria, string directoryOnDisk, bool recurseDirectories) { this.AddSelectedFiles(selectionCriteria, directoryOnDisk, null, recurseDirectories); } public void AddSelectedFiles(string selectionCriteria, string directoryOnDisk, string directoryPathInArchive) { this.AddSelectedFiles(selectionCriteria, directoryOnDisk, directoryPathInArchive, false); } public void AddSelectedFiles(string selectionCriteria, string directoryOnDisk, string directoryPathInArchive, bool recurseDirectories) { this._AddOrUpdateSelectedFiles(selectionCriteria, directoryOnDisk, directoryPathInArchive, recurseDirectories, false); } internal void AfterAddEntry(ZipEntry entry) { EventHandler<AddProgressEventArgs> addProgress = this.AddProgress; if (addProgress != null) { AddProgressEventArgs e = AddProgressEventArgs.AfterEntry(this.ArchiveNameForEvent, entry, this._entries.Count); addProgress(this, e); if (e.Cancel) { this._addOperationCanceled = true; } } } public static bool CheckZip(string zipFileName) { return CheckZip(zipFileName, false, null); } public static bool CheckZip(string zipFileName, bool fixIfNecessary, TextWriter writer) { ZipFile file = null; ZipFile file2 = null; bool flag = true; try { file = new ZipFile { FullScan = true }; file.Initialize(zipFileName); file2 = Read(zipFileName); foreach (ZipEntry entry in file) { foreach (ZipEntry entry2 in file2) { if (entry.FileName == entry2.FileName) { if (entry._RelativeOffsetOfLocalHeader != entry2._RelativeOffsetOfLocalHeader) { flag = false; if (writer != null) { writer.WriteLine("{0}: mismatch in RelativeOffsetOfLocalHeader (0x{1:X16} != 0x{2:X16})", entry.FileName, entry._RelativeOffsetOfLocalHeader, entry2._RelativeOffsetOfLocalHeader); } } if (entry._CompressedSize != entry2._CompressedSize) { flag = false; if (writer != null) { writer.WriteLine("{0}: mismatch in CompressedSize (0x{1:X16} != 0x{2:X16})", entry.FileName, entry._CompressedSize, entry2._CompressedSize); } } if (entry._UncompressedSize != entry2._UncompressedSize) { flag = false; if (writer != null) { writer.WriteLine("{0}: mismatch in UncompressedSize (0x{1:X16} != 0x{2:X16})", entry.FileName, entry._UncompressedSize, entry2._UncompressedSize); } } if (entry.CompressionMethod != entry2.CompressionMethod) { flag = false; if (writer != null) { writer.WriteLine("{0}: mismatch in CompressionMethod (0x{1:X4} != 0x{2:X4})", entry.FileName, entry.CompressionMethod, entry2.CompressionMethod); } } if (entry.Crc != entry2.Crc) { flag = false; if (writer != null) { writer.WriteLine("{0}: mismatch in Crc32 (0x{1:X4} != 0x{2:X4})", entry.FileName, entry.Crc, entry2.Crc); } } break; } } } file2.Dispose(); file2 = null; if (!(flag || !fixIfNecessary)) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(zipFileName); fileNameWithoutExtension = string.Format("{0}_fixed.zip", fileNameWithoutExtension); file.Save(fileNameWithoutExtension); } } finally { if (file != null) { file.Dispose(); } if (file2 != null) { file2.Dispose(); } } return flag; } public static bool CheckZipPassword(string zipFileName, string password) { bool flag = false; try { using (ZipFile file = Read(zipFileName)) { foreach (ZipEntry entry in file) { if (!(entry.IsDirectory || !entry.UsesEncryption)) { entry.ExtractWithPassword(Stream.Null, password); } } } flag = true; } catch (BadPasswordException) { } return flag; } private void CleanupAfterSaveOperation() { if (this._name != null) { if (this._writestream != null) { try { this._writestream.Dispose(); } catch (IOException) { } } this._writestream = null; if (this._temporaryFileName != null) { this.RemoveTempFile(); this._temporaryFileName = null; } } } public bool ContainsEntry(string name) { return this._entries.ContainsKey(SharedUtilities.NormalizePathForUseInZipFile(name)); } private void DeleteFileWithRetry(string filename) { bool flag = false; int num = 3; for (int i = 0; (i < num) && !flag; i++) { try { File.Delete(filename); flag = true; } catch (UnauthorizedAccessException) { Console.WriteLine("************************************************** Retry delete."); Thread.Sleep((int) (200 + (i * 200))); } } } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposeManagedResources) { if (!this._disposed) { if (disposeManagedResources) { if (this._ReadStreamIsOurs && (this._readstream != null)) { this._readstream.Dispose(); this._readstream = null; } if (((this._temporaryFileName != null) && (this._name != null)) && (this._writestream != null)) { this._writestream.Dispose(); this._writestream = null; } if (this.ParallelDeflater != null) { this.ParallelDeflater.Dispose(); this.ParallelDeflater = null; } } this._disposed = true; } } private string EnsureendInSlash(string s) { if (s.EndsWith(@"\")) { return s; } return (s + @"\"); } public void ExtractAll(string path) { this._InternalExtractAll(path, true); } public void ExtractAll(string path, ExtractExistingFileAction extractExistingFile) { this.ExtractExistingFile = extractExistingFile; this._InternalExtractAll(path, true); } private static void ExtractResourceToFile(Assembly a, string resourceName, string filename) { int count = 0; byte[] buffer = new byte[0x400]; using (Stream stream = a.GetManifestResourceStream(resourceName)) { if (stream == null) { throw new ZipException(string.Format("missing resource '{0}'", resourceName)); } using (FileStream stream2 = File.OpenWrite(filename)) { do { count = stream.Read(buffer, 0, buffer.Length); stream2.Write(buffer, 0, count); } while (count > 0); } } } public void ExtractSelectedEntries(string selectionCriteria) { foreach (ZipEntry entry in this.SelectEntries(selectionCriteria)) { entry.Password = this._Password; entry.Extract(); } } public void ExtractSelectedEntries(string selectionCriteria, ExtractExistingFileAction extractExistingFile) { foreach (ZipEntry entry in this.SelectEntries(selectionCriteria)) { entry.Password = this._Password; entry.Extract(extractExistingFile); } } public void ExtractSelectedEntries(string selectionCriteria, string directoryPathInArchive) { foreach (ZipEntry entry in this.SelectEntries(selectionCriteria, directoryPathInArchive)) { entry.Password = this._Password; entry.Extract(); } } public void ExtractSelectedEntries(string selectionCriteria, string directoryInArchive, string extractDirectory) { foreach (ZipEntry entry in this.SelectEntries(selectionCriteria, directoryInArchive)) { entry.Password = this._Password; entry.Extract(extractDirectory); } } public void ExtractSelectedEntries(string selectionCriteria, string directoryPathInArchive, string extractDirectory, ExtractExistingFileAction extractExistingFile) { foreach (ZipEntry entry in this.SelectEntries(selectionCriteria, directoryPathInArchive)) { entry.Password = this._Password; entry.Extract(extractDirectory, extractExistingFile); } } public static void FixZipDirectory(string zipFileName) { using (ZipFile file = new ZipFile()) { file.FullScan = true; file.Initialize(zipFileName); file.Save(zipFileName); } } internal static string GenerateTempPathname(string dir, string extension) { string path = null; string name = Assembly.GetExecutingAssembly().GetName().Name; do { string str3 = Guid.NewGuid().ToString(); string str4 = string.Format("{0}-{1}-{2}.{3}", new object[] { name, DateTime.Now.ToString("yyyyMMMdd-HHmmss"), str3, extension }); path = Path.Combine(dir, str4); } while (File.Exists(path) || Directory.Exists(path)); return path; } public IEnumerator<ZipEntry> GetEnumerator() { foreach (ZipEntry iteratorVariable0 in this._entries.Values) { yield return iteratorVariable0; } } [DispId(-4)] public IEnumerator GetNewEnum() { return this.GetEnumerator(); } public void Initialize(string fileName) { try { this._InitInstance(fileName, null); } catch (Exception exception) { throw new ZipException(string.Format("{0} is not a valid zip file", fileName), exception); } } internal void InternalAddEntry(string name, ZipEntry entry) { this._entries.Add(name, entry); this._zipEntriesAsList = null; this._contentsChanged = true; } public static bool IsZipFile(string fileName) { return IsZipFile(fileName, false); } public static bool IsZipFile(Stream stream, bool testExtract) { if (stream == null) { throw new ArgumentNullException("stream"); } bool flag = false; try { if (!stream.CanRead) { return false; } Stream @null = Stream.Null; using (ZipFile file = Read(stream, null, null, null)) { if (testExtract) { foreach (ZipEntry entry in file) { if (!entry.IsDirectory) { entry.Extract(@null); } } } } flag = true; } catch (IOException) { } catch (ZipException) { } return flag; } public static bool IsZipFile(string fileName, bool testExtract) { bool flag = false; try { if (!File.Exists(fileName)) { return false; } using (FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { flag = IsZipFile(stream, testExtract); } } catch (IOException) { } catch (ZipException) { } return flag; } private static void NotifyEntriesSaveComplete(ICollection<ZipEntry> c) { foreach (ZipEntry entry in c) { entry.NotifySaveComplete(); } } internal void NotifyEntryChanged() { this._contentsChanged = true; } private void OnAddCompleted() { EventHandler<AddProgressEventArgs> addProgress = this.AddProgress; if (addProgress != null) { AddProgressEventArgs e = AddProgressEventArgs.Completed(this.ArchiveNameForEvent); addProgress(this, e); } } private void OnAddStarted() { EventHandler<AddProgressEventArgs> addProgress = this.AddProgress; if (addProgress != null) { AddProgressEventArgs e = AddProgressEventArgs.Started(this.ArchiveNameForEvent); addProgress(this, e); if (e.Cancel) { this._addOperationCanceled = true; } } } private void OnExtractAllCompleted(string path) { EventHandler<ExtractProgressEventArgs> extractProgress = this.ExtractProgress; if (extractProgress != null) { ExtractProgressEventArgs e = ExtractProgressEventArgs.ExtractAllCompleted(this.ArchiveNameForEvent, path); extractProgress(this, e); } } private void OnExtractAllStarted(string path) { EventHandler<ExtractProgressEventArgs> extractProgress = this.ExtractProgress; if (extractProgress != null) { ExtractProgressEventArgs e = ExtractProgressEventArgs.ExtractAllStarted(this.ArchiveNameForEvent, path); extractProgress(this, e); } } internal bool OnExtractBlock(ZipEntry entry, long bytesWritten, long totalBytesToWrite) { EventHandler<ExtractProgressEventArgs> extractProgress = this.ExtractProgress; if (extractProgress != null) { ExtractProgressEventArgs e = ExtractProgressEventArgs.ByteUpdate(this.ArchiveNameForEvent, entry, bytesWritten, totalBytesToWrite); extractProgress(this, e); if (e.Cancel) { this._extractOperationCanceled = true; } } return this._extractOperationCanceled; } private void OnExtractEntry(int current, bool before, ZipEntry currentEntry, string path) { EventHandler<ExtractProgressEventArgs> extractProgress = this.ExtractProgress; if (extractProgress != null) { ExtractProgressEventArgs e = new ExtractProgressEventArgs(this.ArchiveNameForEvent, before, this._entries.Count, current, currentEntry, path); extractProgress(this, e); if (e.Cancel) { this._extractOperationCanceled = true; } } } internal bool OnExtractExisting(ZipEntry entry, string path) { EventHandler<ExtractProgressEventArgs> extractProgress = this.ExtractProgress; if (extractProgress != null) { ExtractProgressEventArgs e = ExtractProgressEventArgs.ExtractExisting(this.ArchiveNameForEvent, entry, path); extractProgress(this, e); if (e.Cancel) { this._extractOperationCanceled = true; } } return this._extractOperationCanceled; } internal void OnReadBytes(ZipEntry entry) { EventHandler<ReadProgressEventArgs> readProgress = this.ReadProgress; if (readProgress != null) { ReadProgressEventArgs e = ReadProgressEventArgs.ByteUpdate(this.ArchiveNameForEvent, entry, this.ReadStream.Position, this.LengthOfReadStream); readProgress(this, e); } } private void OnReadCompleted() { EventHandler<ReadProgressEventArgs> readProgress = this.ReadProgress; if (readProgress != null) { ReadProgressEventArgs e = ReadProgressEventArgs.Completed(this.ArchiveNameForEvent); readProgress(this, e); } } internal void OnReadEntry(bool before, ZipEntry entry) { EventHandler<ReadProgressEventArgs> readProgress = this.ReadProgress; if (readProgress != null) { ReadProgressEventArgs e = before ? ReadProgressEventArgs.Before(this.ArchiveNameForEvent, this._entries.Count) : ReadProgressEventArgs.After(this.ArchiveNameForEvent, entry, this._entries.Count); readProgress(this, e); } } private void OnReadStarted() { EventHandler<ReadProgressEventArgs> readProgress = this.ReadProgress; if (readProgress != null) { ReadProgressEventArgs e = ReadProgressEventArgs.Started(this.ArchiveNameForEvent); readProgress(this, e); } } internal bool OnSaveBlock(ZipEntry entry, long bytesXferred, long totalBytesToXfer) { EventHandler<SaveProgressEventArgs> saveProgress = this.SaveProgress; if (saveProgress != null) { SaveProgressEventArgs e = SaveProgressEventArgs.ByteUpdate(this.ArchiveNameForEvent, entry, bytesXferred, totalBytesToXfer); saveProgress(this, e); if (e.Cancel) { this._saveOperationCanceled = true; } } return this._saveOperationCanceled; } private void OnSaveCompleted() { EventHandler<SaveProgressEventArgs> saveProgress = this.SaveProgress; if (saveProgress != null) { SaveProgressEventArgs e = SaveProgressEventArgs.Completed(this.ArchiveNameForEvent); saveProgress(this, e); } } private void OnSaveEntry(int current, ZipEntry entry, bool before) { EventHandler<SaveProgressEventArgs> saveProgress = this.SaveProgress; if (saveProgress != null) { SaveProgressEventArgs e = new SaveProgressEventArgs(this.ArchiveNameForEvent, before, this._entries.Count, current, entry); saveProgress(this, e); if (e.Cancel) { this._saveOperationCanceled = true; } } } private void OnSaveEvent(ZipProgressEventType eventFlavor) { EventHandler<SaveProgressEventArgs> saveProgress = this.SaveProgress; if (saveProgress != null) { SaveProgressEventArgs e = new SaveProgressEventArgs(this.ArchiveNameForEvent, eventFlavor); saveProgress(this, e); if (e.Cancel) { this._saveOperationCanceled = true; } } } private void OnSaveStarted() { EventHandler<SaveProgressEventArgs> saveProgress = this.SaveProgress; if (saveProgress != null) { SaveProgressEventArgs e = SaveProgressEventArgs.Started(this.ArchiveNameForEvent); saveProgress(this, e); if (e.Cancel) { this._saveOperationCanceled = true; } } } internal bool OnSingleEntryExtract(ZipEntry entry, string path, bool before) { EventHandler<ExtractProgressEventArgs> extractProgress = this.ExtractProgress; if (extractProgress != null) { ExtractProgressEventArgs e = before ? ExtractProgressEventArgs.BeforeExtractEntry(this.ArchiveNameForEvent, entry, path) : ExtractProgressEventArgs.AfterExtractEntry(this.ArchiveNameForEvent, entry, path); extractProgress(this, e); if (e.Cancel) { this._extractOperationCanceled = true; } } return this._extractOperationCanceled; } internal bool OnZipErrorSaving(ZipEntry entry, Exception exc) { if (this.ZipError != null) { lock (this.LOCK) { ZipErrorEventArgs e = ZipErrorEventArgs.Saving(this.Name, entry, exc); this.ZipError(this, e); if (e.Cancel) { this._saveOperationCanceled = true; } } } return this._saveOperationCanceled; } public static ZipFile Read(Stream zipStream) { return Read(zipStream, null, null, null); } public static ZipFile Read(string fileName) { return Read(fileName, null, null, null); } public static ZipFile Read(Stream zipStream, ReadOptions options) { if (options == null) { throw new ArgumentNullException("options"); } return Read(zipStream, options.StatusMessageWriter, options.Encoding, options.ReadProgress); } public static ZipFile Read(string fileName, ReadOptions options) { if (options == null) { throw new ArgumentNullException("options"); } return Read(fileName, options.StatusMessageWriter, options.Encoding, options.ReadProgress); } private static ZipFile Read(Stream zipStream, TextWriter statusMessageWriter, Encoding encoding, EventHandler<ReadProgressEventArgs> readProgress) { if (zipStream == null) { throw new ArgumentNullException("zipStream"); } ZipFile zf = new ZipFile { _StatusMessageTextWriter = statusMessageWriter, _alternateEncoding = encoding ?? DefaultEncoding, _alternateEncodingUsage = ZipOption.Always }; if (readProgress != null) { zf.ReadProgress += readProgress; } zf._readstream = (zipStream.Position == 0L) ? zipStream : new OffsetStream(zipStream); zf._ReadStreamIsOurs = false; if (zf.Verbose) { zf._StatusMessageTextWriter.WriteLine("reading from stream..."); } ReadIntoInstance(zf); return zf; } private static ZipFile Read(string fileName, TextWriter statusMessageWriter, Encoding encoding, EventHandler<ReadProgressEventArgs> readProgress) { ZipFile zf = new ZipFile { AlternateEncoding = encoding ?? DefaultEncoding, AlternateEncodingUsage = ZipOption.Always, _StatusMessageTextWriter = statusMessageWriter, _name = fileName }; if (readProgress != null) { zf.ReadProgress = readProgress; } if (zf.Verbose) { zf._StatusMessageTextWriter.WriteLine("reading from {0}...", fileName); } ReadIntoInstance(zf); zf._fileAlreadyExists = true; return zf; } private static void ReadCentralDirectory(ZipFile zf) { ZipEntry entry; bool flag = false; Dictionary<string, object> previouslySeen = new Dictionary<string, object>(); while ((entry = ZipEntry.ReadDirEntry(zf, previouslySeen)) != null) { entry.ResetDirEntry(); zf.OnReadEntry(true, null); if (zf.Verbose) { zf.StatusMessageTextWriter.WriteLine("entry {0}", entry.FileName); } zf._entries.Add(entry.FileName, entry); if (entry._InputUsesZip64) { flag = true; } previouslySeen.Add(entry.FileName, null); } if (flag) { zf.UseZip64WhenSaving = Zip64Option.Always; } if (zf._locEndOfCDS > 0L) { zf.ReadStream.Seek(zf._locEndOfCDS, SeekOrigin.Begin); } ReadCentralDirectoryFooter(zf); if (!(!zf.Verbose || string.IsNullOrEmpty(zf.Comment))) { zf.StatusMessageTextWriter.WriteLine("Zip file Comment: {0}", zf.Comment); } if (zf.Verbose) { zf.StatusMessageTextWriter.WriteLine("read in {0} entries.", zf._entries.Count); } zf.OnReadCompleted(); } private static void ReadCentralDirectoryFooter(ZipFile zf) { Stream readStream = zf.ReadStream; int num = SharedUtilities.ReadSignature(readStream); byte[] buffer = null; int startIndex = 0; if (num == 0x6064b50L) { buffer = new byte[0x34]; readStream.Read(buffer, 0, buffer.Length); long num3 = BitConverter.ToInt64(buffer, 0); if (num3 < 0x2cL) { throw new ZipException("Bad size in the ZIP64 Central Directory."); } zf._versionMadeBy = BitConverter.ToUInt16(buffer, startIndex); startIndex += 2; zf._versionNeededToExtract = BitConverter.ToUInt16(buffer, startIndex); startIndex += 2; zf._diskNumberWithCd = BitConverter.ToUInt32(buffer, startIndex); startIndex += 2; buffer = new byte[num3 - 0x2cL]; readStream.Read(buffer, 0, buffer.Length); if (SharedUtilities.ReadSignature(readStream) != 0x7064b50L) { throw new ZipException("Inconsistent metadata in the ZIP64 Central Directory."); } buffer = new byte[0x10]; readStream.Read(buffer, 0, buffer.Length); num = SharedUtilities.ReadSignature(readStream); } if (num != 0x6054b50L) { readStream.Seek(-4L, SeekOrigin.Current); throw new BadReadException(string.Format("Bad signature ({0:X8}) at position 0x{1:X8}", num, readStream.Position)); } buffer = new byte[0x10]; zf.ReadStream.Read(buffer, 0, buffer.Length); if (zf._diskNumberWithCd == 0) { zf._diskNumberWithCd = BitConverter.ToUInt16(buffer, 2); } ReadZipFileComment(zf); } private static uint ReadFirstFourBytes(Stream s) { return (uint) SharedUtilities.ReadInt(s); } private static void ReadIntoInstance(ZipFile zf) { Stream readStream = zf.ReadStream; try { zf._readName = zf._name; if (!readStream.CanSeek) { ReadIntoInstance_Orig(zf); return; } zf.OnReadStarted(); if (ReadFirstFourBytes(readStream) == 0x6054b50) { return; } int num2 = 0; bool flag = false; long offset = readStream.Length - 0x40L; long num4 = Math.Max((long) (readStream.Length - 0x4000L), (long) 10L); do { if (offset < 0L) { offset = 0L; } readStream.Seek(offset, SeekOrigin.Begin); if (SharedUtilities.FindSignature(readStream, 0x6054b50) != -1L) { flag = true; } else { if (offset == 0L) { break; } num2++; offset -= (0x20 * (num2 + 1)) * num2; } } while (!flag && (offset > num4)); if (flag) { zf._locEndOfCDS = readStream.Position - 4L; byte[] buffer = new byte[0x10]; readStream.Read(buffer, 0, buffer.Length); zf._diskNumberWithCd = BitConverter.ToUInt16(buffer, 2); if (zf._diskNumberWithCd == 0xffff) { throw new ZipException("Spanned archives with more than 65534 segments are not supported at this time."); } zf._diskNumberWithCd++; int startIndex = 12; uint num7 = BitConverter.ToUInt32(buffer, startIndex); if (num7 == uint.MaxValue) { Zip64SeekToCentralDirectory(zf); } else { zf._OffsetOfCentralDirectory = num7; readStream.Seek((long) num7, SeekOrigin.Begin); } ReadCentralDirectory(zf); } else { readStream.Seek(0L, SeekOrigin.Begin); ReadIntoInstance_Orig(zf); } } catch (Exception exception) { if (zf._ReadStreamIsOurs && (zf._readstream != null)) { try { zf._readstream.Dispose(); zf._readstream = null; } finally { } } throw new ZipException("Cannot read that as a ZipFile", exception); } zf._contentsChanged = false; } private static void ReadIntoInstance_Orig(ZipFile zf) { ZipEntry entry; zf.OnReadStarted(); zf._entries = new Dictionary<string, ZipEntry>(); if (zf.Verbose) { if (zf.Name == null) { zf.StatusMessageTextWriter.WriteLine("Reading zip from stream..."); } else { zf.StatusMessageTextWriter.WriteLine("Reading zip {0}...", zf.Name); } } bool first = true; ZipContainer zc = new ZipContainer(zf); while ((entry = ZipEntry.ReadEntry(zc, first)) != null) { if (zf.Verbose) { zf.StatusMessageTextWriter.WriteLine(" {0}", entry.FileName); } zf._entries.Add(entry.FileName, entry); first = false; } try { ZipEntry entry2; Dictionary<string, object> previouslySeen = new Dictionary<string, object>(); while ((entry2 = ZipEntry.ReadDirEntry(zf, previouslySeen)) != null) { ZipEntry entry3 = zf._entries[entry2.FileName]; if (entry3 != null) { entry3._Comment = entry2.Comment; if (entry2.IsDirectory) { entry3.MarkAsDirectory(); } } previouslySeen.Add(entry2.FileName, null); } if (zf._locEndOfCDS > 0L) { zf.ReadStream.Seek(zf._locEndOfCDS, SeekOrigin.Begin); } ReadCentralDirectoryFooter(zf); if (!(!zf.Verbose || string.IsNullOrEmpty(zf.Comment))) { zf.StatusMessageTextWriter.WriteLine("Zip file Comment: {0}", zf.Comment); } } catch (ZipException) { } catch (IOException) { } zf.OnReadCompleted(); } private static void ReadZipFileComment(ZipFile zf) { byte[] buffer = new byte[2]; zf.ReadStream.Read(buffer, 0, buffer.Length); short num = (short) (buffer[0] + (buffer[1] * 0x100)); if (num > 0) { buffer = new byte[num]; zf.ReadStream.Read(buffer, 0, buffer.Length); string str = zf.AlternateEncoding.GetString(buffer, 0, buffer.Length); zf.Comment = str; } } public void RemoveEntries(ICollection<ZipEntry> entriesToRemove) { if (entriesToRemove == null) { throw new ArgumentNullException("entriesToRemove"); } foreach (ZipEntry entry in entriesToRemove) { this.RemoveEntry(entry); } } public void RemoveEntries(ICollection<string> entriesToRemove) { if (entriesToRemove == null) { throw new ArgumentNullException("entriesToRemove"); } foreach (string str in entriesToRemove) { this.RemoveEntry(str); } } public void RemoveEntry(ZipEntry entry) { if (entry == null) { throw new ArgumentNullException("entry"); } this._entries.Remove(SharedUtilities.NormalizePathForUseInZipFile(entry.FileName)); this._zipEntriesAsList = null; this._contentsChanged = true; } public void RemoveEntry(string fileName) { string str = ZipEntry.NameInArchive(fileName, null); ZipEntry entry = this[str]; if (entry == null) { throw new ArgumentException("The entry you specified was not found in the zip archive."); } this.RemoveEntry(entry); } private void RemoveEntryForUpdate(string entryName) { if (string.IsNullOrEmpty(entryName)) { throw new ArgumentNullException("entryName"); } string directoryPathInArchive = null; if (entryName.IndexOf('\\') != -1) { directoryPathInArchive = Path.GetDirectoryName(entryName); entryName = Path.GetFileName(entryName); } string fileName = ZipEntry.NameInArchive(entryName, directoryPathInArchive); if (this[fileName] != null) { this.RemoveEntry(fileName); } } public int RemoveSelectedEntries(string selectionCriteria) { ICollection<ZipEntry> entriesToRemove = this.SelectEntries(selectionCriteria); this.RemoveEntries(entriesToRemove); return entriesToRemove.Count; } public int RemoveSelectedEntries(string selectionCriteria, string directoryPathInArchive) { ICollection<ZipEntry> entriesToRemove = this.SelectEntries(selectionCriteria, directoryPathInArchive); this.RemoveEntries(entriesToRemove); return entriesToRemove.Count; } private void RemoveTempFile() { try { if (File.Exists(this._temporaryFileName)) { File.Delete(this._temporaryFileName); } } catch (IOException exception) { if (this.Verbose) { this.StatusMessageTextWriter.WriteLine("ZipFile::Save: could not delete temp file: {0}.", exception.Message); } } } private static string ReplaceLeadingDirectory(string original, string pattern, string replacement) { string str = original.ToUpper(); string str2 = pattern.ToUpper(); if (str.IndexOf(str2) != 0) { return original; } return (replacement + original.Substring(str2.Length)); } internal void Reset(bool whileSaving) { if (this._JustSaved) { using (ZipFile file = new ZipFile()) { file._readName = file._name = whileSaving ? (this._readName ?? this._name) : this._name; file.AlternateEncoding = this.AlternateEncoding; file.AlternateEncodingUsage = this.AlternateEncodingUsage; ReadIntoInstance(file); foreach (ZipEntry entry in file) { foreach (ZipEntry entry2 in this) { if (entry.FileName == entry2.FileName) { entry2.CopyMetaData(entry); break; } } } } this._JustSaved = false; } } public void Save() { try { bool flag = false; this._saveOperationCanceled = false; this._numberOfSegmentsForMostRecentSave = 0; this.OnSaveStarted(); if (this.WriteStream == null) { throw new BadStateException("You haven't specified where to save the zip."); } if (!(((this._name == null) || !this._name.EndsWith(".exe")) || this._SavingSfx)) { throw new BadStateException("You specified an EXE for a plain zip file."); } if (!this._contentsChanged) { this.OnSaveCompleted(); if (this.Verbose) { this.StatusMessageTextWriter.WriteLine("No save is necessary...."); } } else { this.Reset(true); if (this.Verbose) { this.StatusMessageTextWriter.WriteLine("saving...."); } if ((this._entries.Count >= 0xffff) && (this._zip64 == Zip64Option.Default)) { throw new ZipException("The number of entries is 65535 or greater. Consider setting the UseZip64WhenSaving property on the ZipFile instance."); } int current = 0; ICollection<ZipEntry> entries = this.SortEntriesBeforeSaving ? this.EntriesSorted : this.Entries; foreach (ZipEntry entry in entries) { this.OnSaveEntry(current, entry, true); entry.Write(this.WriteStream); if (this._saveOperationCanceled) { break; } current++; this.OnSaveEntry(current, entry, false); if (this._saveOperationCanceled) { break; } if (entry.IncludedInMostRecentSave) { flag |= entry.OutputUsedZip64.Value; } } if (!this._saveOperationCanceled) { ZipSegmentedStream writeStream = this.WriteStream as ZipSegmentedStream; this._numberOfSegmentsForMostRecentSave = (writeStream != null) ? writeStream.CurrentSegment : 1; bool flag2 = ZipOutput.WriteCentralDirectoryStructure(this.WriteStream, entries, this._numberOfSegmentsForMostRecentSave, this._zip64, this.Comment, new ZipContainer(this)); this.OnSaveEvent(ZipProgressEventType.Saving_AfterSaveTempArchive); this._hasBeenSaved = true; this._contentsChanged = false; flag |= flag2; this._OutputUsesZip64 = new bool?(flag); if ((this._name != null) && ((this._temporaryFileName != null) || (writeStream != null))) { this.WriteStream.Dispose(); if (this._saveOperationCanceled) { return; } if (this._fileAlreadyExists && (this._readstream != null)) { this._readstream.Close(); this._readstream = null; foreach (ZipEntry entry in entries) { ZipSegmentedStream stream2 = entry._archiveStream as ZipSegmentedStream; if (stream2 != null) { stream2.Dispose(); } entry._archiveStream = null; } } string path = null; if (File.Exists(this._name)) { path = this._name + "." + Path.GetRandomFileName(); if (File.Exists(path)) { this.DeleteFileWithRetry(path); } File.Move(this._name, path); } this.OnSaveEvent(ZipProgressEventType.Saving_BeforeRenameTempArchive); File.Move((writeStream != null) ? writeStream.CurrentTempName : this._temporaryFileName, this._name); this.OnSaveEvent(ZipProgressEventType.Saving_AfterRenameTempArchive); if (path != null) { try { if (File.Exists(path)) { File.Delete(path); } } catch { } } this._fileAlreadyExists = true; } NotifyEntriesSaveComplete(entries); this.OnSaveCompleted(); this._JustSaved = true; } } } finally { this.CleanupAfterSaveOperation(); } } public void Save(Stream outputStream) { if (outputStream == null) { throw new ArgumentNullException("outputStream"); } if (!outputStream.CanWrite) { throw new ArgumentException("Must be a writable stream.", "outputStream"); } this._name = null; this._writestream = new CountingStream(outputStream); this._contentsChanged = true; this._fileAlreadyExists = false; this.Save(); } public void Save(string fileName) { if (this._name == null) { this._writestream = null; } else { this._readName = this._name; } this._name = fileName; if (Directory.Exists(this._name)) { throw new ZipException("Bad Directory", new ArgumentException("That name specifies an existing directory. Please specify a filename.", "fileName")); } this._contentsChanged = true; this._fileAlreadyExists = File.Exists(this._name); this.Save(); } public void SaveSelfExtractor(string exeToGenerate, SelfExtractorFlavor flavor) { SelfExtractorSaveOptions options = new SelfExtractorSaveOptions { Flavor = flavor }; this.SaveSelfExtractor(exeToGenerate, options); } public void SaveSelfExtractor(string exeToGenerate, SelfExtractorSaveOptions options) { if (this._name == null) { this._writestream = null; } this._SavingSfx = true; this._name = exeToGenerate; if (Directory.Exists(this._name)) { throw new ZipException("Bad Directory", new ArgumentException("That name specifies an existing directory. Please specify a filename.", "exeToGenerate")); } this._contentsChanged = true; this._fileAlreadyExists = File.Exists(this._name); this._SaveSfxStub(exeToGenerate, options); this.Save(); this._SavingSfx = false; } public ICollection<ZipEntry> SelectEntries(string selectionCriteria) { FileSelector selector = new FileSelector(selectionCriteria, this.AddDirectoryWillTraverseReparsePoints); return selector.SelectEntries(this); } public ICollection<ZipEntry> SelectEntries(string selectionCriteria, string directoryPathInArchive) { FileSelector selector = new FileSelector(selectionCriteria, this.AddDirectoryWillTraverseReparsePoints); return selector.SelectEntries(this, directoryPathInArchive); } internal Stream StreamForDiskNumber(uint diskNumber) { if (((diskNumber + 1) == this._diskNumberWithCd) || ((diskNumber == 0) && (this._diskNumberWithCd == 0))) { return this.ReadStream; } return ZipSegmentedStream.ForReading(this._readName ?? this._name, diskNumber, this._diskNumberWithCd); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public override string ToString() { return string.Format("ZipFile::{0}", this.Name); } public ZipEntry UpdateDirectory(string directoryName) { return this.UpdateDirectory(directoryName, null); } public ZipEntry UpdateDirectory(string directoryName, string directoryPathInArchive) { return this.AddOrUpdateDirectoryImpl(directoryName, directoryPathInArchive, AddOrUpdateAction.AddOrUpdate); } public ZipEntry UpdateEntry(string entryName, WriteDelegate writer) { this.RemoveEntryForUpdate(entryName); return this.AddEntry(entryName, writer); } public ZipEntry UpdateEntry(string entryName, Stream stream) { this.RemoveEntryForUpdate(entryName); return this.AddEntry(entryName, stream); } public ZipEntry UpdateEntry(string entryName, string content) { return this.UpdateEntry(entryName, content, Encoding.Default); } public ZipEntry UpdateEntry(string entryName, byte[] byteContent) { this.RemoveEntryForUpdate(entryName); return this.AddEntry(entryName, byteContent); } public ZipEntry UpdateEntry(string entryName, OpenDelegate opener, CloseDelegate closer) { this.RemoveEntryForUpdate(entryName); return this.AddEntry(entryName, opener, closer); } public ZipEntry UpdateEntry(string entryName, string content, Encoding encoding) { this.RemoveEntryForUpdate(entryName); return this.AddEntry(entryName, content, encoding); } public ZipEntry UpdateFile(string fileName) { return this.UpdateFile(fileName, null); } public ZipEntry UpdateFile(string fileName, string directoryPathInArchive) { string str = ZipEntry.NameInArchive(fileName, directoryPathInArchive); if (this[str] != null) { this.RemoveEntry(str); } return this.AddFile(fileName, directoryPathInArchive); } public void UpdateFiles(IEnumerable<string> fileNames) { this.UpdateFiles(fileNames, null); } public void UpdateFiles(IEnumerable<string> fileNames, string directoryPathInArchive) { if (fileNames == null) { throw new ArgumentNullException("fileNames"); } this.OnAddStarted(); foreach (string str in fileNames) { this.UpdateFile(str, directoryPathInArchive); } this.OnAddCompleted(); } public void UpdateItem(string itemName) { this.UpdateItem(itemName, null); } public void UpdateItem(string itemName, string directoryPathInArchive) { if (File.Exists(itemName)) { this.UpdateFile(itemName, directoryPathInArchive); } else { if (!Directory.Exists(itemName)) { throw new FileNotFoundException(string.Format("That file or directory ({0}) does not exist!", itemName)); } this.UpdateDirectory(itemName, directoryPathInArchive); } } public void UpdateSelectedFiles(string selectionCriteria, string directoryOnDisk, string directoryPathInArchive, bool recurseDirectories) { this._AddOrUpdateSelectedFiles(selectionCriteria, directoryOnDisk, directoryPathInArchive, recurseDirectories, true); } private static void Zip64SeekToCentralDirectory(ZipFile zf) { Stream readStream = zf.ReadStream; byte[] buffer = new byte[0x10]; readStream.Seek(-40L, SeekOrigin.Current); readStream.Read(buffer, 0, 0x10); long offset = BitConverter.ToInt64(buffer, 8); zf._OffsetOfCentralDirectory = uint.MaxValue; zf._OffsetOfCentralDirectory64 = offset; readStream.Seek(offset, SeekOrigin.Begin); uint num2 = (uint) SharedUtilities.ReadInt(readStream); if (num2 != 0x6064b50) { throw new BadReadException(string.Format(" Bad signature (0x{0:X8}) looking for ZIP64 EoCD Record at position 0x{1:X8}", num2, readStream.Position)); } readStream.Read(buffer, 0, 8); buffer = new byte[BitConverter.ToInt64(buffer, 0)]; readStream.Read(buffer, 0, buffer.Length); offset = BitConverter.ToInt64(buffer, 0x24); readStream.Seek(offset, SeekOrigin.Begin); } public bool AddDirectoryWillTraverseReparsePoints { get; set; } public Encoding AlternateEncoding { get { return this._alternateEncoding; } set { this._alternateEncoding = value; } } public ZipOption AlternateEncodingUsage { get { return this._alternateEncodingUsage; } set { this._alternateEncodingUsage = value; } } private string ArchiveNameForEvent { get { return ((this._name != null) ? this._name : "(stream)"); } } public int BufferSize { get { return this._BufferSize; } set { this._BufferSize = value; } } public bool CaseSensitiveRetrieval { get { return this._CaseSensitiveRetrieval; } set { if (value != this._CaseSensitiveRetrieval) { this._CaseSensitiveRetrieval = value; this._initEntriesDictionary(); } } } public int CodecBufferSize { get; set; } public string Comment { get { return this._Comment; } set { this._Comment = value; this._contentsChanged = true; } } public HazTech.ZUtil.Zlib.CompressionLevel CompressionLevel { get; set; } public HazTech.ZUtil.Zip.CompressionMethod CompressionMethod { get { return this._compressionMethod; } set { this._compressionMethod = value; } } public int Count { get { return this._entries.Count; } } public static Encoding DefaultEncoding { get { return _defaultEncoding; } } public bool EmitTimesInUnixFormatWhenSaving { get { return this._emitUnixTimes; } set { this._emitUnixTimes = value; } } public bool EmitTimesInWindowsFormatWhenSaving { get { return this._emitNtfsTimes; } set { this._emitNtfsTimes = value; } } public EncryptionAlgorithm Encryption { get { return this._Encryption; } set { if (value == EncryptionAlgorithm.Unsupported) { throw new InvalidOperationException("You may not set Encryption to that value."); } this._Encryption = value; } } public ICollection<ZipEntry> Entries { get { return this._entries.Values; } } public ICollection<ZipEntry> EntriesSorted { get { List<ZipEntry> list = new List<ZipEntry>(); foreach (ZipEntry entry in this.Entries) { list.Add(entry); } StringComparison sc = this.CaseSensitiveRetrieval ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; list.Sort((x, y) => string.Compare(x.FileName, y.FileName, sc)); return list.AsReadOnly(); } } public ICollection<string> EntryFileNames { get { return this._entries.Keys; } } public ExtractExistingFileAction ExtractExistingFile { get; set; } public bool FlattenFoldersOnExtract { get; set; } public bool FullScan { get; set; } public string Info { get { StringBuilder builder = new StringBuilder(); builder.Append(string.Format(" ZipFile: {0}\n", this.Name)); if (!string.IsNullOrEmpty(this._Comment)) { builder.Append(string.Format(" Comment: {0}\n", this._Comment)); } if (this._versionMadeBy != 0) { builder.Append(string.Format(" version made by: 0x{0:X4}\n", this._versionMadeBy)); } if (this._versionNeededToExtract != 0) { builder.Append(string.Format("needed to extract: 0x{0:X4}\n", this._versionNeededToExtract)); } builder.Append(string.Format(" uses ZIP64: {0}\n", this.InputUsesZip64)); builder.Append(string.Format(" disk with CD: {0}\n", this._diskNumberWithCd)); if (this._OffsetOfCentralDirectory == uint.MaxValue) { builder.Append(string.Format(" CD64 offset: 0x{0:X16}\n", this._OffsetOfCentralDirectory64)); } else { builder.Append(string.Format(" CD offset: 0x{0:X8}\n", this._OffsetOfCentralDirectory)); } builder.Append("\n"); foreach (ZipEntry entry in this._entries.Values) { builder.Append(entry.Info); } return builder.ToString(); } } public bool? InputUsesZip64 { get { if (this._entries.Count > 0xfffe) { return true; } foreach (ZipEntry entry in this) { if (entry.Source != ZipEntrySource.ZipFile) { return null; } if (entry._InputUsesZip64) { return true; } } return false; } } public ZipEntry this[int ix] { get { return this.ZipEntriesAsList[ix]; } } public ZipEntry this[string fileName] { get { string key = SharedUtilities.NormalizePathForUseInZipFile(fileName); if (this._entries.ContainsKey(key)) { return this._entries[key]; } key = key.Replace("/", @"\"); if (this._entries.ContainsKey(key)) { return this._entries[key]; } return null; } } private long LengthOfReadStream { get { if (this._lengthOfReadStream == -99L) { this._lengthOfReadStream = this._ReadStreamIsOurs ? SharedUtilities.GetFileLength(this._name) : -1L; } return this._lengthOfReadStream; } } public static Version LibraryVersion { get { return Assembly.GetExecutingAssembly().GetName().Version; } } public int MaxOutputSegmentSize { get { return this._maxOutputSegmentSize; } set { if ((value < 0x10000) && (value != 0)) { throw new ZipException("The minimum acceptable segment size is 65536."); } this._maxOutputSegmentSize = value; } } public string Name { get { return this._name; } set { this._name = value; } } public int NumberOfSegmentsForMostRecentSave { get { return (((int) this._numberOfSegmentsForMostRecentSave) + 1); } } public bool? OutputUsedZip64 { get { return this._OutputUsesZip64; } } public int ParallelDeflateMaxBufferPairs { get { return this._maxBufferPairs; } set { if (value < 4) { throw new ArgumentOutOfRangeException("ParallelDeflateMaxBufferPairs", "Value must be 4 or greater."); } this._maxBufferPairs = value; } } public long ParallelDeflateThreshold { get { return this._ParallelDeflateThreshold; } set { if (((value != 0L) && (value != -1L)) && (value < 0x10000L)) { throw new ArgumentOutOfRangeException("ParallelDeflateThreshold should be -1, 0, or > 65536"); } this._ParallelDeflateThreshold = value; } } public string Password { private get { return this._Password; } set { this._Password = value; if (this._Password == null) { this.Encryption = EncryptionAlgorithm.None; } else if (this.Encryption == EncryptionAlgorithm.None) { this.Encryption = EncryptionAlgorithm.PkzipWeak; } } } [Obsolete("use AlternateEncoding instead.")] public Encoding ProvisionalAlternateEncoding { get { if (this._alternateEncodingUsage == ZipOption.AsNecessary) { return this._alternateEncoding; } return null; } set { this._alternateEncoding = value; this._alternateEncodingUsage = ZipOption.AsNecessary; } } internal Stream ReadStream { get { if ((this._readstream == null) && ((this._readName != null) || (this._name != null))) { this._readstream = File.Open(this._readName ?? this._name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); this._ReadStreamIsOurs = true; } return this._readstream; } } public bool? RequiresZip64 { get { if (this._entries.Count > 0xfffe) { return true; } if (!(this._hasBeenSaved && !this._contentsChanged)) { return null; } foreach (ZipEntry entry in this._entries.Values) { if (entry.RequiresZip64.Value) { return true; } } return false; } } public SetCompressionCallback SetCompression { get; set; } public bool SortEntriesBeforeSaving { get; set; } public TextWriter StatusMessageTextWriter { get { return this._StatusMessageTextWriter; } set { this._StatusMessageTextWriter = value; } } public CompressionStrategy Strategy { get { return this._Strategy; } set { this._Strategy = value; } } public string TempFileFolder { get { return this._TempFileFolder; } set { this._TempFileFolder = value; if ((value != null) && !Directory.Exists(value)) { throw new FileNotFoundException(string.Format("That directory ({0}) does not exist.", value)); } } } [Obsolete("Beginning with v1.9.1.6 of DotNetZip, this property is obsolete. It will be removed in a future version of the library. Your applications should use AlternateEncoding and AlternateEncodingUsage instead.")] public bool UseUnicodeAsNecessary { get { return ((this._alternateEncoding == Encoding.GetEncoding("UTF-8")) && (this._alternateEncodingUsage == ZipOption.AsNecessary)); } set { if (value) { this._alternateEncoding = Encoding.GetEncoding("UTF-8"); this._alternateEncodingUsage = ZipOption.AsNecessary; } else { this._alternateEncoding = DefaultEncoding; this._alternateEncodingUsage = ZipOption.Default; } } } public Zip64Option UseZip64WhenSaving { get { return this._zip64; } set { this._zip64 = value; } } internal bool Verbose { get { return (this._StatusMessageTextWriter != null); } } private Stream WriteStream { get { if (this._writestream == null) { if (this._name == null) { return this._writestream; } if (this._maxOutputSegmentSize != 0) { this._writestream = ZipSegmentedStream.ForWriting(this._name, this._maxOutputSegmentSize); return this._writestream; } SharedUtilities.CreateAndOpenUniqueTempFile(this.TempFileFolder ?? Path.GetDirectoryName(this._name), out this._writestream, out this._temporaryFileName); } return this._writestream; } set { if (value != null) { throw new ZipException("Cannot set the stream to a non-null value."); } this._writestream = null; } } private List<ZipEntry> ZipEntriesAsList { get { if (this._zipEntriesAsList == null) { this._zipEntriesAsList = new List<ZipEntry>(this._entries.Values); } return this._zipEntriesAsList; } } public HazTech.ZUtil.Zip.ZipErrorAction ZipErrorAction { get { if (this.ZipError != null) { this._zipErrorAction = HazTech.ZUtil.Zip.ZipErrorAction.InvokeErrorEvent; } return this._zipErrorAction; } set { this._zipErrorAction = value; if ((this._zipErrorAction != HazTech.ZUtil.Zip.ZipErrorAction.InvokeErrorEvent) && (this.ZipError != null)) { this.ZipError = null; } } } private class ExtractorSettings { public List<string> CopyThroughResources; public SelfExtractorFlavor Flavor; public List<string> ReferencedAssemblies; public List<string> ResourcesToCompile; } } }
marhazk/HazTechClass
AeraClass/External/Ionic.Zip/Ionic/Zip/ZipFile.cs
C#
gpl-2.0
114,310
<?php /** * @package HUBzero CMS * @author Shawn Rice <zooley@purdue.edu> * @copyright Copyright 2005-2009 by Purdue Research Foundation, West Lafayette, IN 47906 * @license http://www.gnu.org/licenses/gpl-2.0.html GPLv2 * * Copyright 2005-2009 by Purdue Research Foundation, West Lafayette, IN 47906. * 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, * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License 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. */ // Check to ensure this file is within the rest of the framework defined('_JEXEC') or die('Restricted access'); /** * Renders a list element */ class ResourcesElementList extends ResourcesElement { /** * Element type * * @access protected * @var string */ protected $_name = 'Select list'; /** * Return any options this element may have * * @param string $name Name of the field * @param string $value Value to check against * @param object $element Data Source Object. * @param string $control_name Control name (eg, control[fieldname]) * @return string HTML */ public function fetchElement($name, $value, &$element, $control_name) { $class = (isset($element->class)) ? 'class="'.$element->class.'"' : 'class="inputbox"'; $options = array(); if (!$element->required) { $options[] = JHTML::_('select.option', '', JText::_('Select...')); } foreach ($element->options as $option) { $val = $option->value; $text = $option->label; $options[] = JHTML::_('select.option', $val, JText::_($text)); } return '<span class="field-wrap">' . JHTML::_('select.genericlist', $options, $control_name.'['.$name.']', $class, 'value', 'text', $value, $control_name.'-'.$name) . '</span>'; } /** * Return any options this element may have * * @param string $name Name of the field * @param string $value Value to check against * @param object $element Data Source Object. * @param string $control_name Control name (eg, control[fieldname]) * @return string HTML */ public function fetchOptions($name, $value, &$element, $control_name) { $html = array(); $k = 0; $html[] = '<table class="admintable" id="'.$name.'">'; $html[] = '<caption>' . JText::_('Lists include blank "Select..." option unless made a required field') . '</caption>'; $html[] = '<tfoot>'; $html[] = '<tr>'; $html[] = '<td colspan="4" class="option-button"><button rel="'.$name.'" class="add-custom-option"><span>' . JText::_('+ Add new option') . '</span></button></td>'; $html[] = '</tr>'; $html[] = '</tfoot>'; $html[] = '<tbody>'; foreach ($element->options as $option) { $html[] = '<tr>'; $html[] = '<td><label for="'. $control_name . '-' . $name . '-label-' . $k . '">' . JText::_('Option') . '</label></td>'; $html[] = '<td><input type="text" size="35" name="' . $control_name . '[' . $name . '][options][' . $k . '][label]" id="'. $control_name . '-' . $name . '-label-' . $k . '" value="' . $option->label . '" /></td>'; $html[] = '</tr>'; $k++; } $html[] = '</tbody>'; $html[] = '</table>'; return implode("\n", $html); } }
pkdash/HubZeroCIWaterPortal
components/com_resources/models/element/list.php
PHP
gpl-2.0
3,797
/** * */ package ca.lc.stimesheet.web.login.userdetails; import java.util.ArrayList; import org.springframework.security.core.authority.SimpleGrantedAuthority; import ca.lc.stimesheet.model.User; /** * @author Marc-Andre Lacroix * */ public class TimesheetUserDetails extends org.springframework.security.core.userdetails.User { private static final long serialVersionUID = 3452519087909202050L; private User internalUser; /** * Creates a Timesheet user details with the actual {@link User} infos. * @param internalUser */ public TimesheetUserDetails(User internalUser) { super(internalUser.getUuid(), "", new ArrayList<SimpleGrantedAuthority>()); this.internalUser = internalUser; } /** * @return the internalUser */ public User getInternalUser() { return internalUser; } }
malacroix/stimesheet
src/main/java/ca/lc/stimesheet/web/login/userdetails/TimesheetUserDetails.java
Java
gpl-2.0
883
module.exports = async ({ client, configJS, Utils: { IsURL }, Constants: { Colors } }, msg, commandData) => { const handleQuit = () => { msg.reply({ embed: { color: Colors.RED, description: `You've exited the profile setup menu!`, }, }); }; if (msg.suffix === "setup") { let m = await msg.reply({ embed: { color: Colors.LIGHT_BLUE, author: { name: `Profile setup for ${msg.author.tag}`, }, title: `Let's setup your GAwesomeBot profile ~~--~~ See it by clicking here`, url: `${configJS.hostingURL}activity/users?q=${encodeURIComponent(`${msg.author.tag}`)}`, thumbnail: { url: msg.author.displayAvatarURL({ size: 64, format: "png" }), }, description: `First of all, do you want to make data such as mutual servers with me and profile fields public?`, footer: { text: msg.author.userDocument.isProfilePublic ? `It's already public now, by answering "yes" you're keeping it that way.` : `It's currently not public, by answering "yes" you're making it public.`, }, }, }); const changes = {}; let message = null; try { message = await client.awaitPMMessage(msg.channel, msg.author); } catch (err) { switch (err.code) { case "AWAIT_QUIT": return handleQuit(); case "AWAIT_EXPIRED": { m = await m.edit({ embed: { color: Colors.LIGHT_ORANGE, description: `You didn't answer in time... We'll keep your profile's publicity the way it currently is.`, footer: { text: `Changed your mind? Type "quit" and restart the process by running "profile setup"`, }, }, }); changes.isProfilePublic = msg.author.userDocument.isProfilePublic; } } } if (message && message.content) changes.isProfilePublic = configJS.yesStrings.includes(message.content.toLowerCase().trim()); m = await msg.reply({ embed: { color: Colors.LIGHT_BLUE, title: `Next, here's your current backround.`, image: { url: IsURL(msg.author.userDocument.profile_background_image) ? msg.author.userDocument.profile_background_image : ``, }, thumbnail: { url: msg.author.displayAvatarURL({ size: 64, format: "png" }), }, author: { name: `Profile setup for ${msg.author.tag}`, }, description: `Your current image URL is: \`\`\`\n${msg.author.userDocument.profile_background_image}\`\`\`\nWould you like a new one? Just paste in a URL.`, footer: { text: `Answer with "." to not change it, or "default" to reset it to the default image. | This message expires in 2 minutes`, }, }, }); try { message = await client.awaitPMMessage(msg.channel, msg.author, 120000); } catch (err) { message = undefined; switch (err.code) { case "AWAIT_QUIT": return handleQuit(); case "AWAIT_EXPIRED": { m = await m.edit({ embed: { color: Colors.LIGHT_ORANGE, description: `You didn't answer in time... We'll keep your current profile backround.`, footer: { text: `Changed your mind? Type "quit" and restart the process by running "profile setup"`, }, }, }); changes.profile_background_image = msg.author.userDocument.profile_background_image; } } } if (message) { if (message.content.toLowerCase().trim() === "default") { changes.profile_background_image = "http://i.imgur.com/8UIlbtg.jpg"; } else if (message.content === ".") { changes.profile_background_image = msg.author.userDocument.profile_background_image; } else if (message.content !== "") { changes.profile_background_image = message.content.trim(); } } m = await msg.reply({ embed: { color: Colors.LIGHT_BLUE, title: `Done! That will be your new picture. 🏖`, description: `Now, can you please tell us a little about yourself...? (max 2000 characters)`, thumbnail: { url: msg.author.displayAvatarURL({ size: 64, format: "png" }), }, author: { name: `Profile setup for ${msg.author.tag}`, }, footer: { text: `Answer with "." to not change your bio, or "none" to reset it | This message expires in 5 minutes`, }, }, }); try { message = await client.awaitPMMessage(msg.channel, msg.author, 300000); } catch (err) { message = undefined; switch (err.code) { case "AWAIT_QUIT": return handleQuit(); case "AWAIT_EXPIRED": { m = await m.edit({ embed: { color: Colors.LIGHT_ORANGE, description: `You didn't answer in time... We'll keep your current bio.`, footer: { text: `Changed your mind? Type "quit" and restart the process by running "profile setup"`, }, }, }); if (msg.author.userDocument.profile_fields && msg.author.userDocument.profile_fields.Bio) changes.Bio = msg.author.userDocument.profile_fields.Bio; } } } if (message && message.content) { if (message.content.trim() === ".") { if (msg.author.userDocument.profile_fields && msg.author.userDocument.profile_fields.Bio) changes.Bio = msg.author.userDocument.profile_fields.Bio; else changes.Bio = null; } else if (message.content.toLowerCase().trim() === "none") { changes.Bio = "delete"; } else { changes.Bio = message.content.trim(); } } const userQueryDocument = msg.author.userDocument.query; userQueryDocument.set("isProfilePublic", changes.isProfilePublic) .set("profile_background_image", changes.profile_background_image); if (!msg.author.userDocument.profile_fields) userQueryDocument.set("profile_fields", {}); if (changes.Bio === "delete") { userQueryDocument.remove("profile_fields.Bio"); } else if (changes.Bio) { userQueryDocument.set("profile_fields.Bio", changes.Bio); } await msg.author.userDocument.save().catch(err => { logger.warn(`Failed to save user data for profile setup.`, { usrid: msg.author.id }, err); }); msg.reply({ embed: { color: Colors.GREEN, title: `You're all set! ~~--~~ Click here to see your profile. 👀`, description: `Thanks for your input.`, url: `${configJS.hostingURL}activity/users?q=${encodeURIComponent(`${msg.author.tag}`)}`, footer: { text: `Changed your mind? Run "profile setup" once again!`, }, }, }); } };
GilbertGobbels/GAwesomeBot
Commands/PM/profile.js
JavaScript
gpl-2.0
6,231
<?php /** * @file node-panel-teaser.tpl.php * * Theme implementation to display a node. * * Available variables: * - $title: the (sanitized) title of the node. * - $content: Node body or teaser depending on $teaser flag. * - $picture: The authors picture of the node output from * theme_user_picture(). * - $date: Formatted creation date (use $created to reformat with * format_date()). * - $links: Themed links like "Read more", "Add new comment", etc. output * from theme_links(). * - $name: Themed username of node author output from theme_username(). * - $node_url: Direct url of the current node. * - $terms: the themed list of taxonomy term links output from theme_links(). * - $submitted: themed submission information output from * theme_node_submitted(). * * Other variables: * - $node: Full node object. Contains data that may not be safe. * - $type: Node type, i.e. story, page, blog, etc. * - $comment_count: Number of comments attached to the node. * - $uid: User ID of the node author. * - $created: Time the node was published formatted in Unix timestamp. * - $zebra: Outputs either "even" or "odd". Useful for zebra striping in * teaser listings. * - $id: Position of the node. Increments each time it's output. * * Node status variables: * - $teaser: Flag for the teaser state. * - $page: Flag for the full page state. * - $promote: Flag for front page promotion state. * - $sticky: Flags for sticky post setting. * - $status: Flag for published status. * - $comment: State of comment settings for the node. * - $readmore: Flags true if the teaser content of the node cannot hold the * main body content. * - $is_front: Flags true when presented in the front page. * - $logged_in: Flags true when the current user is a logged-in member. * - $is_admin: Flags true when the current user is an administrator. * * @see template_preprocess() * @see template_preprocess_node() */ ?> <?php print $content ?> <p class="link"><a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?></a></p>
aakb/community
sites/all/themes/kerberos/templates/node-panel-teaser.tpl.php
PHP
gpl-2.0
2,091
<?php /** * Climbuddy API namespace * * @package CB\Api */ namespace CB\Api; /** * API layer controller * * @author Bojan Hribernik <bojan.hribernik@gmail.com> * @version 1.0 * @package CB\Api */ class Layer extends AbstractController { /** * Read layers * * @access public * @return array */ public function read() { return $this->success('Read', []); } /** * Create layer(s) * * @access public * @param array $layers * @return array */ public function create($layers) { try { // must be logged in if (null === $User = $this->getSessionUser()) { return $this->error('You must be signed-in to perform this action!'); } // get entity manager $em = $this->getEntityManager(); // store entities $entities = []; // loop through all layers foreach ($layers as $layer) { // remember client id if (!isset($layer['id'])) { return $this->error('Invalid layer clientId!'); } $clientId = $layer['id']; // must have file if (!isset($layer['fileId']) || null === $File = $em->getRepository('\CB\Entity\File')->find($layer['fileId'])) { return $this->error('Unable to find layer file!'); } // must have route if (!isset($layer['routeId']) || null === $Route = $em->getRepository('\CB\Entity\Route')->find($layer['routeId'])) { return $this->error('Unable to find layer route!'); } // create new layer $Layer = new \CB\Entity\Layer(); $Layer->setValues($layer); $Layer->setUser($User); $Layer->setFile($File); $Layer->setRoute($Route); // persist layer $em->persist($Layer); // store layers by clientId $entities[$clientId] = $Layer; } // save changes $em->flush(); // build response data $data = []; foreach ($entities as $clientId => $Layer) { $layer = $Layer->getValues(); $layer['clientId'] = $clientId; $data[] = $layer; } return $this->success('Create', $data); } catch (\Exception $e) { return $this->error($e->getMessage()); } } /** * Update layer(s) * * @access public * @param array $layers * @return array */ public function update($layers) { try { // must be logged in if (null === $User = $this->getSessionUser()) { return $this->error('You must be signed-in to perform this action!'); } // get entity manager $em = $this->getEntityManager(); // store entities $entities = []; // loop through all layers foreach ($layers as $layer) { // load layer if (!isset($layer['id']) || null === $Layer = $em->getRepository('\CB\Entity\Layer')->find($layer['id'])) { return $this->error('Unable to find layer to update!'); } $layerId = $layer['id']; // update values $Layer->setValues($layer); // persist layer $em->persist($Layer); // store layers by layerId $entities[$layerId] = $Layer; } // save changes $em->flush(); // build response data $data = []; foreach ($entities as $layerId => $Layer) { $data[] = $Layer->getValues(); } return $this->success('Update', $data); } catch (\Exception $e) { return $this->error($e->getMessage()); } } /** * Destroy layer(s) * * @access public * @param array $layers * @return array */ public function destroy($layers) { try { // must be logged in if (null === $User = $this->getSessionUser()) { return $this->error('You must be signed-in to perform this action!'); } // get entity manager $em = $this->getEntityManager(); // loop through all layers foreach ($layers as $layer) { // load layer if (!isset($layer['id']) || null === $Layer = $em->getRepository('\CB\Entity\Layer')->find($layer['id'])) { return $this->error('Unable to find layer to destroy!'); } // remove layer $em->remove($Layer); } // save changes $em->flush(); return $this->success('Destroy'); } catch (\Exception $e) { return $this->error($e->getMessage()); } } }
terloger/cb5
api/CB/Api/Layer.php
PHP
gpl-2.0
5,995
# pylint: disable = C0301 from bs4 import BeautifulSoup from urllib2 import urlopen import pandas as pd pos_idx_map = { 'qb': 2, 'rb': 3, 'wr': 4, 'te': 5, } def make_url(pos, wk): ii = pos_idx_map[pos] fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \ % (wk, ii) return fstr def html2df(soup): table = soup.find('table') headers = [header.text.lower() for header in table.find_all('th')] rows = [] for row in table.find_all('tr'): rows.append([val.text.encode('utf8') for val in row.find_all('td')]) rows = [rr for rr in rows if len(rr) > 0] df = pd.DataFrame.from_records(rows) df.columns = headers return df def position_html_local(posn): dflist = [] for ii in range(1, 17): fname = '%s%s.html' % (posn, ii) with open(fname) as f: df = html2df(BeautifulSoup(f)) df['wk'] = ii df.columns = header_clean(df.columns, posn) dflist.append(df) return pd.concat(dflist) def position_html(posn): dflist = [] for ii in range(1, 17): fname = make_url(posn, ii) df = html2df(BeautifulSoup(urlopen(fname))) df['wk'] = ii df.columns = header_clean(df.columns, posn) dflist.append(df) return pd.concat(dflist) pos_header_suffixes = { 'qb': ['_pass', '_rush'], 'rb': ['_rush', '_recv'], 'wr': ['_recv'], 'te': ['_recv'], } exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points', 'wk', 'fum', 'lost', 'qb rating'] def header_clean(header, posn): res = [] if posn in pos_header_suffixes: suffixes = pos_header_suffixes[posn] seen_dict = {hh: 0 for hh in header} for hh in header: if not hh in exclude_cols: hres = hh + suffixes[seen_dict[hh]] seen_dict[hh] += 1 res.append(hres) else: res.append(hh) else: res = header return res if __name__ == '__main__': data_all = {} for pp in ['qb', 'wr', 'rb', 'te']: data_all[pp] = position_html_local(pp) data_all[pp].to_pickle('%s.pkl' % pp)
yikelu/nfl_fantasy_data
htmls2csvs.py
Python
gpl-2.0
2,265
package edu.asu.spring.quadriga.dao.profile.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import edu.asu.spring.quadriga.dao.impl.BaseDAO; import edu.asu.spring.quadriga.dao.profile.IProfileManagerDAO; import edu.asu.spring.quadriga.domain.IProfile; import edu.asu.spring.quadriga.domain.factories.IProfileFactory; import edu.asu.spring.quadriga.dto.QuadrigaUserprofileDTO; import edu.asu.spring.quadriga.dto.QuadrigaUserprofileDTOPK; import edu.asu.spring.quadriga.exceptions.QuadrigaStorageException; import edu.asu.spring.quadriga.web.profile.impl.SearchResultBackBean; /** * this class manages addition, deletion, retrieval of the records for user * profile table * * @author rohit pendbhaje * */ @Repository public class ProfileManagerDAO extends BaseDAO<QuadrigaUserprofileDTO> implements IProfileManagerDAO { @Autowired private SessionFactory sessionFactory; @Autowired private IProfileFactory profileFactory; /** * adds records in database table for the profile page * * @param name * name of the loggedin user serviceId id of the service from * which records are added resultBackBean this instance contains * all the searchresult information selected by user * @throws QuadrigaStorageException * @author rohit pendbhaje * */ @Override public void addUserProfileDBRequest(String name, String serviceId, SearchResultBackBean resultBackBean) throws QuadrigaStorageException { try { Date date = new Date(); QuadrigaUserprofileDTO userProfile = new QuadrigaUserprofileDTO(); QuadrigaUserprofileDTOPK userProfileKey = new QuadrigaUserprofileDTOPK( name, serviceId, resultBackBean.getId()); userProfile.setQuadrigaUserprofileDTOPK(userProfileKey); userProfile.setProfilename(resultBackBean.getWord()); userProfile.setDescription(resultBackBean.getDescription()); userProfile.setQuadrigaUserDTO(getUserDTO(name)); userProfile.setCreatedby(name); userProfile.setCreateddate(date); userProfile.setUpdatedby(name); userProfile.setUpdateddate(date); sessionFactory.getCurrentSession().save(userProfile); } catch (HibernateException ex) { throw new QuadrigaStorageException("System error", ex); } } /** * retrieves records from database * * @param loggedinUser * @return list of searchresultbackbeans * @throws QuadrigaStorageException * @author rohit pendbhaje * */ @SuppressWarnings("unchecked") @Override public List<IProfile> getUserProfiles(String loggedinUser) throws QuadrigaStorageException { List<IProfile> userProfiles = new ArrayList<IProfile>(); try { Query query = sessionFactory.getCurrentSession().getNamedQuery( "QuadrigaUserprofileDTO.findByUsername"); query.setParameter("username", loggedinUser); List<QuadrigaUserprofileDTO> userProfileList = query.list(); for (QuadrigaUserprofileDTO userProfile : userProfileList) { IProfile profile = profileFactory.createProfile(); profile.setProfileId(userProfile .getQuadrigaUserprofileDTOPK().getProfileid()); profile.setServiceId(userProfile .getQuadrigaUserprofileDTOPK().getServiceid()); profile.setDescription(userProfile .getDescription()); profile.setProfilename(userProfile.getProfilename()); userProfiles.add(profile); } } catch (Exception ex) { throw new QuadrigaStorageException(); } return userProfiles; } /** * deletes profile record from table for particular profileid * * @param username * name of loggedin user serviceid id of the service * corresponding to the record profileId id of the profile for * which record is to be deleted * @throws QuadrigaStorageException * @author rohit pendbhaje * */ @Override public void deleteUserProfileDBRequest(String username, String serviceid, String profileId) throws QuadrigaStorageException { try { QuadrigaUserprofileDTOPK userProfileKey = new QuadrigaUserprofileDTOPK( username, serviceid, profileId); QuadrigaUserprofileDTO userProfile = (QuadrigaUserprofileDTO) sessionFactory .getCurrentSession().get(QuadrigaUserprofileDTO.class, userProfileKey); sessionFactory.getCurrentSession().delete(userProfile); } catch (Exception ex) { throw new QuadrigaStorageException(); } } /** * retrieves serviceid from table of particular profileid * * @param profileId * id of the profile for which record is to be deleted * @throws QuadrigaStorageException * @author rohit pendbhaje * */ @Override public String retrieveServiceIdRequest(String profileid) throws QuadrigaStorageException { String serviceid = null; try { Query query = sessionFactory.getCurrentSession().getNamedQuery( "QuadrigaUserprofileDTO.findByProfileid"); query.setParameter("profileid", profileid); List<QuadrigaUserprofileDTO> userprofileList = query.list(); for (QuadrigaUserprofileDTO userprofile : userprofileList) { serviceid = userprofile.getQuadrigaUserprofileDTOPK() .getServiceid(); } } catch (Exception e) { throw new QuadrigaStorageException("sorry"); } return serviceid; } @Override public QuadrigaUserprofileDTO getDTO(String id) { return getDTO(QuadrigaUserprofileDTO.class, id); } }
diging/quadriga
Quadriga/src/main/java/edu/asu/spring/quadriga/dao/profile/impl/ProfileManagerDAO.java
Java
gpl-2.0
6,447
// ============================================================================= // Module to configure an ExpressJS web server // ============================================================================= // Requires // { // "express": "4.13.3", // "cookie-parser": "1.4.0", // "morgan": "1.6.1", // "body-parser" : "1.14.1", // "express-session" : "1.12.1", // "method-override" : "2.3.5" // } var express = require('express'); var cookieParser = require('cookie-parser'); var methodOverride = require('method-override'); var http = require('http'); var bodyParser = require('body-parser'); var morgan = require('morgan'); var app = express(); app.use(morgan('dev')); // log every request to the console app.use(cookieParser()); // read cookies (needed for auth) app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); module.exports = { app : app }
apycazo/nodes
modules/express-cfg.js
JavaScript
gpl-2.0
971
(function ($) { /** * Attaches double-click behavior to toggle full path of Krumo elements. */ Drupal.behaviors.devel = { attach: function (context, settings) { // Add hint to footnote $('.krumo-footnote .krumo-call').once().before('<img style="vertical-align: middle;" title="Click to expand. Double-click to show path." src="' + settings.basePath + 'misc/help.png"/>'); var krumo_name = []; var krumo_type = []; function krumo_traverse(el) { krumo_name.push($(el).html()); krumo_type.push($(el).siblings('em').html().match(/\w*/)[0]); if ($(el).closest('.krumo-nest').length > 0) { krumo_traverse($(el).closest('.krumo-nest').prev().find('.krumo-name')); } } $('.krumo-child > div:first-child', context).dblclick( function(e) { if ($(this).find('> .krumo-php-path').length > 0) { // Remove path if shown. $(this).find('> .krumo-php-path').remove(); } else { // Get elements. krumo_traverse($(this).find('> a.krumo-name')); // Create path. var krumo_path_string = ''; for (var i = krumo_name.length - 1; i >= 0; --i) { // Start element. if ((krumo_name.length - 1) == i) krumo_path_string += '$' + krumo_name[i]; if (typeof krumo_name[(i-1)] !== 'undefined') { if (krumo_type[i] == 'Array') { krumo_path_string += "["; if (!/^\d*$/.test(krumo_name[(i-1)])) krumo_path_string += "'"; krumo_path_string += krumo_name[(i-1)]; if (!/^\d*$/.test(krumo_name[(i-1)])) krumo_path_string += "'"; krumo_path_string += "]"; } if (krumo_type[i] == 'Object') krumo_path_string += '->' + krumo_name[(i-1)]; } } $(this).append('<div class="krumo-php-path" style="font-family: Courier, monospace; font-weight: bold;">' + krumo_path_string + '</div>'); // Reset arrays. krumo_name = []; krumo_type = []; } } ); } }; })(jQuery); ; /** * Cookie plugin 1.0 * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ jQuery.cookie=function(b,j,m){if(typeof j!="undefined"){m=m||{};if(j===null){j="";m.expires=-1}var e="";if(m.expires&&(typeof m.expires=="number"||m.expires.toUTCString)){var f;if(typeof m.expires=="number"){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000))}else{f=m.expires}e="; expires="+f.toUTCString()}var l=m.path?"; path="+(m.path):"";var g=m.domain?"; domain="+(m.domain):"";var a=m.secure?"; secure":"";document.cookie=[b,"=",encodeURIComponent(j),e,l,g,a].join("")}else{var d=null;if(document.cookie&&document.cookie!=""){var k=document.cookie.split(";");for(var h=0;h<k.length;h++){var c=jQuery.trim(k[h]);if(c.substring(0,b.length+1)==(b+"=")){d=decodeURIComponent(c.substring(b.length+1));break}}}return d}}; ; (function ($) { Drupal.ModuleFilter = {}; Drupal.ModuleFilter.explode = function(string) { var queryArray = string.match(/([a-zA-Z]+\:(\w+|"[^"]+")*)|\w+|"[^"]+"/g); if (!queryArray) { queryArray = new Array(); } var i = queryArray.length; while (i--) { queryArray[i] = queryArray[i].replace(/"/g, ""); } return queryArray; }; Drupal.ModuleFilter.getState = function(key) { if (!Drupal.ModuleFilter.state) { Drupal.ModuleFilter.state = {}; var cookie = $.cookie('DrupalModuleFilter'); var query = cookie ? cookie.split('&') : []; if (query) { for (var i in query) { // Extra check to avoid js errors in Chrome, IE and Safari when // combined with JS like twitter's widget.js. // See http://drupal.org/node/798764. if (typeof(query[i]) == 'string' && query[i].indexOf('=') != -1) { var values = query[i].split('='); if (values.length === 2) { Drupal.ModuleFilter.state[values[0]] = values[1]; } } } } } return Drupal.ModuleFilter.state[key] ? Drupal.ModuleFilter.state[key] : false; }; Drupal.ModuleFilter.setState = function(key, value) { var existing = Drupal.ModuleFilter.getState(key); if (existing != value) { Drupal.ModuleFilter.state[key] = value; var query = []; for (var i in Drupal.ModuleFilter.state) { query.push(i + '=' + Drupal.ModuleFilter.state[i]); } $.cookie('DrupalModuleFilter', query.join('&'), { expires: 7, path: '/' }); } }; Drupal.ModuleFilter.Filter = function(element, selector, options) { var self = this; this.element = element; this.text = $(this.element).val(); this.settings = Drupal.settings.moduleFilter; this.selector = selector; this.options = $.extend({ delay: 500, striping: false, childSelector: null, empty: Drupal.t('No results'), rules: new Array() }, options); if (this.options.wrapper == undefined) { this.options.wrapper = $(self.selector).parent(); } // Add clear button. this.element.after('<div class="module-filter-clear"><a href="#" class="js-hide">' + Drupal.t('clear') + '</a></div>'); if (this.text) { $('.module-filter-clear a', this.element.parent()).removeClass('js-hide'); } $('.module-filter-clear a', this.element.parent()).click(function() { self.element.val(''); self.text = ''; delete self.queries; self.applyFilter(); self.element.focus(); $(this).addClass('js-hide'); return false; }); this.updateQueries = function() { var queryStrings = Drupal.ModuleFilter.explode(self.text); self.queries = new Array(); for (var i in queryStrings) { var query = { operator: 'text', string: queryStrings[i] }; if (self.operators != undefined) { // Check if an operator is possibly used. if (queryStrings[i].indexOf(':') > 0) { // Determine operator used. var args = queryStrings[i].split(':', 2); var operator = args.shift(); if (self.operators[operator] != undefined) { query.operator = operator; query.string = args.shift(); } } } query.string = query.string.toLowerCase(); self.queries.push(query); } if (self.queries.length <= 0) { // Add a blank string query. self.queries.push({ operator: 'text', string: '' }); } }; this.applyFilter = function() { self.results = new Array(); self.updateQueries(); if (self.index == undefined) { self.buildIndex(); } self.element.trigger('moduleFilter:start'); $.each(self.index, function(key, item) { var $item = item.element; for (var i in self.queries) { var query = self.queries[i]; if (query.operator == 'text') { if (item.text.indexOf(query.string) < 0) { continue; } } else { var func = self.operators[query.operator]; if (!(func(query.string, self, item))) { continue; } } var rulesResult = self.processRules(item); if (rulesResult !== false) { return true; } } $item.addClass('js-hide'); }); self.element.trigger('moduleFilter:finish', { results: self.results }); if (self.options.striping) { self.stripe(); } if (self.results.length > 0) { self.options.wrapper.find('.module-filter-no-results').remove(); } else { if (!self.options.wrapper.find('.module-filter-no-results').length) { self.options.wrapper.append($('<p class="module-filter-no-results"/>').text(self.options.empty)); }; } }; self.element.keyup(function(e) { switch (e.which) { case 13: if (self.timeOut) { clearTimeout(self.timeOut); } self.applyFilter(); break; default: if (self.text != $(this).val()) { if (self.timeOut) { clearTimeout(self.timeOut); } self.text = $(this).val(); if (self.text) { self.element.parent().find('.module-filter-clear a').removeClass('js-hide'); } else { self.element.parent().find('.module-filter-clear a').addClass('js-hide'); } self.element.trigger('moduleFilter:keyup'); self.timeOut = setTimeout(self.applyFilter, self.options.delay); } break; } }); self.element.keypress(function(e) { if (e.which == 13) e.preventDefault(); }); }; Drupal.ModuleFilter.Filter.prototype.buildIndex = function() { var self = this; var index = new Array(); $(this.selector).each(function(i) { var text = (self.options.childSelector) ? $(self.options.childSelector, this).text() : $(this).text(); var item = { key: i, element: $(this), text: text.toLowerCase() }; for (var j in self.options.buildIndex) { var func = self.options.buildIndex[j]; item = $.extend(func(self, item), item); } $(this).data('indexKey', i); index.push(item); delete item; }); this.index = index; }; Drupal.ModuleFilter.Filter.prototype.processRules = function(item) { var self = this; var $item = item.element; var rulesResult = true; if (self.options.rules.length > 0) { for (var i in self.options.rules) { var func = self.options.rules[i]; rulesResult = func(self, item); if (rulesResult === false) { break; } } } if (rulesResult !== false) { $item.removeClass('js-hide'); self.results.push(item); } return rulesResult; }; Drupal.ModuleFilter.Filter.prototype.stripe = function() { var self = this; var flip = { even: 'odd', odd: 'even' }; var stripe = 'odd'; $.each(self.index, function(key, item) { if (!item.element.hasClass('js-hide')) { item.element.removeClass('odd even') .addClass(stripe); stripe = flip[stripe]; } }); }; $.fn.moduleFilter = function(selector, options) { var filterInput = this; filterInput.parents('.module-filter-inputs-wrapper').show(); if (Drupal.settings.moduleFilter.setFocus) { filterInput.focus(); } filterInput.data('moduleFilter', new Drupal.ModuleFilter.Filter(this, selector, options)); }; })(jQuery); ; (function($) { Drupal.behaviors.moduleFilterUpdateStatus = { attach: function(context) { $('#module-filter-update-status-form').once('update-status', function() { var filterInput = $('input[name="module_filter[name]"]', context); filterInput.moduleFilter('table.update > tbody > tr', { wrapper: $('table.update:first').parent(), delay: 300, childSelector: 'div.project a', rules: [ function(moduleFilter, item) { switch (moduleFilter.options.show) { case 'all': return true; case 'updates': if (item.state == 'warning' || item.state == 'error') { return true; } break; case 'security': if (item.state == 'error') { return true; } break; case 'ignore': if (item.state == 'ignored') { return true; } break; case 'unknown': if (item.state == 'unknown') { return true; } break; } return false; } ], buildIndex: [ function(moduleFilter, item) { if ($('.version-status', item.element).text() == Drupal.t('Ignored from settings')) { item.state = 'ignored'; return item; } if (item.element.is('.ok')) { item.state = 'ok'; } else if (item.element.is('.warning')) { item.state = 'warning'; } else if (item.element.is('.error')) { item.state = 'error'; } else if (item.element.is('.unknown')) { item.state = 'unknown'; } return item; } ], show: $('#edit-module-filter-show input[name="module_filter[show]"]', context).val() }); var moduleFilter = filterInput.data('moduleFilter'); if (Drupal.settings.moduleFilter.rememberUpdateState) { var updateShow = Drupal.ModuleFilter.getState('updateShow'); if (updateShow) { moduleFilter.options.show = updateShow; $('#edit-module-filter-show input[name="module_filter[show]"][value="' + updateShow + '"]', context).click(); } } $('#edit-module-filter-show input[name="module_filter[show]"]', context).change(function() { moduleFilter.options.show = $(this).val(); Drupal.ModuleFilter.setState('updateShow', moduleFilter.options.show); moduleFilter.applyFilter(); }); moduleFilter.element.bind('moduleFilter:start', function() { $('table.update').each(function() { $(this).show().prev('h3').show(); }); }); moduleFilter.element.bind('moduleFilter:finish', function(e, data) { $('table.update').each(function() { var $table = $(this); if ($('tbody tr', $(this)).filter(':visible').length == 0) { $table.hide().prev('h3').hide(); } }); }); moduleFilter.element.bind('moduleFilter:keyup', function() { if (moduleFilter.clearOffset == undefined) { moduleFilter.inputWidth = filterInput.width(); moduleFilter.clearOffset = moduleFilter.element.parent().find('.module-filter-clear a').width(); } if (moduleFilter.text) { filterInput.width(moduleFilter.inputWidth - moduleFilter.clearOffset - 5).parent().css('margin-right', moduleFilter.clearOffset + 5); } else { filterInput.width(moduleFilter.inputWidth).parent().css('margin-right', 0); } }); moduleFilter.element.parent().find('.module-filter-clear a').click(function() { filterInput.width(moduleFilter.inputWidth).parent().css('margin-right', 0); }); moduleFilter.applyFilter(); }); } }; })(jQuery); ;
tapclicks/tapanalytics
sites/default/files/js/js_-uAWVNNLs-CDqxUul18yVdZpeIHUZse1JmT6XcSAYNU.js
JavaScript
gpl-2.0
15,031
#region License /* * Copyright (C) 1999-2021 John Källén. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #endregion using Reko.Core; using System; namespace Reko.Gui { public class SelectionChangedEventArgs : EventArgs { private AddressRange range; public SelectionChangedEventArgs(AddressRange range) { this.range = range; } public AddressRange AddressRange { get { return range; } } } /// <summary> /// The ILowLevelViewService can be used by user interface methods /// to display a memory dump and raw disassembly of a Program. /// </summary> public interface ILowLevelViewService { /// <summary> /// Show a low level window for the specified <paramref name="program"/>. /// If the window is already visible, bring it to the foreground. /// </summary> /// <param name="program">Program whose low-level details are to /// be shown.</param> void ShowWindow(Program program); /// <summary> /// Show a low level window for the specified <paramref name="program"/>, and /// display the first few bytes. /// </summary> /// <param name="program">Program whose low-level details are to /// be shown.</param> void ViewImage(Program program); /// <summary> /// Show a low-level window for the specified <paramref name="program"/>, and /// make the address <paramref name="addr"/> visible on screen. /// </summary> /// <param name="program">Program whose low-level details are to /// be shown.</param> /// <param name="addr">Address to show.</param> void ShowMemoryAtAddress(Program program, Address addr); } }
nemerle/reko
src/Gui/ILowLevelViewService.cs
C#
gpl-2.0
2,447
<?php /** * The file that defines the core plugin class. * * A class definition that includes attributes and functions used across both the * public-facing side of the site and the admin area. * * @see https://github.com/gr33k01 * @since 1.0.0 */ /** * The core plugin class. * * This is used to define internationalization, admin-specific hooks, and * public-facing site hooks. * * Also maintains the unique identifier of this plugin as well as the current * version of the plugin. * * @since 1.0.0 * * @author Nate Hobi <nate.hobi@gmail.com> */ class Leo_Department_Manager { /** * The loader that's responsible for maintaining and registering all hooks that power * the plugin. * * @since 1.0.0 * * @var Leo_Department_Manager_Loader maintains and registers all hooks for the plugin */ protected $loader; /** * The unique identifier of this plugin. * * @since 1.0.0 * * @var string the string used to uniquely identify this plugin */ protected $plugin_name; /** * The current version of the plugin. * * @since 1.0.0 * * @var string the current version of the plugin */ protected $version; /** * Define the core functionality of the plugin. * * Set the plugin name and the plugin version that can be used throughout the plugin. * Load the dependencies, define the locale, and set the hooks for the admin area and * the public-facing side of the site. * * @since 1.0.0 */ public function __construct() { $this->plugin_name = 'leo-department-manager'; $this->version = '1.0.0'; $this->load_dependencies(); $this->set_locale(); $this->define_admin_hooks(); $this->define_public_hooks(); } /** * Load the required dependencies for this plugin. * * Include the following files that make up the plugin: * * - Leo_Department_Manager_Loader. Orchestrates the hooks of the plugin. * - Leo_Department_Manager_i18n. Defines internationalization functionality. * - Leo_Department_Manager_Admin. Defines all hooks for the admin area. * - Leo_Department_Manager_Public. Defines all hooks for the public side of the site. * * Create an instance of the loader which will be used to register the hooks * with WordPress. * * @since 1.0.0 */ private function load_dependencies() { /** * The class responsible for orchestrating the actions and filters of the * core plugin. */ require_once plugin_dir_path(dirname(__FILE__)).'includes/class-leo-department-manager-loader.php'; /** * The class responsible for defining internationalization functionality * of the plugin. */ require_once plugin_dir_path(dirname(__FILE__)).'includes/class-leo-department-manager-i18n.php'; /** * The class responsible for defining all actions that occur in the admin area. */ require_once plugin_dir_path(dirname(__FILE__)).'admin/class-leo-department-manager-admin.php'; /** * The class responsible for defining all actions that occur in the public-facing * side of the site. */ require_once plugin_dir_path(dirname(__FILE__)).'public/class-leo-department-manager-public.php'; $this->loader = new Leo_Department_Manager_Loader(); } /** * Define the locale for this plugin for internationalization. * * Uses the Leo_Department_Manager_i18n class in order to set the domain and to register the hook * with WordPress. * * @since 1.0.0 */ private function set_locale() { $plugin_i18n = new Leo_Department_Manager_i18n(); $this->loader->add_action('plugins_loaded', $plugin_i18n, 'load_plugin_textdomain'); } /** * Register all of the hooks related to the admin area functionality * of the plugin. * * @since 1.0.0 */ private function define_admin_hooks() { $plugin_admin = new Leo_Department_Manager_Admin($this->get_plugin_name(), $this->get_version()); // Display admin page // $this->loader->add_action( 'admin_menu', $plugin_admin, 'display_admin_page' ); // Scripts and styles $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_styles'); $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts'); // Register settings $this->loader->add_action('admin_init', $plugin_admin, 'register_settings'); // Additional profile fields $this->loader->add_action('user_new_form', $plugin_admin, 'modify_user_fields'); $this->loader->add_action('show_user_profile', $plugin_admin, 'modify_user_fields'); $this->loader->add_action('edit_user_profile', $plugin_admin, 'modify_user_fields'); $this->loader->add_action('personal_options_update', $plugin_admin, 'save_user_fields'); $this->loader->add_action('edit_user_profile_update', $plugin_admin, 'save_user_fields'); $this->loader->add_action('user_register', $plugin_admin, 'save_user_fields'); // Ajax functions $this->loader->add_action('wp_ajax_get_departments', $plugin_admin, 'get_departments'); $this->loader->add_action('wp_ajax_get_users', $plugin_admin, 'get_users'); $this->loader->add_action('wp_ajax_remove_department', $plugin_admin, 'remove_department'); $this->loader->add_action('wp_ajax_update_user_department', $plugin_admin, 'update_user_department'); // Admin post functions $this->loader->add_action('admin_post_toggle_active_department', $plugin_admin, 'toggle_active_department'); $this->loader->add_action('admin_post_toggle_department_head', $plugin_admin, 'toggle_department_head'); $this->loader->add_action('admin_post_nopriv_toggle_department_head', $plugin_admin, 'toggle_department_head'); $this->loader->add_action('admin_post_delete_user', $plugin_admin, 'delete_user'); $this->loader->add_action('admin_post_nopriv_delete_user', $plugin_admin, 'delete_user'); $this->loader->add_action('admin_notices', $plugin_admin, 'show_job_running_message'); // Custom Post Type List Column stuff $this->loader->add_filter('manage_department_posts_columns', $plugin_admin, 'post_columns'); $this->loader->add_action('manage_department_posts_custom_column', $plugin_admin, 'custom_post_column_types', 10, 2); $this->loader->add_action('add_meta_boxes_department', $plugin_admin, 'department_edit_markup'); $this->loader->add_action('save_post', $plugin_admin, 'handle_save'); } /** * Register all of the hooks related to the public-facing functionality * of the plugin. * * @since 1.0.0 */ private function define_public_hooks() { $plugin_public = new Leo_Department_Manager_Public($this->get_plugin_name(), $this->get_version()); $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_styles'); $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_scripts'); $this->loader->add_action('single_template', $plugin_public, 'department_single_template'); $this->loader->add_action('archive_template', $plugin_public, 'department_list_template'); // Admin post functions $this->loader->add_action('admin_post_create_new_dept_user', $plugin_public, 'create_new_dept_user'); $this->loader->add_action('admin_post_nopriv_create_new_dept_user', $plugin_public, 'create_new_dept_user'); } /** * Run the loader to execute all of the hooks with WordPress. * * @since 1.0.0 */ public function run() { $this->loader->run(); } /** * The name of the plugin used to uniquely identify it within the context of * WordPress and to define internationalization functionality. * * @since 1.0.0 * * @return string the name of the plugin */ public function get_plugin_name() { return $this->plugin_name; } /** * The reference to the class that orchestrates the hooks with the plugin. * * @since 1.0.0 * * @return Leo_Department_Manager_Loader orchestrates the hooks of the plugin */ public function get_loader() { return $this->loader; } /** * Retrieve the version number of the plugin. * * @since 1.0.0 * * @return string the version number of the plugin */ public function get_version() { return $this->version; } }
LeoTraining/Leo-Department-Manager
includes/class-leo-department-manager.php
PHP
gpl-2.0
8,877
using System; using MetaphysicsIndustries.Ligra.RenderItems; using MetaphysicsIndustries.Solus.Commands; namespace MetaphysicsIndustries.Ligra.Commands { public class CdCommand : Command { public static readonly CdCommand Value = new CdCommand(); public override string Name => "cd"; public override string DocString => @"cd - Show or change the current directory Show the current directory: cd Change the current directory: cd <path> path A path as a sequence of characters (not enclosed in quotes). It can be an absolute or relative path. The format and semantics of the path string is determined by the underlying operating system. "; public override void Execute(string input, string[] args, LigraEnvironment env, ICommandData data, ILigraUI control) { if (args.Length <= 1) { //print the current directory string dir = System.IO.Directory.GetCurrentDirectory(); control.AddRenderItem( new InfoItem(dir, control.DrawSettings.Font)); } else if (!System.IO.Directory.Exists(args[1])) { control.AddRenderItem( new ErrorItem(input, "Parameter must be a folder name", control.DrawSettings.Font, LBrush.Red, input.IndexOf(args[1]))); } else { //set the current directory string dir = args[1]; try { System.IO.Directory.SetCurrentDirectory(dir); control.AddRenderItem( new InfoItem( $"Directory changed to \"{dir}\"", control.DrawSettings.Font)); } catch (Exception e) { control.AddRenderItem( new ErrorItem( input, $"There was an error: \r\n{e}", control.DrawSettings.Font, LBrush.Red)); } } } } }
izrik/Ligra
Commands/CdCommand.cs
C#
gpl-2.0
2,200
<?php header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); require_once(__DIR__."/../server/tools.php"); require_once(__DIR__."/../server/auth/Config.php"); require_once(__DIR__."/../server/auth/AuthManager.php"); $config =Config::getInstance(); $am = AuthManager::getInstance("Public::finales_equipos"); if ( ! $am->allowed(ENABLE_PUBLIC)) { include_once("unregistered.php"); return 0;} ?> <!-- pbmenu_finales_equipos.php Copyright 2013-2018 by Juan Antonio Martinez ( juansgaviota at gmail dot com ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. --> <!-- Acceso publico desde menu a clasificacion final en pruebas por equipos --> <div id="pb_finales-panel"> <div id="pb_finales-layout" style="width:100%"> <div id="pb_finales-Cabecera" style="height:20%;" class="pb_floatingheader" data-options="region:'north',split:false,collapsed:false"> <a id="pb_back-link" class="easyui-linkbutton" onClick="pbmenu_expandMenu(true);" href="#" style="float:left"> <img id="pb_back-logo" src="../images/backtomenu.png" width="40" /> </a>&nbsp; <a id="pb_header-link" class="easyui-linkbutton" onClick="updateFinales(0,workingData.datosRonda);" href="#" style="float:left"> <img id="pb_header-logo" src="../images/logos/agilitycontest.png" width="40" /> </a> <span style="float:left;padding:5px" id="pb_header-infocabecera"><?php _e('Header'); ?></span> <span style="float:right" id="pb_header-texto"> <?php _e('Final scores'); ?><br/> <span id="enumerateFinales" style="width:200px"></span> </span> <!-- Datos de TRS y TRM --> <?php include(__DIR__ . "/../console/templates/final_rounds_data.inc.php"); ?> </div> <div id="pb_table" data-options="region:'center'" class="scores_table"> <?php include(__DIR__ . "/../console/templates/final_teams.inc.php"); ?> </div> <div id="pb_finales-footer" data-options="region:'south',split:false" style="height:10%;" class="pb_floatingfooter"> <span id="pb_footer-footerData"></span> </div> </div> </div> <!-- finales-window --> <script type="text/javascript"> addTooltip($('#pb_header-link').linkbutton(),'<?php _e("Update scores"); ?>'); addTooltip($('#pb_back-link').linkbutton(),'<?php _e("Back to contest menu"); ?>'); $('#pb_finales-layout').layout({fit:true}); $('#pb_finales-panel').panel({ fit:true, noheader:true, border:false, closable:false, collapsible:false, collapsed:false, resizable:true }); // fire autorefresh if configured and user has no expanded rows function pbmenu_updateFinalesEquipos() { // stop refresh is request to do so var rtime=parseInt(ac_config.web_refreshtime); if ((rtime===0) || (pb_config.Timeout===null) ) return; // if no expanded rows, refresh screen var options= $('#finales_equipos-datagrid').datagrid('options'); if ( options.expandCount <= 0 ){ options.expandCount=0; updateFinales(0,workingData.datosRonda); } // retrigger refresh pb_config.Timeout=setTimeout(pbmenu_updateFinalesEquipos,1000*rtime); } setTimeout(function(){ // update header pb_getHeaderInfo(); // update footer info pb_setFooterInfo(); $('#enumerateFinales').text(workingData.datosRonda.Nombre); },0); if (pb_config.Timeout==="readyToRun") pbmenu_updateFinalesEquipos(); </script>
jonsito/AgilityContest
agility/public/pbmenu_finales_equipos.php
PHP
gpl-2.0
4,212
<?php /** * Loop Add to Cart * * @author WooThemes * @package WooCommerce/Templates * @version 2.1.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly /* global $product; echo apply_filters( 'woocommerce_loop_add_to_cart_link', sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="button %s product_type_%s">%s</a>', esc_url( $product->add_to_cart_url() ), esc_attr( $product->id ), esc_attr( $product->get_sku() ), $product->is_purchasable() ? 'add_to_cart_button' : '', esc_attr( $product->product_type ), esc_html( $product->add_to_cart_text() ) ), $product ); */
davidHuanghw/david_blog
wp-content/themes/marroco/woocommerce/loop/add-to-cart.php
PHP
gpl-2.0
648
<?php /** * @version $Id: default.php 18338 2010-08-05 21:29:01Z 3dentech $ * @package Joomla.Installation * @copyright Copyright (C) 2005 - 2010 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'); // Load the JavaScript behaviors. JHtml::_('behavior.keepalive'); JHtml::_('behavior.tooltip'); JHtml::_('behavior.formvalidation'); JHtml::_('script', 'installation/template/js/installation.js', true, false, false, false); ?> <div id="stepbar"> <div class="t"> <div class="t"> <div class="t"></div> </div> </div> <div class="m"> <?php echo JHtml::_('installation.stepbar', 3); ?> <div class="box"></div> </div> <div class="b"> <div class="b"> <div class="b"></div> </div> </div> </div> <form action="index.php" method="post" id="adminForm" class="form-validate"> <div id="right"> <div id="rightpad"> <div id="step"> <div class="t"> <div class="t"> <div class="t"></div> </div> </div> <div class="m"> <div class="far-right"> <?php if ($this->document->direction == 'ltr') : ?> <div class="button1-right"><div class="prev"><a href="index.php?view=preinstall" title="<?php echo JText::_('JPREVIOUS'); ?>"><?php echo JText::_('JPREVIOUS'); ?></a></div></div> <div class="button1-left"><div class="next"><a href="index.php?view=database" title="<?php echo JText::_('JNEXT'); ?>"><?php echo JText::_('JNEXT'); ?></a></div></div> <?php elseif ($this->document->direction == 'rtl') : ?> <div class="button1-right"><div class="prev"><a href="index.php?view=database" title="<?php echo JText::_('JNEXT'); ?>"><?php echo JText::_('JNEXT'); ?></a></div></div> <div class="button1-left"><div class="next"><a href="index.php?view=preinstall" title="<?php echo JText::_('JPREVIOUS'); ?>"><?php echo JText::_('JPREVIOUS'); ?></a></div></div> <?php endif; ?> </div> <span class="step"><?php echo JText::_('INSTL_LICENSE'); ?></span> </div> <div class="b"> <div class="b"> <div class="b"></div> </div> </div> </div> <div id="installer"> <div class="t"> <div class="t"> <div class="t"></div> </div> </div> <div class="m"> <h2><?php echo JText::_('INSTL_GNU_GPL_LICENSE'); ?>:</h2> <iframe src="gpl.html" class="license" frameborder="0" marginwidth="25" scrolling="auto"></iframe> <div class="clr"></div> </div> <div class="b"> <div class="b"> <div class="b"></div> </div> </div> </div> </div> <input type="hidden" name="task" value="" /> <?php echo JHtml::_('form.token'); ?> </div> <div class="clr"></div> </form>
3den/J-MediaGalleries
installation/views/license/tmpl/default.php
PHP
gpl-2.0
2,769
<!-- Email Scheduling Settings --> <?php $scheduling = $this -> get_option('scheduling'); $queuesendorder = $this -> get_option('queuesendorder'); $queuesendorderby = $this -> get_option('queuesendorderby'); ?> <input type="hidden" name="scheduling" value="Y" /> <table class="form-table"> <tbody> <tr> <th><label for="<?php echo $this -> pre; ?>emailsperinterval"><?php _e('Emails per Interval', $this -> plugin_name); ?></label> <?php echo $Html -> help(__('Specify the number of emails to send per interval. Rather keep the interval short and this number lower to prevent the procedure which sends out the emails to timeout due to too many emails at once.', $this -> plugin_name)); ?></th> <td> <input onkeyup="totalemails_calculate();" class="widefat" style="width:45px;" type="text" value="<?php echo esc_attr(stripslashes($this -> get_option('emailsperinterval'))); ?>" id="<?php echo $this -> pre; ?>emailsperinterval" name="emailsperinterval" /> <span class="howto"><?php _e('Recommended below 100', $this -> plugin_name); ?></span> </td> </tr> <tr class="advanced-setting"> <th><label for="schedulecrontype_server"><?php _e('Cron/Schedule Type', $this -> plugin_name); ?></label></th> <td> <label><input onclick="jQuery('#schedulecrontype_wp_div').show(); jQuery('#schedulecrontype_server_div').hide();" <?php echo ($this -> get_option('schedulecrontype') == "wp") ? 'checked="checked"' : ''; ?> type="radio" name="schedulecrontype" value="wp" id="schedulecrontype_wp" /> <?php _e('WordPress Cron', $this -> plugin_name); ?></label> <label><input onclick="jQuery('#schedulecrontype_wp_div').hide(); jQuery('#schedulecrontype_server_div').show();" <?php echo ($this -> get_option('schedulecrontype') == "server") ? 'checked="checked"' : ''; ?> type="radio" name="schedulecrontype" value="server" id="schedulecrontype_server" /> <?php _e('Server Cron Job (recommended)', $this -> plugin_name); ?></label> <span class="howto"><?php _e('It is recommended that you use the server cron job as it is more reliable and accurate compared to the WordPress cron.', $this -> plugin_name); ?></span> </td> </tr> </tbody> </table> <div id="schedulecrontype_wp_div" style="display:<?php echo ($this -> get_option('schedulecrontype') == "wp") ? 'block' : 'none'; ?>;"> <table class="form-table"> <tbody> <tr> <th><label for="<?php echo $this -> pre; ?>scheduleinterval"><?php _e('Schedule Interval', $this -> plugin_name); ?></label></th> <td> <?php $scheduleinterval = $this -> get_option('scheduleinterval'); ?> <select onchange="totalemails_calculate();" class="widefat" style="width:auto;" id="<?php echo $this -> pre; ?>scheduleinterval" name="scheduleinterval"> <option data-interval="0" value=""><?php _e('- Select Interval -', $this -> plugin_name); ?></option> <?php $schedules = wp_get_schedules(); ?> <?php if (!empty($schedules)) : ?> <?php foreach ($schedules as $key => $val) : ?> <?php $sel = ($scheduleinterval == $key) ? 'selected="selected"' : ''; ?> <option data-interval="<?php echo esc_attr(stripslashes($val['interval'])); ?>" <?php echo $sel; ?> value="<?php echo $key ?>"><?php echo $val['display']; ?> (<?php echo $val['interval'] ?> <?php _e('seconds', $this -> plugin_name); ?>)</option> <?php endforeach; ?> <?php endif; ?> </select> <span class="howto"><?php _e('Keep the schedule interval as low as possible for frequent executions.', $this -> plugin_name); ?></span> </td> </tr> <tr> <th><label for=""><?php _e('Total Emails', $this -> plugin_name); ?></label></th> <td> <p id="totalemails"> <!-- total emails will display here --> </p> <script type="text/javascript"> var totalemails_calculate = function() { var emailsperinterval = jQuery('#wpmlemailsperinterval').val(); var scheduleinterval = jQuery('#wpmlscheduleinterval').find(':selected').data('interval'); var totalemails_hourly = ((3600 / scheduleinterval) * emailsperinterval); var totalemails_daily = (totalemails_hourly * 24); jQuery('#totalemails').html(totalemails_hourly + ' <?php _e('emails per hour', $this -> plugin_name); ?>, ' + totalemails_daily + ' <?php _e('emails per day', $this -> plugin_name); ?>'); } jQuery(document).ready(function() { totalemails_calculate(); }); </script> </td> </tr> </tbody> </table> </div> <?php $servercronstring = ""; if (!$servercronstring = $this -> get_option('servercronstring')) { $servercronstring = substr(md5(rand(1,999)), 0, 12); } $commandurl = home_url() . '/?' . $this -> pre . 'method=docron&auth=' . $servercronstring; $command = '<code>wget -O /dev/null "' . $commandurl . '" > /dev/null 2>&1</code>'; ?> <input type="hidden" name="servercronstring" value="<?php echo esc_attr(stripslashes($servercronstring)); ?>" /> <div id="schedulecrontype_server_div" style="display:<?php echo ($this -> get_option('schedulecrontype') == "server") ? 'block' : 'none'; ?>;"> <p> <?php echo sprintf(__('You have to create a cron job on your server to execute every 5 minutes with the following command %s', $this -> plugin_name), $command); ?> </p> <p> <?php _e('Please see the documentation for instructions and check with your hosting provider that the WGET command is fully supported on your hosting.', $this -> plugin_name); ?> </p> <p> <?php echo sprintf(__('If you cannot create a cron job or your hosting does not support WGET, you can use %s with the URL %s', $this -> plugin_name), '<a class="button button-primary" href="https://www.easycron.com/cron-job-scheduler?ref=7951&url=' . urlencode($commandurl) . '&testFirst=0&specifiedBy=1&specifiedValue=2&cronJobName=' . urlencode(__('Newsletter plugin cron', $this -> plugin_name)) . '" target="_blank">EasyCron <i class="fa fa-external-link"></i></a>', '<code>' . $commandurl . '</code>'); ?> </p> </div> <table class="form-table"> <tbody> <tr class="advanced-setting"> <th><label for=""><?php _e('Sending Order', $this -> plugin_name); ?></label></th> <td> <select name="queuesendorder"> <option <?php echo (!empty($queuesendorder) && $queuesendorder == "ASC") ? 'selected="selected"' : ''; ?> value="ASC"><?php _e('Ascending', $this -> plugin_name); ?></option> <option <?php echo (!empty($queuesendorder) && $queuesendorder == "DESC") ? 'selected="selected"' : ''; ?> value="DESC"><?php _e('Descending', $this -> plugin_name); ?></option> </select> <?php _e('by', $this -> plugin_name); ?> <select name="queuesendorderby"> <option <?php echo (!empty($queuesendorderby) && $queuesendorderby == "history_id") ? 'selected="selected"' : ''; ?> value="history_id"><?php _e('History ID', $this -> plugin_name); ?></option> <option <?php echo (!empty($queuesendorderby) && $queuesendorderby == "theme_id") ? 'selected="selected"' : ''; ?> value="theme_id"><?php _e('Template ID', $this -> plugin_name); ?></option> <option <?php echo (!empty($queuesendorderby) && $queuesendorderby == "subject") ? 'selected="selected"' : ''; ?> value="subject"><?php _e('Subject', $this -> plugin_name); ?></option> <option <?php echo (!empty($queuesendorderby) && $queuesendorderby == "created") ? 'selected="selected"' : ''; ?> value="created"><?php _e('Date', $this -> plugin_name); ?></option> </select> <span class="howto"><?php _e('Choose the order in which the emails in the queue will be sent out', $this -> plugin_name); ?></span> </td> </tr> <tr class="advanced-setting"> <th><?php _e('Admin Notify on Execution', $this -> plugin_name); ?></th> <td> <label><input <?php echo ($this -> get_option('schedulenotify') == "Y") ? 'checked="checked"' : ''; ?> type="radio" name="schedulenotify" value="Y" /> <?php _e('Yes', $this -> plugin_name); ?></label> <label><input <?php echo ($this -> get_option('schedulenotify') == "N") ? 'checked="checked"' : ''; ?> type="radio" name="schedulenotify" value="N" /> <?php _e('No', $this -> plugin_name); ?></label> </td> </tr> </tbody> </table>
shotgunmm/cloudband-dev
wp-content/plugins/newsletters-lite/views/admin/metaboxes/settings-scheduling.php
PHP
gpl-2.0
8,816
#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class JsonErrorResponse(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'status': 'str', 'message': 'str' } self.attribute_map = { 'status': 'status', 'message': 'message' } # Status: \&quot;ok\&quot; or \&quot;error\&quot; self.status = None # str # Error message self.message = None # str def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))
QuantiModo/QuantiModo-SDK-Python
SwaggerPetstore/models/json_error_response.py
Python
gpl-2.0
1,773
/* * Copyright (c) 2006 - 2010 LinogistiX GmbH * * www.linogistix.com * * Project myWMS-LOS */ package de.linogistix.los.inventory.query.dto; import java.util.Date; import de.linogistix.los.inventory.model.LOSOrderRequestState; import de.linogistix.los.inventory.model.OrderReceipt; import de.linogistix.los.query.BODTO; public class OrderReceiptTO extends BODTO<OrderReceipt> { /** * */ private static final long serialVersionUID = 1L; public String orderNumber; public String orderReference; public Date date; public String state; public OrderReceiptTO(Long id, int version, String name){ super(id, version, name); } public OrderReceiptTO(Long id, int version, String name, String orderNumber, String orderreference, Date date, LOSOrderRequestState state){ super(id, version, name); this.orderNumber = orderNumber; this.orderReference = orderreference; this.date = date; this.state = state.toString(); } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public String getOrderReference() { return orderReference; } public void setOrderReference(String orderReference) { this.orderReference = orderReference; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
Jacksson/mywms
server.app/los.inventory-ejb/src/de/linogistix/los/inventory/query/dto/OrderReceiptTO.java
Java
gpl-2.0
1,492
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use PHPExiftool\Driver\AbstractTag; class RecordedLateralSpreadingDeviceSeq extends AbstractTag { protected $Id = '3008,00F4'; protected $Name = 'RecordedLateralSpreadingDeviceSeq'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Recorded Lateral Spreading Device Seq'; }
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/DICOM/RecordedLateralSpreadingDeviceSeq.php
PHP
gpl-2.0
770
<?php /** Template Name: Blog Full Style Four */ get_header(); ?> <!-- Container Start --> <div class="container_16"> <!-- Top Back Theme --> <div id="top-back-two"></div> <!-- Big Message --> <div class="grid_11 top-message"> <h1> <?php if ( get_post_meta($post->ID, 'bigtitle', true) ) { ?> <?php echo get_post_meta($post->ID, "bigtitle", $single = true); ?> <?php } ?> </h1> </div> <!-- Emty Grid --> <div class="grid_5"> </div> <div class="grid_16 blog-page"> <h1> <?php if ( get_post_meta($post->ID, 'title', true) ) { ?> <?php echo get_post_meta($post->ID, "title", $single = true); ?> <?php } ?> </h1> <h2 class="blog-page-space"></h2> </div> <div class="grid_16 list-page"> <?php $category = get_option_tree('blog_category'); $number = get_option_tree('blog_show'); ?> <?php if (have_posts()) : ?> <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts("cat=$category&showposts=$number&somecat&paged=$paged"); ?> <!-- Filter--> <ul class="splitter"> <li> <ul> <li><a href="?page_id=<?php get_option_tree( 'rightpage_sidebar', '', 'true' ); ?>" id="allpage-login-top" title="Open Sidebar Box" class="middle-button" ><span class="middle-right"></span>Categories </a></li> <li><a href="?page_id=<?php get_option_tree( 'leftpage_sidebar', '', 'true' ); ?>" id="allpage-signup-top" title="Open Sidebar Box" class="middle-button" ><span class="middle-right"></span>Tags </a></li> </ul> </li> </ul> <div style="clear:both"></div> <div id="listing"> <?php while (have_posts()) : the_post(); ?> <!-- #1 --> <div class="discounted-item portfolio-four"> <a class="picture" href="<?php bloginfo('template_directory'); ?>/scripts/timthumb.php?src=<?php echo get_post_meta($post->ID, "thumb", $single = true); ?>&amp;h=600&amp;w=900&amp;zc=1&amp;a=t&amp;s=5" title="Look Picture"><img src="<?php bloginfo('template_directory'); ?>/scripts/timthumb.php?src=<?php echo get_post_meta($post->ID, "thumb", $single = true); ?>&amp;h=190&amp;w=190&amp;zc=1&amp;a=t&amp;s=5" alt="<?php the_title_limit( 30, '...'); ?>" class="portfolio-four-left" /></a> <h1><?php the_title_limit( 30, '...'); ?></h1> <p><?php the_content_rss('', TRUE, '', 30); ?></p> <a href="<?php the_permalink() ?>" class="middle-button" style="float:left; margin:-10px 0px 0px 4px;"> <span class="middle-right"></span>More</a> </div> <?php endwhile;?> </div> <div style="clear:both"></div> <!-- Page Navi --> <div class="page-navi" style="margin:0px 0px 0px -28px;"> <?php wp_pagenavi(); ?> </div> <?php else : ?> <?php endif; ?> </div> </div> <?php get_footer(); ?>
laurenpenn/Website
content/themes/multidesign/blog-fullpage-four.php
PHP
gpl-2.0
2,821
require_dependency 'api_exception' # The Group class represents a group record in the database and thus a group # in the ActiveRbac model. Groups are arranged in trees and have a title. # Groups have an arbitrary number of roles and users assigned to them. # class Group < ApplicationRecord has_many :groups_users, inverse_of: :group, dependent: :destroy has_many :group_maintainers, inverse_of: :group, dependent: :destroy has_many :relationships, dependent: :destroy, inverse_of: :group has_many :event_subscriptions, dependent: :destroy, inverse_of: :group validates :title, format: { with: %r{\A[\w\.\-]*\z}, message: 'must not contain invalid characters.' } validates :title, length: { in: 2..100, too_long: 'must have less than 100 characters.', too_short: 'must have more than two characters.', allow_nil: false } # We want to validate a group's title pretty thoroughly. validates :title, uniqueness: { message: 'is the name of an already existing group.' } # groups have a n:m relation to user has_and_belongs_to_many :users, -> { distinct } # groups have a n:m relation to groups has_and_belongs_to_many :roles, -> { distinct } def self.find_by_title!(title) find_by_title(title) || raise(NotFoundError.new("Couldn't find Group '#{title}'")) end def update_from_xml( xmlhash ) with_lock do if xmlhash.value('email') self.email = xmlhash.value('email') else self.email = nil end end save! # update maintainer list cache = group_maintainers.index_by(&:user_id) xmlhash.elements('maintainer') do |maintainer| next unless maintainer['userid'] user = User.find_by_login!(maintainer['userid']) if cache.has_key? user.id # user has already a role in this package cache.delete(user.id) else GroupMaintainer.create( user: user, group: self).save end end cache.each do |login_id, _| GroupMaintainer.where('user_id = ? AND group_id = ?', login_id, id).delete_all end # update user list cache = groups_users.index_by(&:user_id) persons = xmlhash.elements('person').first if persons persons.elements('person') do |person| next unless person['userid'] user = User.find_by_login!(person['userid']) if cache.has_key? user.id # user has already a role in this package cache.delete(user.id) else GroupsUser.create( user: user, group: self).save end end end # delete all users which were not listed cache.each do |login_id, _gu| GroupsUser.where('user_id = ? AND group_id = ?', login_id, id).delete_all end end def add_user(user) return if users.find_by_id user.id # avoid double creation gu = GroupsUser.create( user: user, group: self) gu.save! end def replace_members(members) Group.transaction do users.delete_all members.split(',').each do |m| users << User.find_by_login!(m) end save! end rescue ActiveRecord::RecordInvalid, NotFoundError => exception errors.add(:base, exception.message) end def remove_user(user) GroupsUser.where('user_id = ? AND group_id = ?', user.id, id).delete_all end def set_email(email) self.email = email save! end def to_s title end def to_param to_s end def involved_projects_ids # just for maintainer for now. role = Role.rolecache['maintainer'] ### all projects where user is maintainer Relationship.projects.where(group_id: id, role_id: role.id).distinct.pluck(:project_id) end protected :involved_projects_ids def involved_projects # now filter the projects that are not visible Project.where(id: involved_projects_ids) end # lists packages maintained by this user and are not in maintained projects def involved_packages # just for maintainer for now. role = Role.rolecache['maintainer'] projects = involved_projects_ids projects << -1 if projects.empty? # all packages where group is maintainer packages = Relationship.where(group_id: id, role_id: role.id).joins(:package).where('packages.project_id not in (?)', projects).pluck(:package_id) Package.where(id: packages).where.not(project_id: projects) end # returns the users that actually want email for this group's notifications def email_users User.where(id: groups_users.where(email: true).pluck(:user_id)) end def display_name address = Mail::Address.new email address.display_name = title address.format end end
kulmesa/open-build-service
src/api/app/models/group.rb
Ruby
gpl-2.0
4,742
<?php /** * @package 2JToolBox * @Copyright (C) 2011 2Joomla.net * @ All rights reserved * @ Joomla! is Free Software * @ Released under GNU/GPL License : http://www.gnu.org/copyleft/gpl.html * @version $Revision: 1.0.10 $ **/ defined('_JEXEC') or die('Restricted access'); class TwojToolboxControllerAjax extends TwojController{ public function display($cachable = false, $urlparams = false){ JFactory::getApplication()->close(''); } public function callback(){ $document = JFactory::getDocument(); $document->setType('raw'); if( $plugin_id = JRequest::getInt('plugin_id', 0) ){ echo TwojToolBoxSiteHelper::PluginÑallback( $plugin_id ); } else { echo JText::_('2jToolBox::Plugin callback error!'); } JFactory::getApplication()->close(''); } public function getcss(){ header('Content-type: text/css'); $document = JFactory::getDocument(); $document->setType('raw'); $document->setMimeEncoding('text/css'); $need_files = JRequest::getString('need', ''); TwojToolBoxSiteHelper::scriptSave( $need_files, 'css'); die(); } public function getjs(){ header('Content-type: text/javascript'); $document = JFactory::getDocument(); $document->setType('raw'); $document->setMimeEncoding('text/javascript'); $need_files = JRequest::getString('need', ''); TwojToolBoxSiteHelper::scriptSave( $need_files, 'js'); die(); } function twojtoolbox_image_resize( ){ jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); $id = JRequest::getInt('id', 0); $ems_cache = JRequest::getInt('ems_cache', 1); $max_width = JRequest::getInt('ems_max_width', 120); $max_height = JRequest::getInt('ems_max_height', 120); $bg = JRequest::getString('ems_bg', 'transparent'); $type_img = JRequest::getString('ems_type_img', 'png'); $type_res = JRequest::getInt('ems_type_res', 0); $position = JRequest::getInt('ems_position', 0); $ems_root = JRequest::getInt('ems_root', 0); $debug = JRequest::getInt('ems_debug', 0); $crop = 0; if($type_res==2){ $crop = 1; $type_res = 0; } if($type_res) $position = 0; if( $type_img!='png' && $type_img!='gif' ) $type_img = 'jpg'; if($max_width==0) $max_width = 120; if($max_height==0) $max_height = 108; if( $max_width < 2000) $max_width = $max_width; if( $max_height < 1000) $max_height = $max_height; if( !$id ) { $image_filename_in = JRequest::getString('ems_file', ''); $image_filename = TwojToolboxHelper::path_twojcode($image_filename_in, 1); } else { $database = JFactory::getDbo(); $database->setQuery( "SELECT img FROM #__twojtoolbox_elements WHERE id = ".$id ); $image_filename = $database->loadResult(); } if( !$image_filename ){ JText::_('input parametr error'); return ; } $image_filename = str_replace('\\', '/', $image_filename); $image_filename = str_replace('/', '/', $image_filename); if($ems_root) $image = JPATH_SITE.'/'.$image_filename; else $image = JPATH_SITE.'/media/com_twojtoolbox/'.$image_filename; if( !JFile::exists( $image ) ){ JText::_('2JToolBox::file '.$image_filename.' read error'); return; } $file_size = ( function_exists('md5_file') ? md5_file($image) : filesize($image) ); $cacheFodler = JPATH_CACHE.'/twojtoolbox/'; if(JComponentHelper::getParams('com_twojtoolbox')->get('twojcachefolder', 0)){ $cacheFodler = JPATH_ROOT.'/media/com_twojtoolbox/cache/'; } if( !JFolder::exists($cacheFodler)) JFolder::create($cacheFodler); $resized = $cacheFodler .($id==0?str_replace(array('.', '(', ')'), '', $image_filename_in):$id) .'_size'.$max_width.'x'.$max_height .'_bg'.$bg .'_fs'.$file_size .'_tr'.($crop?2:$type_res) .'_p'.$position .'.' .$type_img; $imageModified = @filemtime($image); $thumbModified = @filemtime($resized); $document = JFactory::getDocument(); $document->setType('raw'); if(!$debug){ switch ($type_img) { case 'gif': $document->setMimeEncoding('image/gif');header("Content-type: image/gif"); break; case 'png': $document->setMimeEncoding('image/png');header("Content-type: image/png"); break; case 'jpg': default: $document->setMimeEncoding('image/jpeg');header("Content-type: image/jpeg"); } } if($imageModified<$thumbModified && $ems_cache ) { header("Last-Modified: ".gmdate("D, d M Y H:i:s",$thumbModified)." GMT"); readfile($resized); return ; } $ext = strtolower(substr(strrchr($image, '.'), 1)); switch ($ext) { case 'jpg': // jpg $src = imagecreatefromjpeg($image) or notfound(); break; case 'png': // png $src = imagecreatefrompng($image) or notfound(); break; case 'gif': // gif $src = imagecreatefromgif($image) or notfound(); break; default: JText::_('2JToolBox::Error - check GD version'); return ; } $size = getimagesize($image); $width = $size[0]; $height = $size[1]; $x_ratio = $max_width / $width; $y_ratio = $max_height / $height; $xy_ratio = $width / $height; if( ($width <= $max_width) && ($height <= $max_height) ) { $tn_width = $width; $tn_height = $height; } else if( ($x_ratio * $height) < $max_height ) { $tn_height = ceil($x_ratio * $height); $tn_width = $max_width; } else { $tn_width = ceil($y_ratio * $width); $tn_height = $max_height; } if( $type_res ) $dst = imagecreatetruecolor($tn_width,$tn_height); else $dst = imagecreatetruecolor($max_width,$max_height); if($crop){ if( $tn_width < $max_width ){ $k_uv = $max_width - $tn_width; $tn_width += $k_uv; $tn_height = $tn_width / $xy_ratio; } if( $tn_height < $max_height ){ $k_uv = $max_height - $tn_height; $tn_height += $k_uv; $tn_width = $xy_ratio * $tn_height; } } if($debug){ echo '$xy_ratio'.$xy_ratio."<br />"; echo '$tn_width'.$tn_width."<br />"; echo '$tn_height'.$tn_height."<br />"; echo '$max_width'.$max_width."<br />"; echo '$max_height'.$max_height."<br />"; echo '$width'.$width."<br />"; echo '$height'.$height."<br />"; die(); } if (function_exists('imageantialias')) imageantialias ($dst, true); if( $bg!='transparent' ) { $bg = $this->html2rgb($bg); $color = imagecolorallocate ($dst, $bg[0] , $bg[1], $bg[2]); } else { if($type_img!='png'){ imagealphablending($dst, false); imagesavealpha($dst,true); $color = imagecolortransparent($src); if($color >= 0) { $transcol = imagecolorsforindex($src, $color); $color = imagecolorallocatealpha($dst, $transcol['red'], $transcol['green'], $transcol['blue'], 127); } else $color = imagecolorallocatealpha($dst, 0, 0, 0, 127); } else { imagealphablending($dst, false); imagesavealpha($dst, true); $color = imagecolorallocatealpha($dst, 0, 0, 0, 127); } } imagefill($dst, 0, 0, $color); if(!$crop){ if( $position!=1 && $type_res!=1 ) $copy_x = ( ($max_width - $tn_width) / ($position==2?1:2) ); else $copy_x = 0; if( $position!=3 && $type_res!=1 ) $copy_y = ( ($max_height - $tn_height) / ($position==4?1:2)); else $copy_y = 0; } else { if( $max_width < $tn_width && !$type_res && $position!=1 ) $copy_x = ( ($max_width - $tn_width) / ($position==2?1:2) ); else $copy_x = 0; if( $max_height < $tn_height && !$type_res && $position!=3 ) $copy_y = ( ($max_height - $tn_height) / ($position==4?1:2)); else $copy_y = 0; } ImageCopyResampled ($dst, $src, $copy_x, $copy_y, 0, 0, $tn_width, $tn_height, $width, $height); if( $bg=='transparent' && $type_img!='png'){ if($color >= 0) { imagecolortransparent($dst, $color); for($y=0; $y<($type_res?$tn_height:$max_height); ++$y) for($x=0; $x<($type_res?$tn_width:$max_width); ++$x) if(((imagecolorat($dst, $x, $y)>>24) & 0x7F) >= 100) imagesetpixel($dst, $x, $y, $color); } } //ob_start(); if ($type_img=='png'){ imagepng($dst, null, 9); if($ems_cache) imagepng($dst, $resized, 9); }else if ($type_img=='gif'){ imagetruecolortopalette($dst, true, 256); imagesavealpha($dst, false); imagegif($dst); if($ems_cache) imagegif($dst, $resized); }else { imagejpeg($dst, null, 90); if($ems_cache)imagejpeg($dst, $resized, 90); } /* $output = ob_get_contents(); ob_end_clean(); echo $output; if($ems_cache) JFile::write( $resized , $output ); */ imagedestroy($src); imagedestroy($dst); die(); } function html2rgb($color){ if (strlen($color) == 6) list($r, $g, $b) = array($color[0].$color[1], $color[2].$color[3], $color[4].$color[5]); else return array(255, 255, 255); $r = hexdec($r); $g = hexdec($g); $b = hexdec($b); return array($r, $g, $b); } }
trungjc/caravancountry
components/com_twojtoolbox/controllers/ajax.raw.php
PHP
gpl-2.0
8,723
<?php // // +----------------------------------------------------------------------+ // |zen-cart Open Source E-commerce | // +----------------------------------------------------------------------+ // | Copyright (c) 2004 The zen-cart developers | // | | // | http://www.zen-cart.com/index.php | // | | // | Portions Copyright (c) 2003 osCommerce | // | | // | Norwegian translation by Rune Rasmussen - 2006 | // | http://www.syntaxerror.no | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.0 of the GPL license, | // | that is bundled with this package in the file LICENSE, and is | // | available through the world-wide-web at the following url: | // | http://www.zen-cart.com/license/2_0.txt. | // | If you did not receive a copy of the zen-cart license and are unable | // | to obtain it through the world-wide-web, please send a note to | // | license@zen-cart.com so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // $Id: product_types.php 84 2012-02-16 17:42:27Z syntaxerror.no $ // define('HEADING_TITLE', 'Produkttyper'); define('HEADING_TITLE_LAYOUT', 'Produkttypeinfo - valg for sidelayout :: '); define('TABLE_HEADING_PRODUCT_TYPES', 'Produkttyper'); define('TABLE_HEADING_PRODUCT_TYPES_ALLOW_ADD_TO_CART', 'Legg<br />i handelvogn'); define('TABLE_HEADING_ACTION', 'Valg'); define('TABLE_HEADING_CONFIGURATION_TITLE', 'Tittel'); define('TABLE_HEADING_CONFIGURATION_VALUE', 'Verdi'); define('TEXT_HEADING_NEW_PRODUCT_TYPE', 'Ny produkttype'); define('TEXT_HEADING_EDIT_PRODUCT_TYPE', 'Endre produkttype'); define('TEXT_HEADING_DELETE_PRODUCT_TYPE', 'Slett produkttype'); define('TEXT_PRODUCT_TYPES', 'Produkttyper:'); define('TEXT_PRODUCT_TYPES_HANDLER', 'Behandlingsside:'); define('TEXT_PRODUCT_TYPES_ALLOW_ADD_CART', 'SDette produktet kan bli lagt i handlekurv:'); define('TEXT_DATE_ADDED', 'Lagt til:'); define('TEXT_LAST_MODIFIED', 'Sist endret:'); define('TEXT_PRODUCTS', 'Produkter:'); define('TEXT_PRODUCTS_IMAGE_DIR', 'Last opp til mappe:'); define('TEXT_IMAGE_NONEXISTENT', 'Bilde eksisterer ikke'); define('TEXT_MASTER_TYPE', 'Denne produkttypen skal bli sett på som en undertype av '); define('TEXT_NEW_INTRO', 'Fyll ut følgende informasjon for ny produsent'); define('TEXT_EDIT_INTRO', 'Gjør nødvendige endringer'); define('TEXT_PRODUCT_TYPES_NAME', 'Navn på produkttype:'); define('TEXT_PRODUCT_TYPES_IMAGE', 'Standard bilde for produkttype:'); define('TEXT_PRODUCT_TYPES_URL', 'Produsentens nettadresse:'); define('TEXT_DELETE_INTRO', 'Er du sikker på at du ønsker å slette denne produkttypen?'); define('TEXT_DELETE_IMAGE', 'Slett produkttypens standardbilde?'); define('TEXT_DELETE_PRODUCTS', 'Slett produkter fra denne produkttypen? (inkluder produktomtaler, produkter på tilbud og innkommende produkter)'); define('TEXT_DELETE_WARNING_PRODUCTS', '<b>Advarsel:</b> Det er %s produkter forsatt lenket til denne produkt typen!'); define('ERROR_DIRECTORY_NOT_WRITEABLE', 'Feil: Jeg kan ikke skrive til denne mappen. Sett riktige brukerrettigheter på: %s'); define('ERROR_DIRECTORY_DOES_NOT_EXIST', 'Feil: Mappe eksisterer ikke: %s'); define('IMAGE_LAYOUT', 'Layoutinnstillinger');
zencartnorge/norwegian-zencart-translation
admin/includes/languages/norwegian/product_types.php
PHP
gpl-2.0
3,735
/* * IRIS -- Intelligent Roadway Information System * Copyright (C) 2009-2015 Minnesota Department of Transportation * Copyright (C) 2012 Iteris Inc. * Copyright (C) 2014 AHMCT, University of California * Copyright (C) 2015 SRF Consulting Group * * 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. */ package us.mn.state.dot.tms; import java.util.HashMap; import static us.mn.state.dot.tms.SignMessageHelper.DMS_MESSAGE_MAX_PAGES; import us.mn.state.dot.tms.utils.I18N; /** * This enum defines all system attributes. * * @author Douglas Lau * @author Michael Darter * @author Travis Swanston */ public enum SystemAttrEnum { CAMERA_AUTH_USERNAME(""), CAMERA_AUTH_PASSWORD(""), CAMERA_AUTOPLAY(true, Change.RESTART_CLIENT), CAMERA_ID_BLANK(""), CAMERA_NUM_PRESET_BTNS(3, 0, 20, Change.RESTART_CLIENT), CAMERA_PRESET_PANEL_COLUMNS(6, 1, 6, Change.RESTART_CLIENT), CAMERA_PRESET_PANEL_ENABLE(false, Change.RESTART_CLIENT), CAMERA_PRESET_STORE_ENABLE(false, Change.RESTART_CLIENT), CAMERA_PTZ_AXIS_COMPORT(1, 1, 64), CAMERA_PTZ_AXIS_RESET(""), CAMERA_PTZ_AXIS_WIPE(""), CAMERA_PTZ_BLIND(true), CAMERA_PTZ_PANEL_ENABLE(false, Change.RESTART_CLIENT), CAMERA_STREAM_CONTROLS_ENABLE(false, Change.RESTART_CLIENT), CAMERA_UTIL_PANEL_ENABLE(false, Change.RESTART_CLIENT), CAMERA_WIPER_PRECIP_MM_HR(8, 1, 100), CLIENT_UNITS_SI(true), COMM_EVENT_PURGE_DAYS(14, 0, 1000), DATABASE_VERSION(String.class, Change.RESTART_SERVER), DETECTOR_AUTO_FAIL_ENABLE(true), DIALUP_POLL_PERIOD_MINS(60, 2, 1440), DMS_AWS_ENABLE(false), DMS_BRIGHTNESS_ENABLE(true, Change.RESTART_CLIENT), DMS_COMM_LOSS_MINUTES(5, 0, 60), DMS_COMPOSER_EDIT_MODE(1, 0, 2, Change.RESTART_CLIENT), DMS_DEFAULT_JUSTIFICATION_LINE(3, 2, 5, Change.RESTART_CLIENT), DMS_DEFAULT_JUSTIFICATION_PAGE(2, 2, 4, Change.RESTART_CLIENT), DMS_DURATION_ENABLE(true), DMS_FONT_SELECTION_ENABLE(false, Change.RESTART_CLIENT), DMS_FORM(1, 1, 2), DMS_HIGH_TEMP_CUTOFF(60, 35, 100), DMS_LAMP_TEST_TIMEOUT_SECS(30, 5, 90), DMS_MANUFACTURER_ENABLE(true, Change.RESTART_CLIENT), DMS_MAX_LINES(3, 1, 12, Change.RESTART_CLIENT), DMS_MESSAGE_MIN_PAGES(1, 1, DMS_MESSAGE_MAX_PAGES, Change.RESTART_CLIENT), DMS_OP_STATUS_ENABLE(false, Change.RESTART_CLIENT), DMS_PAGE_OFF_DEFAULT_SECS(0f, 0f, 60f), DMS_PAGE_ON_DEFAULT_SECS(2f, 0f, 60f), DMS_PAGE_ON_MAX_SECS(10.0f, 0f, 100f, Change.RESTART_CLIENT), DMS_PAGE_ON_MIN_SECS(0.5f, 0f, 100f, Change.RESTART_CLIENT), DMS_PAGE_ON_SELECTION_ENABLE(false), DMS_PIXEL_OFF_LIMIT(2, 1), DMS_PIXEL_ON_LIMIT(1, 1), DMS_PIXEL_MAINT_THRESHOLD(35, 1), DMS_PIXEL_STATUS_ENABLE(true, Change.RESTART_CLIENT), DMS_PIXEL_TEST_TIMEOUT_SECS(30, 5, 90), DMS_QUERYMSG_ENABLE(false, Change.RESTART_CLIENT), DMS_QUICKMSG_STORE_ENABLE(false, Change.RESTART_CLIENT), DMS_RESET_ENABLE(false, Change.RESTART_CLIENT), DMS_SEND_CONFIRMATION_ENABLE(false, Change.RESTART_CLIENT), DMS_UPDATE_FONT_TABLE(false), DMSXML_MODEM_OP_TIMEOUT_SECS(5 * 60 + 5, 5), DMSXML_OP_TIMEOUT_SECS(60 + 5, 5), DMSXML_REINIT_DETECT(false), EMAIL_SENDER_SERVER(String.class), EMAIL_SMTP_HOST(String.class), EMAIL_RECIPIENT_AWS(String.class), EMAIL_RECIPIENT_DMSXML_REINIT(String.class), EMAIL_RECIPIENT_GATE_ARM(String.class), GATE_ARM_ALERT_TIMEOUT_SECS(90, 10), GPS_NTCIP_ENABLE(false), GPS_NTCIP_JITTER_M(100, 0, 1610), HELP_TROUBLE_TICKET_ENABLE(false), HELP_TROUBLE_TICKET_URL(String.class), INCIDENT_CLEAR_SECS(600, 0, 3600), LCS_POLL_PERIOD_SECS(30, 0, Change.RESTART_SERVER), MAP_EXTENT_NAME_INITIAL("Home"), MAP_ICON_SIZE_SCALE_MAX(30f, 0f, 9000f), MAP_SEGMENT_MAX_METERS(2000, 100, Change.RESTART_CLIENT), METER_EVENT_PURGE_DAYS(14, 0, 1000), METER_GREEN_SECS(1.3f, 0.1f, 10f), METER_MAX_RED_SECS(13f, 5f, 30f), METER_MIN_RED_SECS(0.1f, 0.1f, 10f), METER_YELLOW_SECS(0.7f, 0.1f, 10f), MSG_FEED_VERIFY(true), OPERATION_RETRY_THRESHOLD(3, 1, 20), ROUTE_MAX_LEGS(8, 1, 20), ROUTE_MAX_MILES(16, 1, 30), RWIS_HIGH_WIND_SPEED_KPH(40, 0), RWIS_LOW_VISIBILITY_DISTANCE_M(152, 0), RWIS_OBS_AGE_LIMIT_SECS(240, 0), RWIS_MAX_VALID_WIND_SPEED_KPH(282, 0), SAMPLE_ARCHIVE_ENABLE(true), SPEED_LIMIT_MIN_MPH(45, 0, 100), SPEED_LIMIT_DEFAULT_MPH(55, 0, 100), SPEED_LIMIT_MAX_MPH(75, 0, 100), TESLA_HOST(String.class), TRAVEL_TIME_MIN_MPH(15, 1, 50), UPTIME_LOG_ENABLE(false), VSA_BOTTLENECK_ID_MPH(55, 10, 65), VSA_CONTROL_THRESHOLD(-1000, -5000, -200), VSA_DOWNSTREAM_MILES(0.2f, 0f, 2.0f), VSA_MAX_DISPLAY_MPH(60, 10, 60), VSA_MIN_DISPLAY_MPH(30, 10, 55), VSA_MIN_STATION_MILES(0.1f, 0.01f, 1.0f), VSA_START_INTERVALS(3, 0, 10), VSA_START_THRESHOLD(-1500, -5000, -200), VSA_STOP_THRESHOLD(-750, -5000, -200), WINDOW_TITLE("IRIS: ", Change.RESTART_CLIENT); /** Change action, which indicates what action the admin must * take after changing a system attribute. */ enum Change { RESTART_SERVER("Restart the server after changing."), RESTART_CLIENT("Restart the client after changing."), NONE("A change takes effect immediately."); /** Change message for user. */ private final String m_msg; /** Constructor */ private Change(String msg) { m_msg = msg; } /** Get the restart message. */ public String getMessage() { return m_msg; } } /** System attribute class */ protected final Class atype; /** Default value */ protected final Object def_value; /** Change action */ protected final Change change_action; /** Minimum value for number attributes */ protected final Number min_value; /** Maximum value for number attributes */ protected final Number max_value; /** Create a String attribute with the given default value */ private SystemAttrEnum(String d) { this(String.class, d, null, null, Change.NONE); } /** Create a String attribute with the given default value */ private SystemAttrEnum(String d, Change ca) { this(String.class, d, null, null, ca); } /** Create a Boolean attribute with the given default value */ private SystemAttrEnum(boolean d) { this(Boolean.class, d, null, null, Change.NONE); } /** Create a Boolean attribute with the given default value */ private SystemAttrEnum(boolean d, Change ca) { this(Boolean.class, d, null, null, ca); } /** Create an Integer attribute with default, min and max values */ private SystemAttrEnum(int d, int mn, int mx) { this(Integer.class, d, mn, mx, Change.NONE); } /** Create an Integer attribute with default, min and max values */ private SystemAttrEnum(int d, int mn, int mx, Change ca) { this(Integer.class, d, mn, mx, ca); } /** Create an Integer attribute with default and min values */ private SystemAttrEnum(int d, int mn) { this(Integer.class, d, mn, null, Change.NONE); } /** Create an Integer attribute with default and min values */ private SystemAttrEnum(int d, int mn, Change ca) { this(Integer.class, d, mn, null, ca); } /** Create a Float attribute with default, min and max values */ private SystemAttrEnum(float d, float mn, float mx) { this(Float.class, d, mn, mx, Change.NONE); } /** Create a Float attribute with default, min and max values */ private SystemAttrEnum(float d, float mn, float mx, Change ca) { this(Float.class, d, mn, mx, ca); } /** Create a system attribute with a null default value */ private SystemAttrEnum(Class c) { this(c, null, null, null, Change.NONE); } /** Create a system attribute with a null default value */ private SystemAttrEnum(Class c, Change ca) { this(c, null, null, null, ca); } /** Create a system attribute */ private SystemAttrEnum(Class c, Object d, Number mn, Number mx, Change ca) { atype = c; def_value = d; min_value = mn; max_value = mx; change_action = ca; assert isValidBoolean() || isValidFloat() || isValidInteger() || isValidString(); } /** Get a description of the system attribute enum. */ public static String getDesc(String aname) { String ret = I18N.get(aname); SystemAttrEnum sae = lookup(aname); if(sae != null) ret += " " + sae.change_action.getMessage(); return ret; } /** Return true if the value is the default value. */ public boolean equalsDefault() { return get().toString().equals(getDefault()); } /** Test if the attribute is a valid boolean */ private boolean isValidBoolean() { return (atype == Boolean.class) && (def_value instanceof Boolean) && min_value == null && max_value == null; } /** Test if the attribute is a valid float */ private boolean isValidFloat() { return (atype == Float.class) && (def_value instanceof Float) && (min_value == null || min_value instanceof Float) && (max_value == null || max_value instanceof Float); } /** Test if the attribute is a valid integer */ private boolean isValidInteger() { return (atype == Integer.class) && (def_value instanceof Integer) && (min_value == null || min_value instanceof Integer) && (max_value == null || max_value instanceof Integer); } /** Test if the attribute is a valid string */ private boolean isValidString() { return (atype == String.class) && (def_value == null || def_value instanceof String) && min_value == null && max_value == null; } /** Get the attribute name */ public String aname() { return toString().toLowerCase(); } /** Set of all system attributes */ static protected final HashMap<String, SystemAttrEnum> ALL_ATTRIBUTES = new HashMap<String, SystemAttrEnum>(); static { for(SystemAttrEnum sa: SystemAttrEnum.values()) ALL_ATTRIBUTES.put(sa.aname(), sa); } /** Lookup an attribute by name */ static public SystemAttrEnum lookup(String aname) { return ALL_ATTRIBUTES.get(aname); } /** * Get the value of the attribute as a string. * @return The value of the attribute as a string, never null. */ public String getString() { assert atype == String.class; return (String)get(); } /** Get the default value as a String. */ public String getDefault() { if(def_value != null) return def_value.toString(); else return ""; } /** Get the value of the attribute as a boolean */ public boolean getBoolean() { assert atype == Boolean.class; return (Boolean)get(); } /** Get the value of the attribute as an int */ public int getInt() { assert atype == Integer.class; return (Integer)get(); } /** Get the value of the attribute as a float */ public float getFloat() { assert atype == Float.class; return (Float)get(); } /** * Get the value of the attribute. * @return The value of the attribute, never null. */ protected Object get() { return getValue(SystemAttributeHelper.get(aname())); } /** * Get the value of a system attribute. * @param attr System attribute or null. * @return The attribute value or the default value on error. * Null is never returned. */ private Object getValue(SystemAttribute attr) { if(attr == null) { System.err.println(warningDefault()); return def_value; } return parseValue(attr.getValue()); } /** * Get the value of a system attribute. * @return The parsed value or the default value on error. * Null is never returned. */ public Object parseValue(String v) { Object value = parse(v); if(value == null) { System.err.println(warningParse()); return def_value; } return value; } /** * Parse an attribute value. * @param v Attribute value, may be null. * @return The parsed value or null on error. */ protected Object parse(String v) { if(atype == String.class) return v; if(atype == Boolean.class) return parseBoolean(v); if(atype == Integer.class) return parseInteger(v); if(atype == Float.class) return parseFloat(v); assert false; return null; } /** Parse a boolean attribute value */ protected Boolean parseBoolean(String v) { try { return Boolean.parseBoolean(v); } catch(NumberFormatException e) { return null; } } /** Parse an integer attribute value */ protected Integer parseInteger(String v) { int i; try { i = Integer.parseInt(v); } catch(NumberFormatException e) { return null; } if(min_value != null) { int m = min_value.intValue(); if(i < m) { System.err.println(warningMinimum()); return m; } } if(max_value != null) { int m = max_value.intValue(); if(i > m) { System.err.println(warningMaximum()); return m; } } return i; } /** Parse a float attribute value */ protected Float parseFloat(String v) { float f; try { f = Float.parseFloat(v); } catch(NumberFormatException e) { return null; } if(min_value != null) { float m = min_value.floatValue(); if(f < m) { System.err.println(warningMinimum()); return m; } } if(max_value != null) { float m = max_value.floatValue(); if(f > m) { System.err.println(warningMaximum()); return m; } } return f; } /** Create a 'missing system attribute' warning message */ protected String warningDefault() { return "Warning: " + toString() + " system attribute was not " + "found; using a default value (" + def_value + ")."; } /** Create a parsing warning message */ protected String warningParse() { return "Warning: " + toString() + " system attribute could " + "not be parsed; using a default value (" + def_value + ")."; } /** Create a minimum value warning message */ protected String warningMinimum() { return "Warning: " + toString() + " system attribute was too " + "low; using a minimum value (" + min_value + ")."; } /** Create a maximum value warning message */ protected String warningMaximum() { return "Warning: " + toString() + " system attribute was too " + "high; using a maximum value (" + max_value + ")."; } }
SRF-Consulting/NDOR-IRIS
src/us/mn/state/dot/tms/SystemAttrEnum.java
Java
gpl-2.0
14,208
<?php /** * QContacts Contact manager component for Joomla! 1.5 * * @version 1.0.3 * @package qcontacts * @author Massimo Giagnoni * @copyright Copyright (C) 2008 Massimo Giagnoni. All rights reserved. * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL */ /* This file is part of QContacts. QContacts 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/>. */ function QContactsBuildRoute(&$query) { static $items; $segments = array(); $itemid = null; // Get the menu items for this component. if (!$items) { $component = &JComponentHelper::getComponent('com_qcontacts'); $menu = &JSite::getMenu(); $items = $menu->getItems('componentid', $component->id); } // Break up the contact id into numeric and alias values. if (isset($query['id']) && strpos($query['id'], ':')) { list($query['id'], $query['alias']) = explode(':', $query['id'], 2); } // Break up the category id into numeric and alias values. if (isset($query['catid']) && strpos($query['catid'], ':')) { list($query['catid'], $query['catalias']) = explode(':', $query['catid'], 2); } // Search for an appropriate menu item. if (is_array($items)) { // If only the option and itemid are specified in the query, return that item. if (!isset($query['view']) && !isset($query['id']) && !isset($query['catid']) && isset($query['Itemid'])) { $itemid = (int) $query['Itemid']; } // Search for a specific link based on the critera given. if (!$itemid) { foreach ($items as $item) { // Check if this menu item links to this view. if (isset($item->query['view']) && $item->query['view'] == 'contact' && isset($query['view']) && $query['view'] == 'contact' && isset($item->query['id']) && $item->query['id'] == $query['id']) { $itemid = $item->id; } elseif (isset($item->query['view']) && $item->query['view'] == 'category' && isset($query['view']) && $query['view'] == 'category' && isset($item->query['catid']) && $item->query['catid'] == $query['catid']) { $itemid = $item->id; } } } // If no specific link has been found, search for a general one. if (!$itemid) { foreach ($items as $item) { if (isset($query['view']) && $query['view'] == 'contact' && isset($item->query['view']) && $item->query['view'] == 'category') { // Check for an undealt with contact id. if (isset($query['id'])) { // This menu item links to the contact view but we need to append the contact id to it. $itemid = $item->id; $segments[] = isset($query['catalias']) ? $query['catid'].':'.$query['catalias'] : $query['catid']; $segments[] = isset($query['alias']) ? $query['id'].':'.$query['alias'] : $query['id']; break; } } elseif (isset($query['view']) && $query['view'] == 'category' && isset($item->query['view']) && $item->query['view'] == 'category' && isset($item->query['id']) && $item->query['id'] != $query['id']) { // Check for an undealt with category id. if (isset($query['catid'])) { // This menu item links to the category view but we need to append the category id to it. $itemid = $item->id; $segments[] = isset($query['alias']) ? $query['id'].':'.$query['alias'] : $query['id']; break; } } } } } // Check if the router found an appropriate itemid. if (!$itemid) { // Check if a id was specified. if (isset($query['id'])) { if (isset($query['alias'])) { $query['id'] .= ':'.$query['alias']; } // Push the id onto the stack. $segments[] = $query['id']; unset($query['view']); unset($query['id']); unset($query['alias']); } elseif (isset($query['catid'])) { if (isset($query['catalias'])) { $query['catid'] .= ':'.$query['catalias']; } if (isset($query['alias'])) { $query['id'] .= ':'.$query['alias']; } // Push the catid onto the stack. $segments[] = 'category'; $segments[] = $query['catid']; // Push the id onto the stack. $segments[] = $query['id']; // Remove the unnecessary URL segments. unset($query['view']); unset($query['id']); unset($query['alias']); unset($query['catid']); unset($query['catalias']); } } else { $query['Itemid'] = $itemid; // Remove the unnecessary URL segments. unset($query['view']); unset($query['id']); unset($query['alias']); unset($query['catid']); unset($query['catalias']); } return $segments; } function QContactsParseRoute($segments) { $vars = array(); // Get the active menu item. $menu = &JSite::getMenu(); $item = &$menu->getActive(); // Check if we have a valid menu item. if (is_object($item)) { // Proceed through the possible variations trying to match the most specific one. if (isset($item->query['view']) && $item->query['view'] == 'contact' && isset($segments[0])) { // Break up the contact id into numeric and alias values. if (isset($segments[0]) && strpos($segments[0], ':')) { list($id, $alias) = explode(':', $segments[0], 2); } // Contact view. $vars['view'] = 'contact'; $vars['id'] = $id; } elseif (isset($item->query['view']) && $item->query['view'] == 'category' && count($segments) == 2) { // Break up the category id into numeric and alias values. if (isset($segments[0]) && strpos($segments[0], ':')) { list($catid, $catalias) = explode(':', $segments[0], 2); } // Break up the contact id into numeric and alias values. if (isset($segments[1]) && strpos($segments[1], ':')) { list($id, $alias) = explode(':', $segments[1], 2); } // Contact view. $vars['view'] = 'contact'; $vars['id'] = $id; $vars['catid'] = $catid; } elseif (isset($item->query['view']) && $item->query['view'] == 'category' && isset($segments[0])) { // Break up the category id into numeric and alias values. if (isset($segments[0]) && strpos($segments[0], ':')) { list($catid, $alias) = explode(':', $segments[0], 2); } // Category view. $vars['view'] = 'category'; $vars['catid'] = $catid; } } else { // Count route segments $count = count($segments); // Check if there are any route segments to handle. if ($count) { if ($count == 2) { // We are viewing a contact. $vars['view'] = 'contact'; $vars['id'] = $segments[$count-1]; $vars['catid'] = $segments[$count-2]; } else { // We are viewing a category. $vars['view'] = 'category'; $vars['catid'] = $segments[$count-1]; } } } return $vars; }
lycoben/veneflights
components/com_qcontacts/router.php
PHP
gpl-2.0
7,433
package codejam2016_1st; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Comparator; import java.util.Scanner; import java.util.Stack; class Pair { int _node; int _dist; Pair(int node, int dist) { _node = node; _dist = dist; } public int getDist() { return _dist; } public int getNode() { return _node; } public void setDist(int dist) { _dist = dist; } } class Comp implements Comparator<Pair>{ @Override public int compare(Pair o1, Pair o2) { if(o1.getNode() < o2.getNode()) { return -1; } else if(o1.getNode() > o2.getNode()) { return 1; } else if(o1.getDist() < o2.getDist()) { return -1; } return 1; } } public class Problem_4 { public static void main(String[] args) { try { //start(args[0]); start("problem_4_Set1.in"); } catch (FileNotFoundException e) { e.printStackTrace(); } } static ArrayList<Pair> pairList[]; static ArrayList<Integer> addedCity; static int addedDist[]; static int N; static int Q, M, sum1, sum2; static int dist[]; static void start(String filename) throws FileNotFoundException { Scanner sc = new Scanner(new BufferedInputStream(new FileInputStream(filename))); int tc = sc.nextInt(); while(tc-- > 0) { addedCity = new ArrayList<Integer>(); pairList = new ArrayList[1000000]; addedDist = new int[1000000]; sum1 = 0; sum2 = 0; N = sc.nextInt(); for(int i=0;i<N;i++) { pairList[i] = new ArrayList<Pair>(); } Q = sc.nextInt(); for(int i=0; i<N-1; i++) { int t = sc.nextInt(); int d = sc.nextInt(); pairList[i+1].add(new Pair(t-1, d)); pairList[t-1].add(new Pair(i+1, d)); } // get M for(int i=1;i<N; i++) { if(pairList[i].size() == 1) { addedCity.add(i); } } M = addedCity.size(); for(int i=0; i<M; i++) { int m = sc.nextInt(); addedDist[addedCity.get(i)] = m; } ArrayList<Integer> from = new ArrayList<Integer>(); ArrayList<Integer> to = new ArrayList<Integer>(); for(int i=0; i<Q; i++) { from.add(sc.nextInt()-1); to.add(sc.nextInt()-1); } for(int i=0; i<Q; i++) { // need to ordering if(from.get(i) != to.get(i)) { getShortestDist(from.get(i), to.get(i)); } } // update new road for(int i=0; i<M; i++) { boolean found = false; int m = addedCity.get(i); for(int j=0; j<pairList[0].size(); j++) { if(pairList[0].get(j).getNode() == m) { found = true; pairList[0].get(j).setDist(addedDist[addedCity.get(i)]); } } if(found == false) pairList[0].add(new Pair(m, addedDist[addedCity.get(i)])); found = false; for(int j=0; j<pairList[m].size(); j++) { if(pairList[m].get(j).getNode() == m) { found = true; pairList[m].get(j).setDist(addedDist[addedCity.get(i)]); } } if(found == false) pairList[m].add(new Pair(0, addedDist[addedCity.get(i)])); } for(int i=0; i<Q; i++) { // need to ordering if(from.get(i) != to.get(i)) { getShortestDistAdded(from.get(i), to.get(i)); } } System.out.println(sum1 + " " + sum2); } } static void getShortestDist(int from, int to) { int visited[] = new int[1000000]; dist = new int[1000000]; int n = 0, d; Stack<Integer> path = new Stack<Integer>(); int currentIndex = 0; path.push(from); visited[from] = 1; while(!path.isEmpty()) { // 1. add next ordering by dist currentIndex = path.pop(); ArrayList<Pair> current = pairList[currentIndex]; for(int j=0; j<current.size(); j++) { n = current.get(j).getNode(); d = current.get(j).getDist(); if (visited[n] == 0 || (dist[n] == 0 || dist[currentIndex] + d < dist[n])) { dist[n] = dist[currentIndex] + d; path.push(n); visited[n] = 1; //System.out.println("from:" + currentIndex + " to:" + n); } } } //System.out.println("sum1:" + dist[to]); sum1 += dist[to]; } static void getShortestDistAdded(int from, int to) { int visited[] = new int[1000000]; dist = new int[1000000]; int n = 0, d; Stack<Integer> path = new Stack<Integer>(); int currentIndex = 0; path.push(from); visited[from] = 1; while(!path.isEmpty()) { // 1. add next ordering by dist currentIndex = path.pop(); ArrayList<Pair> current = pairList[currentIndex]; for(int j=0; j<current.size(); j++) { n = current.get(j).getNode(); d = current.get(j).getDist(); if (visited[n] == 0 || (dist[n] == 0 || dist[currentIndex] + d < dist[n])) { dist[n] = dist[currentIndex] + d; path.push(n); visited[n] = 1; //System.out.println("visit2:" + n); } } } //System.out.println("sum2:" + dist[to]); sum2 += dist[to]; } }
apostlez/algorithm-Exams
src/codejam2016_1st/Problem_4.java
Java
gpl-2.0
4,964
#include "control.h" Control::Control (int special_index) : _special_index (special_index) { } void Control::process_g (double delta_t) { } void Control::process_c (double delta_t) { for (size_t i = 0; i < _control_outs.size(); ++i) { _control_outs[i] = *(_control_ins[0] + _special_index + i); } } TrigControl::TrigControl (int special_index) : _special_index (special_index) { } void TrigControl::process_g (double delta_t) { } void TrigControl::process_c (double delta_t) { // TODO make it work for synth-wide controls, not just local ones for (size_t i = 0; i < _control_outs.size(); ++i) { _control_outs[i] = *(_control_ins[0] + _special_index + i); *(_control_ins[0] + _special_index + i) = 0.f; } }
scgraph/SCGraph
src/control.cc
C++
gpl-2.0
734
/******************************************************************************* Copyright (C) 2016 OLogN Technologies AG This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 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 "idlc_include.h" #include "front-back/idl_tree.h" #include "back/idlc_back.h" #include "front/idl/parser.h" #include "front-back/idl_tree_serializer.h" Root* deserializeFile(const char* fileName) { unique_ptr<Root> root(new Root()); uint8_t baseBuff[0x10000]; FILE* in = fopen(fileName, "rb"); if (!in) { fmt::print("Failed to open input file '{}'\n", fileName); return nullptr; } size_t sz = fread(baseBuff, 1, 0x10000, in); fclose(in); IStream i(baseBuff, sz); bool ok = deserializeRoot(*root, i); return ok ? root.release() : nullptr; } struct CmdOptions { vector<string> templs; string templPath; string inputIdl; string inputBinary; }; CmdOptions getCmdOptionFake() { CmdOptions result; result.templPath = "../../Hare-IDL/src/targets/cpp/codegen/protobuf/"; result.templs = { "main.txt", "mapping.txt", "encoding.txt", "proto.txt", "dbg_helpers.txt" }; // result.inputBinary = "../../Hare-IDL/test/targets/protobuf/poly-ptr/test.h.idlbin"; result.inputIdl = "../../Hare-IDL/test/targets/protobuf/idl-primitive/test.idl"; return result; } CmdOptions getCmdOption(char** begin, char** end) { if (begin != end) { string current(*begin); if (current == "--debug") { return getCmdOptionFake(); } } CmdOptions result; for (char** it = begin; it != end; ++it) { string current(*it); if (current.substr(0, 11) == "--template=") result.templs.push_back(current.substr(11)); else if (current.substr(0, 15) == "--templatePath=") result.templPath = current.substr(15); else if (current.substr(0, 14) == "--inputBinary=") result.inputBinary = current.substr(14); else if (current.substr(0, 11) == "--inputIdl=") result.inputIdl = current.substr(11); else fmt::print("Unrecognized command line option: {}\n", current); } return result; } int main(int argc, char* argv[]) { try { HAREASSERT(argc >= 1); CmdOptions opts = getCmdOption(argv + 1, argv + argc); Root* root = 0; if(!opts.inputIdl.empty()) { root = parseSourceFile(opts.inputIdl, false); } else if (!opts.inputBinary.empty()) { root = deserializeFile(opts.inputBinary.c_str()); } else { fmt::print("Missing input file name\n"); return 1; } HAREASSERT(root); idlcBackEnd(*root, opts.templPath, opts.templs, false); } catch ( std::exception& x ) { fmt::print( "Exception happened:\n{}\n", x.what() ); return 1; } return 0; }
O-Log-N/Hare-IDL
src/main.cpp
C++
gpl-2.0
3,604
package com.usp.icmc.labes.fsm; public class FsmTransition extends FsmElement{ private FsmState from; private String input; private String output; private FsmState to; public FsmTransition(){ super(); } public FsmTransition(FsmState f, String in, String out, FsmState t) { this(); from = f; to = t; input = in; output = out; f.getOut().add(this); t.getIn().add(this); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; FsmTransition other = (FsmTransition) obj; if (from == null) { if (other.from != null) return false; } else if (!from.equals(other.from)) return false; if (input == null) { if (other.input != null) return false; } else if (!input.equals(other.input)) return false; if (output == null) { if (other.output != null) return false; } else if (!output.equals(other.output)) return false; if (to == null) { if (other.to != null) return false; } else if (!to.equals(other.to)) return false; return true; } public FsmState getFrom() { return from; } public String getInput() { return input; } public String getOutput() { return output; } public FsmState getTo() { return to; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((from == null) ? 0 : from.hashCode()); result = prime * result + ((input == null) ? 0 : input.hashCode()); result = prime * result + ((output == null) ? 0 : output.hashCode()); result = prime * result + ((to == null) ? 0 : to.hashCode()); return result; } public void setFrom(FsmState from) { this.from = from; } public void setInput(String input) { this.input = input; } public void setOutput(String output) { this.output = output; } public void setTo(FsmState to) { this.to = to; } @Override public String toString() { return from+" -- "+input+" / "+output+" -> "+to; } }
sidgleyandrade/fsmTestCompleteness
fsmTestCompleteness/src/com/usp/icmc/labes/fsm/FsmTransition.java
Java
gpl-2.0
2,070
/* * Magix - A Web Application Framework for Humans * Copyright 2010 - 2011 - Ra-Software, Inc. - thomas.hansen@winergyinc.com * Magix is licensed as GPLv3, or Commercially for Proprietary Projects through Ra-Software. */ using System; using System.Web.UI; using Magix.UX.Widgets; using Magix.UX.Effects; using Magix.Brix.Types; using Magix.Brix.Loader; using System.Web; using Magix.UX; namespace Magix.Brix.Components.ActiveModules.Publishing { /** * Level2: Allows for editing of WebPageTemplate objects. Contains most of the UI * which you're probably daily using while adding and creating new templates and such */ [ActiveModule] public class EditSpecificTemplate : ActiveModule { protected Panel parts; protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (DataSource != null) DataBindWebParts(); } private void DataBindWebParts() { int current = DataSource["ID"].Get<int>(); foreach (Node idx in DataSource["Templates"]) { if (idx.Name == "t-" + current) { foreach (Node idxC in idx["Containers"]) { int width = idxC["Width"].Get<int>(); int height = idxC["Height"].Get<int>(); bool last = idxC["Last"].Get<bool>(); bool overflow = idxC["Overflow"].Get<bool>(); string name = idxC["Name"].Get<string>() ?? "[Unknown]"; int id = idxC["ID"].Get<int>(); int padding = idxC["Padding"].Get<int>(); int push = idxC["Push"].Get<int>(); int top = idxC["Top"].Get<int>(); int bottomMargin = idxC["BottomMargin"].Get<int>(); string moduleName = idxC["ModuleName"].Get<string>(); string cssClass = idxC["CssClass"].Get<string>(); // Creating Window ... Window w = new Window(); w.CssClass = " mux-web-part"; if (overflow) w.CssClass += " mux-overflow-design"; SetCommonWebPartProperties( width, height, last, name, id, padding, push, top, bottomMargin, moduleName, w); w.CssClass += " "; Label lbl3 = new Label(); lbl3.Text = name; lbl3.CssClass = "mux-webpart-widget-info"; lbl3.ToolTip = "Click for Settings ..."; w.Content.Controls.Add(lbl3); lbl3.Click += delegate(object sender, EventArgs e) { bool remove = (((Control)sender).Parent.Parent as Window).CssClass.Contains(" mux-edit-web-part"); foreach (Window idxW in Selector.Select<Window>(parts)) { idxW.CssClass = idxW.CssClass.Replace(" mux-edit-web-part", ""); idxW.Style[Styles.zIndex] = "1"; } (((Control)sender).Parent.Parent as Window).Style[Styles.zIndex] = "2"; if (remove) (((Control)sender).Parent.Parent as Window).CssClass = (((Control)sender).Parent.Parent as Window).CssClass.Replace(" mux-edit-web-part", ""); else (((Control)sender).Parent.Parent as Window).CssClass += " mux-edit-web-part"; }; CreateActionButtons(id, w); CreateNameInPlaceEdit(name, id, w); Label lbl2 = new Label(); lbl2.Text = "WebPart CSS Class"; lbl2.Tag = "label"; lbl2.CssClass = " span-5 down-1 mux-webpart-property-edit-widget"; w.Content.Controls.Add(lbl2); InPlaceEdit tx = CreateChangeCssClassInPlaceEdit(id, cssClass, w); CreateChangeCssClassTemplate(id, name, w, cssClass, tx); CreateModuleSelectListForWebPart(id, moduleName, w); // Last CheckBox CheckBox ch = new CheckBox(); ch.Checked = last; ch.ID = "lch-" + id; ch.CssClass = "span-1"; ch.CheckedChanged += delegate(object sender, EventArgs e) { ch = sender as CheckBox; Node nx = new Node(); nx["ID"].Value = id; nx["Action"].Value = "ChangeLast"; nx["Value"].Value = ch.Checked; RaiseSafeEvent( "Magix.Publishing.ChangeTemplateProperty", nx); if (ch.Checked) w.CssClass += " last"; else w.CssClass = w.CssClass.Replace(" last", ""); }; Label lbl = new Label(); lbl.ID = "llbl-" + id; lbl.Text = "Last"; lbl.CssClass = "span-4 last"; lbl.Tag = "label"; lbl.Load += delegate { lbl.For = ch.ClientID; }; Panel pnl = new Panel(); ch.ID = "lpnl-" + id; pnl.CssClass = "span-5 down-1 mux-webpart-property-edit-widget"; pnl.Controls.Add(ch); pnl.Controls.Add(lbl); w.Content.Controls.Add(pnl); // Overflow CheckBox CheckBox ch1 = new CheckBox(); ch1.Checked = overflow; ch1.ID = "och-" + id; ch1.CssClass = "span-1"; ch1.CheckedChanged += delegate(object sender, EventArgs e) { Node nx = new Node(); nx["ID"].Value = id; nx["Action"].Value = "ChangeOverflow"; nx["Value"].Value = ch1.Checked; RaiseSafeEvent( "Magix.Publishing.ChangeTemplateProperty", nx); if (ch1.Checked) w.CssClass += " mux-overflow-design"; else w.CssClass = w.CssClass.Replace(" mux-overflow-design", ""); }; Label lbl1 = new Label(); lbl1.ID = "olbl-" + id; lbl1.Text = "Overflow"; lbl1.CssClass = "span-4 last"; lbl1.Load += delegate { lbl1.For = ch1.ClientID; }; lbl1.Tag = "label"; Panel pnl1 = new Panel(); pnl1.ID = "opnl-" + id; pnl1.CssClass = "span-5 down-1 mux-webpart-property-edit-widget"; pnl1.Controls.Add(ch1); pnl1.Controls.Add(lbl1); w.Content.Controls.Add(pnl1); // Delete 'this' button LinkButton b = new LinkButton(); b.Text = "Delete"; b.CssClass = "span-5 down-1 mux-webpart-property-edit-widget"; b.Style[Styles.display] = "block"; b.Click += delegate { Node dl = new Node(); dl["ID"].Value = id; RaiseSafeEvent( "Magix.Publishing.DeleteWebPartTemplate", dl); ReDataBind(); }; w.Content.Controls.Add(b); parts.Controls.Add(w); } } } } private void CreateChangeCssClassTemplate(int id, string name, Window w, string cssClass, InPlaceEdit tx) { Node node = new Node(); node["ID"].Value = id; node["Name"].Value = name; RaiseSafeEvent( "Magix.Publishing.GetCssTemplatesForWebPartTemplate", node); if (node.Contains("Classes")) { Label lbl2 = new Label(); lbl2.Text = "CSS Template"; lbl2.Tag = "label"; lbl2.CssClass = " span-5 down-1 mux-webpart-property-edit-widget"; w.Content.Controls.Add(lbl2); SelectList ls = new SelectList(); ls.ID = "selTem-" + id; ls.CssClass = "span-5 mux-webpart-property-edit-widget"; ls.SelectedIndexChanged += delegate { Node nx = new Node(); nx["ID"].Value = id; nx["Value"].Value = ls.SelectedItem.Value; RaiseSafeEvent( "Magix.Publishing.ChangeCssForWebPartTemplateFromCssTemplate", nx); tx.Text = ls.SelectedItem.Value; }; ls.Items.Add(new ListItem("Choose Template ...", "")); foreach (Node idx in node["Classes"]) { ListItem li = new ListItem(idx["Name"].Get<string>(), idx["Value"].Get<string>()); if (li.Value == cssClass) li.Selected = true; ls.Items.Add(li); } w.Content.Controls.Add(ls); } } private InPlaceEdit CreateChangeCssClassInPlaceEdit(int id, string cssClass, Window w) { InPlaceEdit tx = new InPlaceEdit(); tx.Text = cssClass; tx.CssClass += " span-5 mux-in-place-edit-loose mux-webpart-property-edit-widget"; tx.Info = id.ToString(); tx.TextChanged += delegate(object sender, EventArgs e) { InPlaceEdit t = sender as InPlaceEdit; Node node = new Node(); node["ID"].Value = int.Parse(t.Info); node["Action"].Value = "ChangeCssClass"; node["Value"].Value = t.Text; RaiseSafeEvent( "Magix.Publishing.ChangeTemplateProperty", node); }; w.Content.Controls.Add(tx); return tx; } private void CreateNameInPlaceEdit(string name, int id, Window w) { Label lbl = new Label(); lbl.Text = "WebPart Name"; lbl.Tag = "label"; lbl.CssClass = " span-5 down-1 mux-webpart-property-edit-widget"; w.Content.Controls.Add(lbl); InPlaceEdit nameI = new InPlaceEdit(); nameI.Text = name; nameI.Info = id.ToString(); nameI.CssClass += " span-5 mux-in-place-edit-loose mux-webpart-property-edit-widget"; nameI.TextChanged += delegate(object sender, EventArgs e) { InPlaceEdit xed = sender as InPlaceEdit; int idPart = int.Parse(xed.Info); Node node = new Node(); node["ID"].Value = idPart; node["Action"].Value = "ChangeName"; node["Action"]["Value"].Value = xed.Text; if (RaiseSafeEvent( "Magix.Publishing.ChangeTemplateProperty", node)) { Selector.SelectFirst<Label>( xed.Parent, delegate(Control idx) { return (idx is Label) && (idx as Label).CssClass.Contains("mux-webpart-widget-info"); }).Text = xed.Text; } }; w.Content.Controls.Add(nameI); } private void CreateActionButtons(int id, Window w) { LinkButton incWidth = new LinkButton(); incWidth.Text = "&nbsp;"; incWidth.ToolTip = "Increase Width"; incWidth.CssClass = "magix-publishing-increase-width"; incWidth.Info = id.ToString(); incWidth.Click += incWidth_Click; incWidth.DblClick += incWidth_DblClick; w.Content.Controls.Add(incWidth); LinkButton decWidth = new LinkButton(); decWidth.Text = "&nbsp;"; decWidth.ToolTip = "Decrease Width"; decWidth.CssClass = "magix-publishing-decrease-width"; decWidth.Info = id.ToString(); decWidth.Click += decWidth_Click; decWidth.DblClick += decWidth_DblClick; w.Content.Controls.Add(decWidth); LinkButton incHeight = new LinkButton(); incHeight.Text = "&nbsp;"; incHeight.ToolTip = "Increase Height"; incHeight.CssClass = "magix-publishing-increase-height"; incHeight.Info = id.ToString(); incHeight.Click += incHeight_Click; incHeight.DblClick += incHeight_DblClick; w.Content.Controls.Add(incHeight); LinkButton decHeight = new LinkButton(); decHeight.Text = "&nbsp;"; decHeight.ToolTip = "Decrease Height"; decHeight.CssClass = "magix-publishing-decrease-height"; decHeight.Info = id.ToString(); decHeight.Click += decHeight_Click; decHeight.DblClick += decHeight_DblClick; w.Content.Controls.Add(decHeight); LinkButton incDown = new LinkButton(); incDown.Text = "&nbsp;"; incDown.ToolTip = "Increase Top Margin"; incDown.CssClass = "magix-publishing-increase-down"; incDown.Info = id.ToString(); incDown.Click += incDown_Click; incDown.DblClick += incDown_DblClick; w.Content.Controls.Add(incDown); LinkButton decDown = new LinkButton(); decDown.Text = "&nbsp;"; decDown.ToolTip = "Decrease Top Margin"; decDown.CssClass = "magix-publishing-decrease-down"; decDown.Info = id.ToString(); decDown.Click += decDown_Click; decDown.DblClick += decDown_DblClick; w.Content.Controls.Add(decDown); LinkButton incBottom = new LinkButton(); incBottom.Text = "&nbsp;"; incBottom.ToolTip = "Increase Bottom Margin"; incBottom.CssClass = "magix-publishing-increase-bottom"; incBottom.Info = id.ToString(); incBottom.Click += incBottom_Click; incBottom.DblClick += incBottom_DblClick; w.Content.Controls.Add(incBottom); LinkButton decBottom = new LinkButton(); decBottom.Text = "&nbsp;"; decBottom.ToolTip = "Decrease Bottom Margin"; decBottom.CssClass = "magix-publishing-decrease-bottom"; decBottom.Info = id.ToString(); decBottom.Click += decBottom_Click; decBottom.DblClick += decBottom_DblClick; w.Content.Controls.Add(decBottom); LinkButton incLeft = new LinkButton(); incLeft.Text = "&nbsp;"; incLeft.ToolTip = "Increase Left Margin"; incLeft.CssClass = "magix-publishing-increase-left"; incLeft.Info = id.ToString(); incLeft.Click += incLeft_Click; incLeft.DblClick += incLeft_DblClick; w.Content.Controls.Add(incLeft); LinkButton decLeft = new LinkButton(); decLeft.Text = "&nbsp;"; decLeft.ToolTip = "Decrease Left Margin"; decLeft.CssClass = "magix-publishing-decrease-left"; decLeft.Info = id.ToString(); decLeft.Click += decLeft_Click; decLeft.DblClick += decLeft_DblClick; w.Content.Controls.Add(decLeft); LinkButton incPadding = new LinkButton(); incPadding.Text = "&nbsp;"; incPadding.ToolTip = "Increase Right Margin"; incPadding.CssClass = "magix-publishing-increase-padding"; incPadding.Info = id.ToString(); incPadding.Click += incPadding_Click; incPadding.DblClick += incPadding_DblClick; w.Content.Controls.Add(incPadding); LinkButton decPadding = new LinkButton(); decPadding.Text = "&nbsp;"; decPadding.ToolTip = "Decrease Right Margin"; decPadding.CssClass = "magix-publishing-decrease-padding"; decPadding.Info = id.ToString(); decPadding.Click += decPadding_Click; decPadding.DblClick += decPadding_DblClick; w.Content.Controls.Add(decPadding); } void incWidth_Click(object sender, EventArgs e) { ChangeProperty(sender, "IncreaseWidth", -1); } void decWidth_Click(object sender, EventArgs e) { ChangeProperty(sender, "DecreaseWidth", -1); } void incHeight_Click(object sender, EventArgs e) { ChangeProperty(sender, "IncreaseHeight", -1); } void decHeight_Click(object sender, EventArgs e) { ChangeProperty(sender, "DecreaseHeight", -1); } void incDown_Click(object sender, EventArgs e) { ChangeProperty(sender, "IncreaseDown", -1); } void decDown_Click(object sender, EventArgs e) { ChangeProperty(sender, "DecreaseDown", -1); } void incBottom_Click(object sender, EventArgs e) { ChangeProperty(sender, "IncreaseBottom", -1); } void decBottom_Click(object sender, EventArgs e) { ChangeProperty(sender, "DecreaseBottom", -1); } void incLeft_Click(object sender, EventArgs e) { ChangeProperty(sender, "IncreaseLeft", -1); } void decLeft_Click(object sender, EventArgs e) { ChangeProperty(sender, "DecreaseLeft", -1); } void incPadding_Click(object sender, EventArgs e) { ChangeProperty(sender, "IncreasePadding", -1); } void decPadding_Click(object sender, EventArgs e) { ChangeProperty(sender, "DecreasePadding", -1); } private void ChangeProperty(object sender, string action, int value) { LinkButton lbn = sender as LinkButton; int idPart = int.Parse(lbn.Info); Node node = new Node(); node["ID"].Value = idPart; node["Action"].Value = action; if (value != -1) { node["NewValue"].Value = value; } RaiseSafeEvent( "Magix.Publishing.ChangeTemplateProperty", node); Panel p = lbn.Parent.Parent as Window; if (node.Contains("NewWidth")) p.CssClass = p.CssClass.Replace( " span-" + node["OldWidth"].Get<int>(), "") + " span-" + node["NewWidth"].Get<int>(); if (node.Contains("NewHeight")) p.CssClass = p.CssClass.Replace( " height-" + node["OldHeight"].Get<int>(), "") + " height-" + node["NewHeight"].Get<int>(); if (node.Contains("NewTop")) p.CssClass = p.CssClass.Replace( " down-" + node["OldTop"].Get<int>(), "") + " down-" + node["NewTop"].Get<int>(); if (node.Contains("NewPadding")) p.CssClass = p.CssClass.Replace( " right-" + node["OldPadding"].Get<int>(), "") + " right-" + node["NewPadding"].Get<int>(); if (node.Contains("NewPush")) p.CssClass = p.CssClass.Replace( " push-" + node["OldPush"].Get<int>(), "") + " push-" + node["NewPush"].Get<int>(); if (node.Contains("NewMarginBottom")) p.CssClass = p.CssClass.Replace( " bottom-" + node["OldMarginBottom"].Get<int>(), "") + " bottom-" + node["NewMarginBottom"].Get<int>(); } void incWidth_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "IncreaseWidth", 100); } void decWidth_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "DecreaseWidth", 0); } void incHeight_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "IncreaseHeight", 100); } void decHeight_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "DecreaseHeight", 0); } void incDown_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "IncreaseDown", 100); } void decDown_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "DecreaseDown", 0); } void incBottom_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "IncreaseBottom", 100); } void decBottom_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "DecreaseBottom", 0); } void incLeft_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "IncreaseLeft", 100); } void decLeft_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "DecreaseLeft", 0); } void incPadding_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "IncreasePadding", 100); } void decPadding_DblClick(object sender, EventArgs e) { ChangeProperty(sender, "DecreasePadding", 0); } private void ReDataBind() { DataSource["Templates"].UnTie(); DataSource["AllModules"].UnTie(); RaiseEvent( "Magix.Publishing.GetWebPageTemplates", DataSource); RaiseEvent( "Magix.Publishing.GetPublisherPlugins", DataSource); parts.Controls.Clear(); DataBindWebParts(); parts.ReRender(); } private static void SetCommonWebPartProperties(int width, int height, bool last, string name, int id, int padding, int push, int top, int bottomMargin, string moduleName, Window w) { w.CssClass += " mux-shaded mux-rounded"; if (width != 0) w.CssClass += " span-" + width; if (height != 0) w.CssClass += " height-" + height; if (last) w.CssClass += " last"; w.Caption = name; w.Info = id.ToString(); if (padding != 0) w.CssClass += " right-" + padding; if (push != 0) w.CssClass += " push-" + push; if (top != 0) w.CssClass += " down-" + top; if (bottomMargin != 0) w.CssClass += " bottom-" + bottomMargin; w.Draggable = false; w.Closable = false; } private void CreateModuleSelectListForWebPart(int id, string moduleName, Window w) { if (DataSource.Contains("AllModules")) { Label lbl2 = new Label(); lbl2.Text = "Module"; lbl2.Tag = "label"; lbl2.CssClass = " span-5 down-1 mux-webpart-property-edit-widget"; w.Content.Controls.Add(lbl2); SelectList sel = new SelectList(); sel.CssClass = "span-5 mux-webpart-property-edit-widget"; sel.Info = id.ToString(); sel.ID = "selMod-" + id; sel.SelectedIndexChanged += delegate(object sender, EventArgs e) { SelectList sel2 = sender as SelectList; int id2 = int.Parse(sel2.Info); Node nn = new Node(); nn["ID"].Value = id2; nn["ModuleName"].Value = sel.SelectedItem.Value; RaiseSafeEvent( "Magix.Publishing.ChangeModuleTypeForWebPartTemplate", nn); }; foreach (Node idxN1 in DataSource["AllModules"]) { ListItem li = new ListItem( idxN1["ShortName"].Get<string>(), idxN1["ModuleName"].Get<string>()); if (idxN1["ModuleName"].Get<string>() == moduleName) li.Selected = true; sel.Items.Add(li); } w.Content.Controls.Add(sel); } } [ActiveEvent(Name = "Magix.Publishing.WebPageTemplateWasModified")] protected void Magix_Publishing_MultiHandler(object sender, EventArgs e) { ReDataBind(); } } }
xingh/magix
Magix-Brix/Magix.Brix.Components/ActiveModules/Magix.Brix.Components.ActiveModules.Publishing/EditSpecificTemplate.ascx.cs
C#
gpl-2.0
28,342
<?php /** * The Search Form * * @package _starter */ ?> <form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <label> <span class="screen-reader-text"><?php esc_html_e( 'Search for:', '_starter' ); ?></span> <input type="text" class="search-field" name="s" placeholder="<?php esc_html_e( 'Search', '_starter' ); ?>" title="search" /> </label> <button type="submit" class="search-submit"><?php esc_html_e( 'Search', '_starter' ); ?></button> </form>
troutacular/_starter
searchform.php
PHP
gpl-2.0
512
var events = new Hash(); function showEvent( eid, fid, width, height ) { var url = '?view=event&eid='+eid+'&fid='+fid; url += filterQuery; createPopup( url, 'zmEvent', 'event', width, height ); } function createEventHtml( event, frame ) { var eventHtml = new Element( 'div' ); if ( event.Archived > 0 ) eventHtml.addClass( 'archived' ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', monitorNames[event.MonitorId] ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.Name+(frame?("("+frame.FrameId+")"):"") ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.StartTime+" - "+event.Length+"s" ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.Cause ); if ( event.Notes ) new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.Notes ); if ( event.Archived > 0 ) new Element( 'p' ).injectInside( eventHtml ).set( 'text', archivedString ); return( eventHtml ); } function showEventDetail( eventHtml ) { $('instruction').addClass( 'hidden' ); $('eventData').empty(); $('eventData').adopt( eventHtml ); $('eventData').removeClass( 'hidden' ); } function eventDataResponse( respObj, respText ) { var event = respObj.event; if ( !event ) { console.log( "Null event" ); return; } events[event.Id] = event; if ( respObj.loopback ) { requestFrameData( event.Id, respObj.loopback ); } } function frameDataResponse( respObj, respText ) { var frame = respObj.frameimage; if ( !frame.FrameId ) { console.log( "Null frame" ); return; } var event = events[frame.EventId]; if ( !event ) { console.error( "No event "+frame.eventId+" found" ); return; } if ( !event['frames'] ) event['frames'] = new Hash(); event['frames'][frame.FrameId] = frame; event['frames'][frame.FrameId]['html'] = createEventHtml( event, frame ); showEventDetail( event['frames'][frame.FrameId]['html'] ); loadEventImage( frame.Image.imagePath, event.Id, frame.FrameId, event.Width, event.Height ); } var eventQuery = new Request.JSON( { url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: eventDataResponse } ); var frameQuery = new Request.JSON( { url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: frameDataResponse } ); function requestFrameData( eventId, frameId ) { if ( !events[eventId] ) { eventQuery.options.data = "view=request&request=status&entity=event&id="+eventId+"&loopback="+frameId; eventQuery.send(); } else { frameQuery.options.data = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId; frameQuery.send(); } } function previewEvent( eventId, frameId ) { if ( events[eventId] ) { if ( events[eventId]['frames'] ) { if ( events[eventId]['frames'][frameId] ) { showEventDetail( events[eventId]['frames'][frameId]['html'] ); loadEventImage( events[eventId].frames[frameId].Image.imagePath, eventId, frameId, events[eventId].Width, events[eventId].Height ); return; } } } requestFrameData( eventId, frameId ); } function loadEventImage( imagePath, eid, fid, width, height ) { var imageSrc = $('imageSrc'); imageSrc.setProperty( 'src', imagePrefix+imagePath ); imageSrc.removeEvent( 'click' ); imageSrc.addEvent( 'click', showEvent.pass( [ eid, fid, width, height ] ) ); var eventData = $('eventData'); eventData.removeEvent( 'click' ); eventData.addEvent( 'click', showEvent.pass( [ eid, fid, width, height ] ) ); } function tlZoomBounds( minTime, maxTime ) { console.log( "Zooming" ); window.location = '?view='+currentView+filterQuery+'&minTime='+minTime+'&maxTime='+maxTime; } function tlZoomRange( midTime, range ) { window.location = '?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+range; } function tlPan( midTime, range ) { window.location = '?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+range; }
eyezm/ZoneMinder
web/skins/classic/views/js/timeline.js
JavaScript
gpl-2.0
4,238
(function() { /* constructor */ function PhotoFloat() { this.albumCache = []; } /* public member functions */ PhotoFloat.prototype.album = function(subalbum, callback, error) { var cacheKey, ajaxOptions, self; if (typeof subalbum.photos !== "undefined" && subalbum.photos !== null) { callback(subalbum); return; } if (Object.prototype.toString.call(subalbum).slice(8, -1) === "String") cacheKey = subalbum; else cacheKey = PhotoFloat.cachePath(subalbum.parent.path + "/" + subalbum.path); if (this.albumCache.hasOwnProperty(cacheKey)) { callback(this.albumCache[cacheKey]); return; } self = this; ajaxOptions = { type: "GET", dataType: "json", url: "cache/" + cacheKey + ".json", success: function(album) { var i; for (i = 0; i < album.albums.length; ++i) album.albums[i].parent = album; for (i = 0; i < album.photos.length; ++i) album.photos[i].parent = album; self.albumCache[cacheKey] = album; callback(album); } }; if (typeof error !== "undefined" && error !== null) { ajaxOptions.error = function(jqXHR, textStatus, errorThrown) { error(jqXHR.status); }; } $.ajax(ajaxOptions); }; PhotoFloat.prototype.albumPhoto = function(subalbum, callback, error) { var nextAlbum, self; self = this; nextAlbum = function(album) { //var index = Math.floor(Math.random() * (album.photos.length + album.albums.length)); if (1==1 && album.main != null && album.main != "") { var index = 0; for (index = 0; index < album.photos.length; ++index) { if (PhotoFloat.cachePath(album.photos[index].name) === PhotoFloat.cachePath(album.main)) { break; } } callback(album, album.photos[index]); } else{ var index = 0; if (album.photos.length > 0) { index = album.photos.length - 1; } if (index >= album.photos.length) { index -= album.photos.length; self.album(album.albums[index], nextAlbum, error); } else callback(album, album.photos[index]); } }; if (typeof subalbum.photos !== "undefined" && subalbum.photos !== null) nextAlbum(subalbum); else this.album(subalbum, nextAlbum, error); }; PhotoFloat.prototype.parseHash = function(hash, callback, error) { var index, album, photo; hash = PhotoFloat.cleanHash(hash); index = hash.lastIndexOf("/"); if (!hash.length) { album = PhotoFloat.cachePath("root"); photo = null; } else if (index !== -1 && index !== hash.length - 1) { photo = hash.substring(index + 1); album = hash.substring(0, index); } else { album = hash; photo = null; } this.album(album, function(theAlbum) { var i = -1; if (photo !== null) { for (i = 0; i < theAlbum.photos.length; ++i) { if (PhotoFloat.cachePath(theAlbum.photos[i].name) === photo) { photo = theAlbum.photos[i]; break; } } if (i >= theAlbum.photos.length) { photo = null; i = -1; } } callback(theAlbum, photo, i); }, error); }; PhotoFloat.prototype.authenticate = function(password, result) { $.ajax({ type: "GET", dataType: "text", url: "auth?username=photos&password=" + password, success: function() { result(true); }, error: function() { result(false); } }); }; /* static functions */ PhotoFloat.cachePath = function(path) { if (path === "") return "root"; if (path.charAt(0) === "/") path = path.substring(1); path = path .replace(/ /g, "_") .replace(/\//g, "-") .replace(/\(/g, "") .replace(/\)/g, "") .replace(/#/g, "") .replace(/&/g, "") .replace(/,/g, "") .replace(/\[/g, "") .replace(/\]/g, "") .replace(/"/g, "") .replace(/'/g, "") .replace(/_-_/g, "-") .toLowerCase(); while (path.indexOf("--") !== -1) path = path.replace(/--/g, "-"); while (path.indexOf("__") !== -1) path = path.replace(/__/g, "_"); return path; }; PhotoFloat.photoHash = function(album, photo) { return PhotoFloat.albumHash(album) + "/" + PhotoFloat.cachePath(photo.name); }; PhotoFloat.albumHash = function(album) { if (typeof album.photos !== "undefined" && album.photos !== null) return PhotoFloat.cachePath(album.path); return PhotoFloat.cachePath(album.parent.path + "/" + album.path); }; PhotoFloat.photoPath = function(album, photo, size, square) { var suffix; if (square) suffix = size.toString() + "s"; else suffix = size.toString(); return "cache/" + PhotoFloat.cachePath(PhotoFloat.photoHash(album, photo) + "_" + suffix + ".jpg"); }; PhotoFloat.originalPhotoPath = function(album, photo) { return "albums/" + album.path + "/" + photo.name; }; PhotoFloat.trimExtension = function(name) { var index = name.lastIndexOf("."); if (index !== -1) return name.substring(0, index); return name; }; PhotoFloat.cleanHash = function(hash) { while (hash.length) { if (hash.charAt(0) === "#") hash = hash.substring(1); else if (hash.charAt(0) === "!") hash = hash.substring(1); else if (hash.charAt(0) === "/") hash = hash.substring(1); else if (hash.substring(0, 3) === "%21") hash = hash.substring(3); else if (hash.charAt(hash.length - 1) === "/") hash = hash.substring(0, hash.length - 1); else break; } return hash; }; /* make static methods callable as member functions */ PhotoFloat.prototype.cachePath = PhotoFloat.cachePath; PhotoFloat.prototype.photoHash = PhotoFloat.photoHash; PhotoFloat.prototype.albumHash = PhotoFloat.albumHash; PhotoFloat.prototype.photoPath = PhotoFloat.photoPath; PhotoFloat.prototype.originalPhotoPath = PhotoFloat.originalPhotoPath; PhotoFloat.prototype.trimExtension = PhotoFloat.trimExtension; PhotoFloat.prototype.cleanHash = PhotoFloat.cleanHash; /* expose class globally */ window.PhotoFloat = PhotoFloat; }());
mperceau/PhotoFloat
web/js/010-libphotofloat.js
JavaScript
gpl-2.0
5,824
<?php /*____________________________________________________________________ * Name Extension: Magento Ajaxsearch Autocomplete And Suggest * Author: The Cmsmart Development Team * Date Created: 2013 * Websites: http://cmsmart.net * Technical Support: Forum - http://cmsmart.net/support * GNU General Public License v3 (http://opensource.org/licenses/GPL-3.0) * Copyright © 2011-2013 Cmsmart.net. All Rights Reserved. ______________________________________________________________________*/ ?> <?php class Cmsmart_Ajaxsearch_Model_Source_Order { public function toOptionArray() { return array( array('value' => 0, 'label' =>'Ascending'), array('value' => 1, 'label' => 'Descending'), // and so on... ); } }
novayadi85/navicet
app/code/local/Cmsmart/Ajaxsearch/Model/Source/Order.php
PHP
gpl-2.0
753
/// \file // Range v3 library // // Copyright Eric Niebler 2013-present // Copyright Tomislav Ivek 2015-2016 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_VIEW_SET_ALGORITHM_HPP #define RANGES_V3_VIEW_SET_ALGORITHM_HPP #include <algorithm> #include <iterator> #include <type_traits> #include <utility> #include <meta/meta.hpp> #include <range/v3/range_fwd.hpp> #include <range/v3/functional/comparisons.hpp> #include <range/v3/functional/identity.hpp> #include <range/v3/functional/invoke.hpp> #include <range/v3/iterator/default_sentinel.hpp> #include <range/v3/range/access.hpp> #include <range/v3/range/primitives.hpp> #include <range/v3/range/traits.hpp> #include <range/v3/utility/move.hpp> #include <range/v3/utility/semiregular_box.hpp> #include <range/v3/utility/static_const.hpp> #include <range/v3/view/all.hpp> #include <range/v3/view/facade.hpp> #include <range/v3/view/view.hpp> #include <range/v3/detail/disable_warnings.hpp> namespace ranges { /// \cond namespace detail { template<typename Rng1, typename Rng2, typename C, typename P1, typename P2, template<bool, typename...> class Cursor, cardinality Cardinality> struct set_algorithm_view : view_facade<set_algorithm_view<Rng1, Rng2, C, P1, P2, Cursor, Cardinality>, Cardinality> { private: friend range_access; semiregular_box_t<C> pred_; semiregular_box_t<P1> proj1_; semiregular_box_t<P2> proj2_; Rng1 rng1_; Rng2 rng2_; template<bool IsConst> using cursor = Cursor<IsConst, Rng1, Rng2, C, P1, P2>; cursor<simple_view<Rng1>() && simple_view<Rng2>()> begin_cursor() { return {pred_, proj1_, proj2_, ranges::begin(rng1_), ranges::end(rng1_), ranges::begin(rng2_), ranges::end(rng2_)}; } CPP_member auto begin_cursor() const -> CPP_ret(cursor<true>)( // requires range<Rng1 const> && range<Rng2 const>) { return {pred_, proj1_, proj2_, ranges::begin(rng1_), ranges::end(rng1_), ranges::begin(rng2_), ranges::end(rng2_)}; } public: set_algorithm_view() = default; set_algorithm_view(Rng1 rng1, Rng2 rng2, C pred, P1 proj1, P2 proj2) : pred_(std::move(pred)) , proj1_(std::move(proj1)) , proj2_(std::move(proj2)) , rng1_(std::move(rng1)) , rng2_(std::move(rng2)) {} }; template<bool IsConst, typename Rng1, typename Rng2, typename C, typename P1, typename P2> struct set_difference_cursor { private: friend struct set_difference_cursor<!IsConst, Rng1, Rng2, C, P1, P2>; using pred_ref_ = semiregular_box_ref_or_val_t<C, IsConst>; using proj1_ref_ = semiregular_box_ref_or_val_t<P1, IsConst>; using proj2_ref_ = semiregular_box_ref_or_val_t<P2, IsConst>; pred_ref_ pred_; proj1_ref_ proj1_; proj2_ref_ proj2_; template<typename T> using constify_if = meta::const_if_c<IsConst, T>; using R1 = constify_if<Rng1>; using R2 = constify_if<Rng2>; iterator_t<R1> it1_; sentinel_t<R1> end1_; iterator_t<R2> it2_; sentinel_t<R2> end2_; void satisfy() { while(it1_ != end1_) { if(it2_ == end2_) return; if(invoke(pred_, invoke(proj1_, *it1_), invoke(proj2_, *it2_))) return; if(!invoke(pred_, invoke(proj2_, *it2_), invoke(proj1_, *it1_))) ++it1_; ++it2_; } } public: using value_type = range_value_t<constify_if<Rng1>>; using single_pass = meta::or_c<single_pass_iterator_<iterator_t<R1>>, single_pass_iterator_<iterator_t<R2>>>; set_difference_cursor() = default; set_difference_cursor(pred_ref_ pred, proj1_ref_ proj1, proj2_ref_ proj2, iterator_t<R1> it1, sentinel_t<R1> end1, iterator_t<R2> it2, sentinel_t<R2> end2) : pred_(std::move(pred)) , proj1_(std::move(proj1)) , proj2_(std::move(proj2)) , it1_(std::move(it1)) , end1_(std::move(end1)) , it2_(std::move(it2)) , end2_(std::move(end2)) { satisfy(); } CPP_template(bool Other)( // requires IsConst && (!Other)) // set_difference_cursor( set_difference_cursor<Other, Rng1, Rng2, C, P1, P2> that) : pred_(std::move(that.pred_)) , proj1_(std::move(that.proj1_)) , proj2_(std::move(that.proj2_)) , it1_(std::move(that.it1_)) , end1_(std::move(that.end1_)) , it2_(std::move(that.it2_)) , end2_(std::move(that.end2_)) {} // clang-format off auto CPP_auto_fun(read)()(const) ( return *it1_ ) // clang-format on void next() { ++it1_; satisfy(); } CPP_member auto equal(set_difference_cursor const & that) const -> CPP_ret(bool)( // requires forward_range<Rng1>) { // does not support comparing iterators from different ranges return it1_ == that.it1_; } bool equal(default_sentinel_t) const { return it1_ == end1_; } // clang-format off auto CPP_auto_fun(move)()(const) ( return iter_move(it1_) ) // clang-format on }; constexpr cardinality set_difference_cardinality(cardinality c1, cardinality c2) { return (c1 == unknown) ? unknown : (c1 >= 0) || (c1 == finite) ? finite : // else, c1 == infinite (c2 >= 0) || (c2 == finite) ? infinite : unknown; } } // namespace detail /// \endcond template<typename Rng1, typename Rng2, typename C, typename P1, typename P2> using set_difference_view = detail::set_algorithm_view<Rng1, Rng2, C, P1, P2, detail::set_difference_cursor, detail::set_difference_cardinality( range_cardinality<Rng1>::value, range_cardinality<Rng2>::value)>; namespace views { struct set_difference_base_fn { template<typename Rng1, typename Rng2, typename C = less, typename P1 = identity, typename P2 = identity> auto operator()(Rng1 && rng1, Rng2 && rng2, C pred = C{}, P1 proj1 = P1{}, P2 proj2 = P2{}) const -> CPP_ret(set_difference_view<all_t<Rng1>, all_t<Rng2>, C, P1, P2>)( // requires viewable_range<Rng1> && input_range<Rng1> && viewable_range<Rng2> && input_range<Rng2> && indirect_relation<C, projected<iterator_t<Rng1>, P1>, projected<iterator_t<Rng2>, P2>>) { return {all(static_cast<Rng1 &&>(rng1)), all(static_cast<Rng2 &&>(rng2)), std::move(pred), std::move(proj1), std::move(proj2)}; } }; struct set_difference_fn : set_difference_base_fn { using set_difference_base_fn::operator(); template<typename Rng2, typename C = less, typename P1 = identity, typename P2 = identity> constexpr auto CPP_fun(operator())(Rng2 && rng2, C && pred = C{}, P1 proj1 = P1{}, P2 proj2 = P2{})( const // requires viewable_range<Rng2> && input_range<Rng2> && (!range<C>)) { return make_view_closure(bind_back(set_difference_base_fn{}, all(rng2), static_cast<C &&>(pred), std::move(proj1), std::move(proj2))); } }; /// \relates set_difference_fn /// \ingroup group-views RANGES_INLINE_VARIABLE(set_difference_fn, set_difference) } // namespace views /// @} /// \cond namespace detail { template<bool IsConst, typename Rng1, typename Rng2, typename C, typename P1, typename P2> struct set_intersection_cursor { private: friend struct set_intersection_cursor<!IsConst, Rng1, Rng2, C, P1, P2>; using pred_ref_ = semiregular_box_ref_or_val_t<C, IsConst>; using proj1_ref_ = semiregular_box_ref_or_val_t<P1, IsConst>; using proj2_ref_ = semiregular_box_ref_or_val_t<P2, IsConst>; pred_ref_ pred_; proj1_ref_ proj1_; proj2_ref_ proj2_; template<typename T> using constify_if = meta::const_if_c<IsConst, T>; using R1 = constify_if<Rng1>; using R2 = constify_if<Rng2>; iterator_t<R1> it1_; sentinel_t<R1> end1_; iterator_t<R2> it2_; sentinel_t<R2> end2_; void satisfy() { while(it1_ != end1_ && it2_ != end2_) { if(invoke(pred_, invoke(proj1_, *it1_), invoke(proj2_, *it2_))) ++it1_; else { if(!invoke(pred_, invoke(proj2_, *it2_), invoke(proj1_, *it1_))) return; ++it2_; } } } public: using value_type = range_value_t<R1>; using single_pass = meta::or_c<single_pass_iterator_<iterator_t<R1>>, single_pass_iterator_<iterator_t<R2>>>; set_intersection_cursor() = default; set_intersection_cursor(pred_ref_ pred, proj1_ref_ proj1, proj2_ref_ proj2, iterator_t<R1> it1, sentinel_t<R1> end1, iterator_t<R2> it2, sentinel_t<R2> end2) : pred_(std::move(pred)) , proj1_(std::move(proj1)) , proj2_(std::move(proj2)) , it1_(std::move(it1)) , end1_(std::move(end1)) , it2_(std::move(it2)) , end2_(std::move(end2)) { satisfy(); } CPP_template(bool Other)( // requires IsConst && (!Other)) // set_intersection_cursor( set_intersection_cursor<Other, Rng1, Rng2, C, P1, P2> that) : pred_(std::move(that.pred_)) , proj1_(std::move(that.proj1_)) , proj2_(std::move(that.proj2_)) , it1_(std::move(that.it1_)) , end1_(std::move(that.end1_)) , it2_(std::move(that.it2_)) , end2_(std::move(that.end2_)) {} // clang-format off auto CPP_auto_fun(read)()(const) ( return *it1_ ) // clang-format on void next() { ++it1_; ++it2_; satisfy(); } CPP_member auto equal(set_intersection_cursor const & that) const -> CPP_ret(bool)( // requires forward_range<Rng1>) { // does not support comparing iterators from different ranges return it1_ == that.it1_; } bool equal(default_sentinel_t) const { return (it1_ == end1_) || (it2_ == end2_); } // clang-format off auto CPP_auto_fun(move)()(const) ( return iter_move(it1_) ) // clang-format on }; constexpr cardinality set_intersection_cardinality(cardinality c1, cardinality c2) { return (c1 == unknown) || (c2 == unknown) ? unknown : (c1 >= 0 || c1 == finite) || (c2 >= 0 || c2 == finite) ? finite : unknown; } } // namespace detail /// \endcond template<typename Rng1, typename Rng2, typename C, typename P1, typename P2> using set_intersection_view = detail::set_algorithm_view<Rng1, Rng2, C, P1, P2, detail::set_intersection_cursor, detail::set_intersection_cardinality( range_cardinality<Rng1>::value, range_cardinality<Rng2>::value)>; namespace views { struct set_intersection_base_fn { template<typename Rng1, typename Rng2, typename C = less, typename P1 = identity, typename P2 = identity> auto operator()(Rng1 && rng1, Rng2 && rng2, C pred = C{}, P1 proj1 = P1{}, P2 proj2 = P2{}) const -> CPP_ret(set_intersection_view<all_t<Rng1>, all_t<Rng2>, C, P1, P2>)( // requires viewable_range<Rng1> && input_range<Rng1> && viewable_range<Rng2> && input_range<Rng2> && indirect_relation<C, projected<iterator_t<Rng1>, P1>, projected<iterator_t<Rng2>, P2>>) { return {all(static_cast<Rng1 &&>(rng1)), all(static_cast<Rng2 &&>(rng2)), std::move(pred), std::move(proj1), std::move(proj2)}; } }; struct set_intersection_fn : set_intersection_base_fn { using set_intersection_base_fn::operator(); template<typename Rng2, typename C = less, typename P1 = identity, typename P2 = identity> constexpr auto CPP_fun(operator())(Rng2 && rng2, C && pred = C{}, P1 proj1 = P1{}, P2 proj2 = P2{})( const // requires viewable_range<Rng2> && input_range<Rng2> && (!range<C>)) { return make_view_closure(bind_back(set_intersection_base_fn{}, all(rng2), static_cast<C &&>(pred), std::move(proj1), std::move(proj2))); } }; /// \relates set_intersection_fn /// \ingroup group-views RANGES_INLINE_VARIABLE(set_intersection_fn, set_intersection) } // namespace views /// @} /// \cond namespace detail { template<bool IsConst, typename Rng1, typename Rng2, typename C, typename P1, typename P2> struct set_union_cursor { private: friend struct set_union_cursor<!IsConst, Rng1, Rng2, C, P1, P2>; using pred_ref_ = semiregular_box_ref_or_val_t<C, IsConst>; using proj1_ref_ = semiregular_box_ref_or_val_t<P1, IsConst>; using proj2_ref_ = semiregular_box_ref_or_val_t<P2, IsConst>; pred_ref_ pred_; proj1_ref_ proj1_; proj2_ref_ proj2_; template<typename T> using constify_if = meta::const_if_c<IsConst, T>; using R1 = constify_if<Rng1>; using R2 = constify_if<Rng2>; iterator_t<R1> it1_; sentinel_t<R1> end1_; iterator_t<R2> it2_; sentinel_t<R2> end2_; enum class state_t { FIRST, SECOND } state; void satisfy() { if(it1_ == end1_) { state = state_t::SECOND; return; } if(it2_ == end2_) { state = state_t::FIRST; return; } if(invoke(pred_, invoke(proj2_, *it2_), invoke(proj1_, *it1_))) { state = state_t::SECOND; return; } if(!invoke(pred_, invoke(proj1_, *it1_), invoke(proj2_, *it2_))) ++it2_; state = state_t::FIRST; } public: using value_type = common_type_t<range_value_t<R1>, range_value_t<R2>>; using reference_type = common_reference_t<range_reference_t<R1>, range_reference_t<R2>>; using rvalue_reference_type = common_reference_t<range_rvalue_reference_t<R1>, range_rvalue_reference_t<R2>>; using single_pass = meta::or_c<single_pass_iterator_<iterator_t<R1>>, single_pass_iterator_<iterator_t<R2>>>; set_union_cursor() = default; set_union_cursor(pred_ref_ pred, proj1_ref_ proj1, proj2_ref_ proj2, iterator_t<R1> it1, sentinel_t<R1> end1, iterator_t<R2> it2, sentinel_t<R2> end2) : pred_(std::move(pred)) , proj1_(std::move(proj1)) , proj2_(std::move(proj2)) , it1_(std::move(it1)) , end1_(std::move(end1)) , it2_(std::move(it2)) , end2_(std::move(end2)) { satisfy(); } CPP_template(bool Other)( // requires IsConst && (!Other)) set_union_cursor(set_union_cursor<Other, Rng1, Rng2, C, P1, P2> that) : pred_(std::move(that.pred_)) , proj1_(std::move(that.proj1_)) , proj2_(std::move(that.proj2_)) , it1_(std::move(that.it1_)) , end1_(std::move(that.end1_)) , it2_(std::move(that.it2_)) , end2_(std::move(that.end2_)) {} reference_type read() const noexcept(noexcept(*it1_) && noexcept(*it2_)) { if(state == state_t::SECOND) return *it2_; else return *it1_; } void next() { if(state == state_t::FIRST) ++it1_; else ++it2_; satisfy(); } CPP_member auto equal(set_union_cursor const & that) const -> CPP_ret(bool)( // requires forward_range<Rng1> && forward_range<Rng2>) { // does not support comparing iterators from different ranges return (it1_ == that.it1_) && (it2_ == that.it2_); } bool equal(default_sentinel_t) const { return (it1_ == end1_) && (it2_ == end2_); } rvalue_reference_type move() const noexcept(noexcept(iter_move(it1_)) && noexcept(iter_move(it2_))) { if(state == state_t::SECOND) return iter_move(it2_); else return iter_move(it1_); } }; constexpr cardinality set_union_cardinality(cardinality c1, cardinality c2) { return (c1 == infinite) || (c2 == infinite) ? infinite : (c1 == unknown) || (c2 == unknown) ? unknown : finite; } } // namespace detail /// \endcond template<typename Rng1, typename Rng2, typename C, typename P1, typename P2> using set_union_view = detail::set_algorithm_view<Rng1, Rng2, C, P1, P2, detail::set_union_cursor, detail::set_union_cardinality( range_cardinality<Rng1>::value, range_cardinality<Rng2>::value)>; namespace views { struct set_union_base_fn { public: template<typename Rng1, typename Rng2, typename C = less, typename P1 = identity, typename P2 = identity> auto operator()(Rng1 && rng1, Rng2 && rng2, C pred = C{}, P1 proj1 = P1{}, P2 proj2 = P2{}) const -> CPP_ret(set_union_view<all_t<Rng1>, all_t<Rng2>, C, P1, P2>)( // requires viewable_range<Rng1> && input_range<Rng1> && viewable_range<Rng2> && input_range<Rng2> && common_with< range_value_t<Rng1>, range_value_t<Rng2>> && common_reference_with<range_reference_t<Rng1>, range_reference_t<Rng2>> && common_reference_with<range_rvalue_reference_t<Rng1>, range_rvalue_reference_t<Rng2>> && indirect_relation<C, projected<iterator_t<Rng1>, P1>, projected<iterator_t<Rng2>, P2>>) { return {all(static_cast<Rng1 &&>(rng1)), all(static_cast<Rng2 &&>(rng2)), std::move(pred), std::move(proj1), std::move(proj2)}; } }; struct set_union_fn : set_union_base_fn { using set_union_base_fn::operator(); template<typename Rng2, typename C = less, typename P1 = identity, typename P2 = identity> constexpr auto CPP_fun(operator())(Rng2 && rng2, C && pred = C{}, P1 proj1 = P1{}, P2 proj2 = P2{})( const // requires viewable_range<Rng2> && input_range<Rng2> && (!range<C>)) { return make_view_closure(bind_back(set_union_base_fn{}, all(rng2), static_cast<C &&>(pred), std::move(proj1), std::move(proj2))); } }; /// \relates set_union_fn /// \ingroup group-views RANGES_INLINE_VARIABLE(set_union_fn, set_union) } // namespace views /// @} /// \cond namespace detail { template<bool IsConst, typename Rng1, typename Rng2, typename C, typename P1, typename P2> struct set_symmetric_difference_cursor { private: friend struct set_symmetric_difference_cursor<!IsConst, Rng1, Rng2, C, P1, P2>; using pred_ref_ = semiregular_box_ref_or_val_t<C, IsConst>; using proj1_ref_ = semiregular_box_ref_or_val_t<P1, IsConst>; using proj2_ref_ = semiregular_box_ref_or_val_t<P2, IsConst>; pred_ref_ pred_; proj1_ref_ proj1_; proj2_ref_ proj2_; template<typename T> using constify_if = meta::const_if_c<IsConst, T>; using R1 = constify_if<Rng1>; using R2 = constify_if<Rng2>; iterator_t<R1> it1_; sentinel_t<R1> end1_; iterator_t<R2> it2_; sentinel_t<R2> end2_; enum class state_t { FIRST, SECOND, ONLY_FIRST, ONLY_SECOND } state; void satisfy() { while(it1_ != end1_) { if(it2_ == end2_) { state = state_t::ONLY_FIRST; return; } if(invoke(pred_, invoke(proj1_, *it1_), invoke(proj2_, *it2_))) { state = state_t::FIRST; return; } else { if(invoke(pred_, invoke(proj2_, *it2_), invoke(proj1_, *it1_))) { state = state_t::SECOND; return; } else { ++it1_; ++it2_; } } } state = state_t::ONLY_SECOND; } public: using value_type = common_type_t<range_value_t<R1>, range_value_t<R2>>; using reference_type = common_reference_t<range_reference_t<R1>, range_reference_t<R2>>; using rvalue_reference_type = common_reference_t<range_rvalue_reference_t<R1>, range_rvalue_reference_t<R2>>; using single_pass = meta::or_c<single_pass_iterator_<iterator_t<R1>>, single_pass_iterator_<iterator_t<R2>>>; set_symmetric_difference_cursor() = default; set_symmetric_difference_cursor(pred_ref_ pred, proj1_ref_ proj1, proj2_ref_ proj2, iterator_t<R1> it1, sentinel_t<R1> end1, iterator_t<R2> it2, sentinel_t<R2> end2) : pred_(std::move(pred)) , proj1_(std::move(proj1)) , proj2_(std::move(proj2)) , it1_(std::move(it1)) , end1_(std::move(end1)) , it2_(std::move(it2)) , end2_(std::move(end2)) , state() { satisfy(); } CPP_template(bool Other)( // requires IsConst && (!Other)) // set_symmetric_difference_cursor( set_symmetric_difference_cursor<Other, Rng1, Rng2, C, P1, P2> that) : pred_(std::move(that.pred_)) , proj1_(std::move(that.proj1_)) , proj2_(std::move(that.proj2_)) , it1_(std::move(that.it1_)) , end1_(std::move(that.end1_)) , it2_(std::move(that.it2_)) , end2_(std::move(that.end2_)) , state(that.state) {} reference_type read() const noexcept(noexcept(*it1_) && noexcept(*it2_)) { if(state == state_t::SECOND || state == state_t::ONLY_SECOND) return *it2_; else return *it1_; } void next() { switch(state) { case state_t::FIRST: ++it1_; satisfy(); break; case state_t::ONLY_FIRST: ++it1_; break; case state_t::SECOND: ++it2_; satisfy(); break; case state_t::ONLY_SECOND: ++it2_; break; } } CPP_member auto equal(set_symmetric_difference_cursor const & that) const -> CPP_ret(bool)( // requires forward_range<R1> && forward_range<R2>) { // does not support comparing iterators from different ranges: return (it1_ == that.it1_) && (it2_ == that.it2_); } bool equal(default_sentinel_t) const { return (it1_ == end1_) && (it2_ == end2_); } rvalue_reference_type move() const noexcept(noexcept(iter_move(it1_)) && noexcept(iter_move(it2_))) { if(state == state_t::SECOND || state == state_t::ONLY_SECOND) return iter_move(it2_); else return iter_move(it1_); } }; constexpr cardinality set_symmetric_difference_cardinality(cardinality c1, cardinality c2) { return (c1 == unknown) || (c2 == unknown) ? unknown : (c1 == infinite) != (c2 == infinite) ? infinite : (c1 == infinite) && (c2 == infinite) ? unknown : finite; } } // namespace detail /// \endcond template<typename Rng1, typename Rng2, typename C, typename P1, typename P2> using set_symmetric_difference_view = detail::set_algorithm_view< Rng1, Rng2, C, P1, P2, detail::set_symmetric_difference_cursor, detail::set_symmetric_difference_cardinality(range_cardinality<Rng1>::value, range_cardinality<Rng2>::value)>; namespace views { struct set_symmetric_difference_base_fn { template<typename Rng1, typename Rng2, typename C = less, typename P1 = identity, typename P2 = identity> auto operator()(Rng1 && rng1, Rng2 && rng2, C pred = C{}, P1 proj1 = P1{}, P2 proj2 = P2{}) const -> CPP_ret(set_symmetric_difference_view<all_t<Rng1>, all_t<Rng2>, C, P1, P2>)( // requires viewable_range<Rng1> && input_range<Rng1> && viewable_range<Rng2> && input_range<Rng2> && common_with< range_value_t<Rng1>, range_value_t<Rng2>> && common_reference_with<range_reference_t<Rng1>, range_reference_t<Rng2>> && common_reference_with<range_rvalue_reference_t<Rng1>, range_rvalue_reference_t<Rng2>> && indirect_relation<C, projected<iterator_t<Rng1>, P1>, projected<iterator_t<Rng2>, P2>>) { return {all(static_cast<Rng1 &&>(rng1)), all(static_cast<Rng2 &&>(rng2)), std::move(pred), std::move(proj1), std::move(proj2)}; } }; struct set_symmetric_difference_fn : set_symmetric_difference_base_fn { using set_symmetric_difference_base_fn::operator(); template<typename Rng2, typename C = less, typename P1 = identity, typename P2 = identity> constexpr auto CPP_fun(operator())(Rng2 && rng2, C && pred = C{}, P1 proj1 = P1{}, P2 proj2 = P2{})( const // requires viewable_range<Rng2> && input_range<Rng2> && (!range<C>)) { return make_view_closure(bind_back(set_symmetric_difference_base_fn{}, all(rng2), static_cast<C &&>(pred), std::move(proj1), std::move(proj2))); } }; /// \relates set_symmetric_difference_fn /// \ingroup group-views RANGES_INLINE_VARIABLE(set_symmetric_difference_fn, set_symmetric_difference) } // namespace views /// @} } // namespace ranges #include <range/v3/detail/reenable_warnings.hpp> #endif
bredelings/BAli-Phy
external/range-v3/0.10.0/include/range/v3/view/set_algorithm.hpp
C++
gpl-2.0
33,745
<?php /* Copyright (C) <2011> Vasyl Martyniuk <martyniuk.vasyl@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 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/>. */ /** * Metabox & Widget Manager * * @package AAM * @subpackage Model */ class mvb_Model_Manager_Metabox { public static $parent; /** * * @global array $submenu * @param string $tmpl * @param mvb_Model_Manager $parent * @return string */ public static function render($tmpl, $parent) { global $wp_post_types; self::$parent = $parent; //get cache. Compatible with version previouse versions $cache = mvb_Model_API::getBlogOption(WPACCESS_PREFIX . 'cache', NULL); if (!is_array($cache)) { //yeap this is new version $cache = mvb_Model_API::getBlogOption( WPACCESS_PREFIX . 'options', array() ); $cache = (isset($cache['settings']) ? $cache['settings'] : array()); mvb_Model_API::updateBlogOption(WPACCESS_PREFIX . 'cache', $cache); } $row_tmpl = mvb_Model_Template::retrieveSub('METABOX_LIST_ITEM', $tmpl); $list = ''; if (isset($cache['metaboxes']) && is_array($cache['metaboxes'])) { $list_tmpl = mvb_Model_Template::retrieveSub( 'POST_METABOXES_LIST', $row_tmpl ); $item_tmpl = mvb_Model_Template::retrieveSub( 'POST_METABOXES_ITEM', $list_tmpl ); $widget_tmpl = mvb_Model_Template::retrieveSub( 'WIDGET_ITEM', $list_tmpl ); foreach ($cache['metaboxes'] as $type => $metaboxes) { $render = TRUE; switch ($type) { case 'widgets': $temp = self::renderWidget($widget_tmpl, $metaboxes); $label = mvb_Model_Label::get('LABEL_79'); break; case 'dashboard': $temp = self::renderMetabox( $item_tmpl, $metaboxes, $type ); $label = mvb_Model_Label::get('LABEL_116'); break; default: if (isset($wp_post_types[$type])) { $temp = self::renderMetabox( $item_tmpl, $metaboxes, $type ); $label = $wp_post_types[$type]->labels->name; }else{ $render = FALSE; } break; } if ($render){ $temp = mvb_Model_Template::replaceSub( 'POST_METABOXES_LIST', $temp, $row_tmpl ); $list .= mvb_Model_Template::updateMarkers( array('###post_type_label###' => $label), $temp ); } } $content = mvb_Model_Template::replaceSub( 'METABOX_LIST_ITEM', $list, $tmpl ); $content = mvb_Model_Template::replaceSub( 'METABOX_LIST_EMPTY', '', $content ); }else{ $empty_tmpl = mvb_Model_Template::retrieveSub( 'METABOX_LIST_EMPTY', $tmpl ); $content = mvb_Model_Template::replaceSub( 'METABOX_LIST_ITEM', '', $tmpl ); $content = mvb_Model_Template::replaceSub( 'METABOX_LIST_EMPTY', $empty_tmpl, $content ); } return $content; } public static function renderWidget($tmpl, $list) { global $wp_registered_widgets; $content = ''; if (is_array($list)) { foreach ($list as $classname => $data) { if (is_array($data)) { $desc = mvb_Model_Helper::removeHTML($data['description']); $markers = array( '###title###' => (mvb_Model_Helper::removeHTML($data['title'])), '###classname###' => $classname, '###description###' => ($desc), '###description_short###' => (mvb_Model_Helper::cutStr( $desc, 20 )), '###checked###' => (self::$parent->getConfig() ->hasMetabox($classname) ? 'checked' : '') ); $content .= mvb_Model_Template::updateMarkers( $markers, $tmpl ); } } } return $content; } public static function renderMetabox($tmpl, $list, $type) { $content = ''; foreach ($list as $position => $set) { foreach ($set as $priority => $metaboxes) { if (is_array($metaboxes)) { foreach ($metaboxes as $id => $data) { if (is_array($data) && isset($data['id']) && !empty($data['id'])) { $data['title'] = mvb_Model_Helper::removeHTML( $data['title'] ); $markers = array( '###title###' => (mvb_Model_Helper::removeHTML( $data['title'] )), '###short_id###' => mvb_Model_Helper::cutStr( $data['id'], 25 ), '###id###' => $data['id'], '###priority###' => $priority, '###internal_id###' => $type . '-' . $id, '###position###' => $position, '###checked###' => (self::$parent->getConfig() ->hasMetabox($type . '-' . $id) ? 'checked' : '') ); $content .= mvb_Model_Template::updateMarkers( $markers, $tmpl ); } } } } } return $content; } } ?>
augustocorrea/sbmarmoles_website
wp-content/plugins/advanced-access-manager/model/manager/metabox.php
PHP
gpl-2.0
7,111
<?php /** * @package cbarnes_dev */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <h1 class="entry-title"><?php the_title(); ?></h1> <div class="entry-meta"> <?php cbarnes_dev_posted_on(); ?> </div><!-- .entry-meta --> </header><!-- .entry-header --> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'cbarnes_dev' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-meta"> <?php /* translators: used between list items, there is a space after the comma */ $category_list = get_the_category_list( __( ', ', 'cbarnes_dev' ) ); /* translators: used between list items, there is a space after the comma */ $tag_list = get_the_tag_list( '', __( ', ', 'cbarnes_dev' ) ); if ( ! cbarnes_dev_categorized_blog() ) { // This blog only has 1 category so we just need to worry about tags in the meta text if ( '' != $tag_list ) { $meta_text = __( 'This entry was tagged %2$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'cbarnes_dev' ); } else { $meta_text = __( 'Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'cbarnes_dev' ); } } else { // But this blog has loads of categories so we should probably display them here if ( '' != $tag_list ) { $meta_text = __( 'This entry was posted in %1$s and tagged %2$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'cbarnes_dev' ); } else { $meta_text = __( 'This entry was posted in %1$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'cbarnes_dev' ); } } // end check for categories on this blog printf( $meta_text, $category_list, $tag_list, get_permalink(), the_title_attribute( 'echo=0' ) ); ?> <?php edit_post_link( __( 'Edit', 'cbarnes_dev' ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-meta --> </article><!-- #post-## -->
chrisbarnes/bootstrap-starter-theme
content-single.php
PHP
gpl-2.0
2,162