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 |
|---|---|---|---|---|---|
package de.metas.handlingunits.impl;
/*
* #%L
* de.metas.handlingunits.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 de.metas.handlingunits.IHUTrxQuery;
/* package */class HUTrxQuery implements IHUTrxQuery
{
private int M_HU_Trx_Hdr_ID = -1;
private int Exclude_M_HU_Trx_Line_ID = -1;
private int Parent_M_HU_Trx_Line_ID = -1;
private int Ref_HU_Item_ID = -1;
private int AD_Table_ID = -1;
private int Record_ID = -1;
private int M_HU_ID = -1;
@Override
public String toString()
{
return "HUTrxQuery ["
+ "M_HU_Trx_Hdr_ID=" + M_HU_Trx_Hdr_ID
+ ", Exclude_M_HU_Trx_Line_ID=" + Exclude_M_HU_Trx_Line_ID
+ ", Parent_M_HU_Trx_Line_ID=" + Parent_M_HU_Trx_Line_ID
+ ", Ref_HU_Item_ID=" + Ref_HU_Item_ID
+ ", AD_Table_ID/Record_ID=" + AD_Table_ID + "/" + Record_ID
+ "]";
}
@Override
public int getM_HU_Trx_Hdr_ID()
{
return M_HU_Trx_Hdr_ID;
}
@Override
public void setM_HU_Trx_Hdr_ID(final int m_HU_Trx_Hdr_ID)
{
M_HU_Trx_Hdr_ID = m_HU_Trx_Hdr_ID;
}
@Override
public int getExclude_M_HU_Trx_Line_ID()
{
return Exclude_M_HU_Trx_Line_ID;
}
@Override
public void setExclude_M_HU_Trx_Line_ID(final int exclude_M_HU_Trx_Line_ID)
{
Exclude_M_HU_Trx_Line_ID = exclude_M_HU_Trx_Line_ID;
}
@Override
public int getParent_M_HU_Trx_Line_ID()
{
return Parent_M_HU_Trx_Line_ID;
}
@Override
public void setParent_M_HU_Trx_Line_ID(final int parent_M_HU_Trx_Line_ID)
{
Parent_M_HU_Trx_Line_ID = parent_M_HU_Trx_Line_ID;
}
@Override
public void setM_HU_Item_ID(final int Ref_HU_Item_ID)
{
this.Ref_HU_Item_ID = Ref_HU_Item_ID;
}
@Override
public int getM_HU_Item_ID()
{
return Ref_HU_Item_ID;
}
@Override
public int getAD_Table_ID()
{
return AD_Table_ID;
}
@Override
public void setAD_Table_ID(final int aD_Table_ID)
{
AD_Table_ID = aD_Table_ID;
}
@Override
public int getRecord_ID()
{
return Record_ID;
}
@Override
public void setRecord_ID(final int record_ID)
{
Record_ID = record_ID;
}
@Override
public void setM_HU_ID(int m_hu_ID)
{
M_HU_ID = m_hu_ID;
}
@Override
public int getM_HU_ID()
{
return M_HU_ID;
}
}
| klst-com/metasfresh | de.metas.handlingunits.base/src/main/java/de/metas/handlingunits/impl/HUTrxQuery.java | Java | gpl-2.0 | 2,821 |
<?php
/**
* WooThemes Media Library-driven AJAX File Uploader Module (2010-11-05)
*
* Slightly modified for use in the Options Framework.
*/
if ( is_admin() ) {
// Load additional css and js for image uploads on the Options Framework page
$of_page= 'appearance_page_options-framework';
add_action( "admin_print_styles-$of_page", 'optionsframework_mlu_css', 0 );
add_action( "admin_print_scripts-$of_page", 'optionsframework_mlu_js', 0 );
}
/**
* Sets up a custom post type to attach image to. This allows us to have
* individual galleries for different uploaders.
*/
if ( ! function_exists( 'optionsframework_mlu_init' ) ) {
function optionsframework_mlu_init () {
register_post_type( 'optionsframework', array(
'labels' => array(
'name' => __( 'Options Framework Internal Container', 'Raptor' ),
),
'public' => true,
'show_ui' => false,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => false,
'supports' => array( 'title', 'editor' ),
'query_var' => false,
'can_export' => true,
'show_in_nav_menus' => false
) );
}
}
/**
* Adds the Thickbox CSS file and specific loading and button images to the header
* on the pages where this function is called.
*/
if ( ! function_exists( 'optionsframework_mlu_css' ) ) {
function optionsframework_mlu_css () {
$_html = '';
$_html .= '<link rel="stylesheet" href="' . site_url() . '/' . WPINC . '/js/thickbox/thickbox.css" type="text/css" media="screen" />' . "\n";
$_html .= '<script type="text/javascript">
var tb_pathToImage = "' . site_url() . '/' . WPINC . '/js/thickbox/loadingAnimation.gif";
var tb_closeImage = "' . site_url() . '/' . WPINC . '/js/thickbox/tb-close.png";
</script>' . "\n";
echo $_html;
}
}
/**
* Registers and enqueues (loads) the necessary JavaScript file for working with the
* Media Library-driven AJAX File Uploader Module.
*/
if ( ! function_exists( 'optionsframework_mlu_js' ) ) {
function optionsframework_mlu_js () {
// Registers custom scripts for the Media Library AJAX uploader.
wp_register_script( 'of-medialibrary-uploader', OPTIONS_FRAMEWORK_DIRECTORY .'js/of-medialibrary-uploader.js', array( 'jquery', 'thickbox' ) );
wp_enqueue_script( 'of-medialibrary-uploader' );
wp_enqueue_script( 'media-upload' );
}
}
/**
* Media Uploader Using the WordPress Media Library.
*
* Parameters:
* - string $_id - A token to identify this field (the name).
* - string $_value - The value of the field, if present.
* - string $_mode - The display mode of the field.
* - string $_desc - An optional description of the field.
* - int $_postid - An optional post id (used in the meta boxes).
*
* Dependencies:
* - optionsframework_mlu_get_silentpost()
*/
if ( ! function_exists( 'optionsframework_medialibrary_uploader' ) ) {
function optionsframework_medialibrary_uploader( $_id, $_value, $_mode = 'full', $_desc = '', $_postid = 0, $_name = '') {
$optionsframework_settings = get_option('optionsframework');
// Gets the unique option id
$option_name = $optionsframework_settings['id'];
$output = '';
$id = '';
$class = '';
$int = '';
$value = '';
$name = '';
$id = strip_tags( strtolower( $_id ) );
// Change for each field, using a "silent" post. If no post is present, one will be created.
$int = optionsframework_mlu_get_silentpost( $id );
// If a value is passed and we don't have a stored value, use the value that's passed through.
if ( $_value != '' && $value == '' ) {
$value = $_value;
}
if ($_name != '') {
$name = $option_name.'['.$id.']['.$_name.']';
}
else {
$name = $option_name.'['.$id.']';
}
if ( $value ) { $class = ' has-file'; }
$output .= '<input id="' . $id . '" class="upload' . $class . '" type="text" name="'.$name.'" value="' . $value . '" />' . "\n";
$output .= '<input id="upload_' . $id . '" class="upload_button button" type="button" value="' . __( 'Upload', 'Raptor' ) . '" rel="' . $int . '" />' . "\n";
if ( $_desc != '' ) {
$output .= '<span class="of_metabox_desc">' . $_desc . '</span>' . "\n";
}
$output .= '<div class="screenshot" id="' . $id . '_image">' . "\n";
if ( $value != '' ) {
$remove = '<a href="javascript:(void);" class="mlu_remove button">Remove</a>';
$image = preg_match( '/(^.*\.jpg|jpeg|png|gif|ico*)/i', $value );
if ( $image ) {
$output .= '<img src="' . $value . '" alt="" />'.$remove.'';
} else {
$parts = explode( "/", $value );
for( $i = 0; $i < sizeof( $parts ); ++$i ) {
$title = $parts[$i];
}
// No output preview if it's not an image.
$output .= '';
// Standard generic output if it's not an image.
$title = __( 'View File', 'optionsframework' );
$output .= '<div class="no_image"><span class="file_link"><a href="' . $value . '" target="_blank" rel="external">'.$title.'</a></span>' . $remove . '</div>';
}
}
$output .= '</div>' . "\n";
return $output;
}
}
/**
* Uses "silent" posts in the database to store relationships for images.
* This also creates the facility to collect galleries of, for example, logo images.
*
* Return: $_postid.
*
* If no "silent" post is present, one will be created with the type "optionsframework"
* and the post_name of "of-$_token".
*
* Example Usage:
* optionsframework_mlu_get_silentpost ( 'of_logo' );
*/
if ( ! function_exists( 'optionsframework_mlu_get_silentpost' ) ) {
function optionsframework_mlu_get_silentpost ( $_token ) {
global $wpdb;
$_id = 0;
// Check if the token is valid against a whitelist.
// $_whitelist = array( 'of_logo', 'of_custom_favicon', 'of_ad_top_image' );
// Sanitise the token.
$_token = strtolower( str_replace( ' ', '_', $_token ) );
// if ( in_array( $_token, $_whitelist ) ) {
if ( $_token ) {
// Tell the function what to look for in a post.
$_args = array( 'post_type' => 'optionsframework', 'post_name' => 'of-' . $_token, 'post_status' => 'draft', 'comment_status' => 'closed', 'ping_status' => 'closed' );
// Look in the database for a "silent" post that meets our criteria.
$query = 'SELECT ID FROM ' . $wpdb->posts . ' WHERE post_parent = 0';
foreach ( $_args as $k => $v ) {
$query .= ' AND ' . $k . ' = "' . $v . '"';
} // End FOREACH Loop
$query .= ' LIMIT 1';
$_posts = $wpdb->get_row( $query );
// If we've got a post, loop through and get it's ID.
if ( count( $_posts ) ) {
$_id = $_posts->ID;
} else {
// If no post is present, insert one.
// Prepare some additional data to go with the post insertion.
$_words = explode( '_', $_token );
$_title = join( ' ', $_words );
$_title = ucwords( $_title );
$_post_data = array( 'post_title' => $_title );
$_post_data = array_merge( $_post_data, $_args );
$_id = wp_insert_post( $_post_data );
}
}
return $_id;
}
}
/**
* Trigger code inside the Media Library popup.
*/
if ( ! function_exists( 'optionsframework_mlu_insidepopup' ) ) {
function optionsframework_mlu_insidepopup () {
if ( isset( $_REQUEST['is_optionsframework'] ) && $_REQUEST['is_optionsframework'] == 'yes' ) {
add_action( 'admin_head', 'optionsframework_mlu_js_popup' );
add_filter( 'media_upload_tabs', 'optionsframework_mlu_modify_tabs' );
}
}
}
if ( ! function_exists( 'optionsframework_mlu_js_popup' ) ) {
function optionsframework_mlu_js_popup () {
$_of_title = $_REQUEST['of_title'];
if ( ! $_of_title ) { $_of_title = 'file'; } // End IF Statement
?>
<script type="text/javascript">
<!--
jQuery(function($) {
jQuery.noConflict();
// Change the title of each tab to use the custom title text instead of "Media File".
$( 'h3.media-title' ).each ( function () {
var current_title = $( this ).html();
var new_title = current_title.replace( 'media file', '<?php echo $_of_title; ?>' );
$( this ).html( new_title );
} );
// Change the text of the "Insert into Post" buttons to read "Use this File".
$( '.savesend input.button[value*="Insert into Post"], .media-item #go_button' ).attr( 'value', 'Use this File' );
// Hide the "Insert Gallery" settings box on the "Gallery" tab.
$( 'div#gallery-settings' ).hide();
// Preserve the "is_optionsframework" parameter on the "delete" confirmation button.
$( '.savesend a.del-link' ).click ( function () {
var continueButton = $( this ).next( '.del-attachment' ).children( 'a.button[id*="del"]' );
var continueHref = continueButton.attr( 'href' );
continueHref = continueHref + '&is_optionsframework=yes';
continueButton.attr( 'href', continueHref );
} );
});
-->
</script>
<?php
}
}
/**
* Triggered inside the Media Library popup to modify the title of the "Gallery" tab.
*/
if ( ! function_exists( 'optionsframework_mlu_modify_tabs' ) ) {
function optionsframework_mlu_modify_tabs ( $tabs ) {
$tabs['gallery'] = str_replace( __( 'Gallery', 'optionsframework' ), __( 'Previously Uploaded', 'optionsframework' ), $tabs['gallery'] );
return $tabs;
}
} | doloreel/smh-wp | wp-content/themes/raptor/admin/options-medialibrary-uploader.php | PHP | gpl-2.0 | 9,395 |
<?php
return array(
'title'=>'Opciones del servidor SMTP',
'php_mail'=>'¿Usar la función de PHP mail()?',
'php_mail_desc'=>'Utiliza esta opción si el servidor SMTP no te funciona, la configuració del servidor no permite utilizar directamente SMTP o no dispones de servidor SMTP. NOTE: Si seleccionas esta opción, no es necesario modificar ninguna de las otras opciones, serán ignoradas.',
'server'=>'Servidor SMTP',
'server_desc'=>'La dirección IP o el nombre del host/dominio del servidor a través del cual se envia el email via SMTP.',
'port'=>'Puerto',
'port_desc'=>'El puerto a través del cual el servidor SMTP esta escuchando las conexiones SMTP. Si conoce cual es, deje el puerto por defecto (puerto 25).',
'auth'=>'Método de autentificación',
'auth_desc'=>'Aquí puede especificar que tipo de autentificación requiere su servidor SMTP (si es necesaria). Por favor, consulte esta información al admnistrador de su servidor de correo.',
'auth_none'=>'Sin autentifiacación',
'auth_plain'=>'PLAIN',
'auth_login'=>'LOGIN',
'username'=>'Usuario SMTP',
'username_desc'=>'El usuario que va a usar cuando conecte a un servidor SMTP que requiera autentifiacación',
'password'=>'Contraseña SMTP',
'password_desc'=>'La contraseña que tiene que usar cuando conecte a un servidor SMTP que requiera autentifiacación',
'from_address'=>'Dirección de envío',
'from_address_desc'=>'Direcció de email que se usa para comunicarse con el servidor SMTP. Esto es importante para servidores SMTP que restringen el acceso a ciertas direcciones de email.',
);
?> | exponentcms/exponent-cms-1 | subsystems/lang/es_ES/conf/extensions/smtp.structure.php | PHP | gpl-2.0 | 1,682 |
<?php
/*
* * * * * * * * * * * * * * * * * * *
* Shows the author links
* * * * * * * * * * * * * * * * * * *
*/
class GPAISRFilter {
/**
* @since 0.6
*/
function __construct() {
$options = get_option( 'gpaisr' );
if( isset( $options['replacement'] ) && $options['replacement'] == 1 ) {
add_filter( 'author_link', array( $this, 'author_link_filter' ), 0, 3 );
}
else {
add_filter( 'the_content', array( $this, 'author_link_in_content' ), 15 );
}
}
/**
* Just replaces the link with the google+ url
*
* @param $link
* @param $author_id
* @param $author_nicename
*
* @since 0.6
*
* @return string
*/
function author_link_filter( $link, $author_id, $author_nicename ) {
$gplus_author_link = get_the_author_meta( 'gplus_link', $author_id );
if( ! empty( $gplus_author_link ) ) return $gplus_author_link . '?rel=author';
return $link;
}
/**
* Writes the Google+-URL right after the Content
*
* @param $content
*
* @since 0.6
*
* @return string
*/
function author_link_in_content( $content ) {
// load the options from the settings page
$options = get_option( 'gpaisr' );
// is this the feed? if yes, should we display the link?
if( ! isset( $options['in_feed'] ) ) $options['in_feed'] = 0;
if( is_feed() && $options['in_feed'] != 1 ) return $content;
// what's the author id?
$authorId = get_the_author_meta( 'ID' );
// find the link
$gplus_author_link = get_the_author_meta( 'gplus_link', $authorId );
if( ! empty( $gplus_author_link ) ) $gplus_author_link = $gplus_author_link . '?rel=author';
// open in a new window?
$newWindow = '';
if( isset( $options['new_window'] ) && $options['new_window'] == 1 ) $newWindow = 'target="_blank"';
// show or hide?
$showHide = '';
if( isset( $options['hide'] ) && $options['hide'] == 1 ) {
$showHide = 'style="display:none;"';
}
// is there a linktext?
$linktext = 'Google+';
if( ! empty( $options['link_text'] ) ) $linktext = $options['link_text'];
return $content .= '<a rel="author" href="' . $gplus_author_link . '" ' . $newWindow . ' ' . $showHide . '>' . $linktext . '</a>';
}
} | yondri/newyorkando | wp-content/plugins/google-author-information-in-search-results-wordpress-plugin/class.filter.php | PHP | gpl-2.0 | 2,158 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 1.8 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2007 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the Affero General Public License Version 1, |
| March 2002. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the Affero General Public |
| License along with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2007
* $Id$
*
*/
require_once 'CRM/Core/Session.php';
require_once 'CRM/Core/DAO/UFMatch.php';
/**
* The basic class that interfaces with the external user framework
*/
class CRM_Core_BAO_UFMatch extends CRM_Core_DAO_UFMatch {
/**
* Given a UF user object, make sure there is a contact
* object for this user. If the user has new values, we need
* to update the CRM DB with the new values
*
* @param Object $user the drupal user object
* @param boolean $update has the user object been edited
* @param $uf
*
* @return void
* @access public
* @static
*/
static function synchronize( &$user, $update, $uf, $ctype ) {
$session =& CRM_Core_Session::singleton( );
if ( ! is_object( $session ) ) {
CRM_Core_Error::fatal( 'wow, session is not an object?' );
return;
}
if ( $uf == 'Drupal' ) {
$key = 'uid';
$mail = 'mail';
} else if ( $uf == 'Joomla' ) {
$key = 'id';
$mail = 'email';
} else if ( $uf == 'Standalone' ) {
// There is no CMS to synchronize with in the standalone version,
// so just return.
return;
} else {
CRM_Core_Error::statusBounce(ts('Please set the user framework variable'));
}
// have we already processed this user, if so early
// return.
$userID = $session->get( 'userID' );
$ufID = $session->get( 'ufID' );
if ( ! $update && $ufID == $user->$key ) {
return;
}
// reset the session if we are a different user
if ( $ufID && $ufID != $user->$key ) {
$session->reset( );
}
// make sure we load the joomla object to get valid information
if ( $uf == 'Joomla' ) {
$user->load( );
}
// if the id of the object is zero (true for anon users in drupal)
// return early
if ( $user->$key == 0 ) {
return;
}
$ufmatch =& self::synchronizeUFMatch( $user, $user->$key, $user->$mail, $uf, null, $ctype );
if ( ! $ufmatch ) {
return;
}
$session->set( 'ufID' , $ufmatch->uf_id );
$session->set( 'userID' , $ufmatch->contact_id );
$session->set( 'domainID', $ufmatch->domain_id );
$session->set( 'ufEmail' , $ufmatch->email );
if ( $update ) {
// the only information we care about is email, so lets check that
if ( $user->$mail != $ufmatch->email ) {
// email has changed, so we need to change all our primary email also
$ufmatch->email = $user->$mail;
$ufmatch->save( );
$query = "
UPDATE civicrm_contact
LEFT JOIN civicrm_location ON ( civicrm_location.entity_table = 'civicrm_contact' AND
civicrm_contact.id = civicrm_location.entity_id AND
civicrm_location.is_primary = 1 )
LEFT JOIN civicrm_email ON ( civicrm_location.id = civicrm_email.location_id AND
civicrm_email.is_primary = 1 )
SET civicrm_email.email = %1 WHERE civicrm_contact.id = %2 ";
$p = array( 1 => array( $user->$mail , 'String' ),
2 => array( $ufmatch->contact_id, 'Integer' ) );
CRM_Core_DAO::executeQuery( $query, $p );
}
}
}
/**
* Synchronize the object with the UF Match entry. Can be called stand-alone from
* the drupalUsers script
*
* @param Object $user the drupal user object
* @param string $userKey the id of the user from the uf object
* @param string $mail the email address of the user
* @param string $uf the name of the user framework
* @param integer $status returns the status if user created or already exits (used for CMS sync)
*
* @return the ufmatch object that was found or created
* @access public
* @static
*/
static function &synchronizeUFMatch( &$user, $userKey, $mail, $uf, $status = null, $ctype = null ) {
// validate that mail is a valid email address. hopefully there is
// not too many conflicting emails between the CMS and CiviCRM
require_once 'CRM/Utils/Rule.php';
if ( ! CRM_Utils_Rule::email( $mail ) ) {
return $status ? null : false;
}
$newContact = false;
// make sure that a contact id exists for this user id
$ufmatch =& new CRM_Core_DAO_UFMatch( );
$ufmatch->uf_id = $userKey;
$ufmatch->domain_id = CRM_Core_Config::domainID( );
if ( ! $ufmatch->find( true ) ) {
require_once 'CRM/Contact/BAO/Contact.php';
$dao =& CRM_Contact_BAO_Contact::matchContactOnEmail( $mail, $ctype );
if ( $dao ) {
$ufmatch->contact_id = $dao->contact_id;
$ufmatch->domain_id = $dao->domain_id ;
$ufmatch->email = $mail;
} else {
require_once 'CRM/Core/BAO/LocationType.php';
$locationType =& CRM_Core_BAO_LocationType::getDefault( );
$params = array( 'email' => $mail, 'location_type' => $locationType->name );
if ( $ctype == 'Organization' ) {
$params['organization_name'] = $mail;
} else if ( $ctype == 'Household' ) {
$params['household_name'] = $mail;
}
if ( ! $ctype ) {
$ctype = "Individual";
}
$params['contact_type'] = $ctype;
// extract first / middle / last name
// for joomla
if ( $uf == 'Joomla' && $user->name ) {
$name = trim( $user->name );
$names = explode( ' ', $user->name );
if ( count( $names ) == 1 ) {
$params['first_name'] = $names[0];
} else if ( count( $names ) == 2 ) {
$params['first_name'] = $names[0];
$params['last_name' ] = $names[1];
} else {
$params['first_name' ] = $names[0];
$params['middle_name'] = $names[1];
$params['last_name' ] = $names[2];
}
}
require_once 'api/Contact.php';
$contact =& crm_create_contact( $params, $ctype, false );
if ( is_a( $contact, 'CRM_Core_Error' ) ) {
CRM_Core_Error::debug( 'error', $contact );
exit(1);
}
$ufmatch->contact_id = $contact->id;
$ufmatch->domain_id = $contact->domain_id ;
$ufmatch->email = $mail;
}
$ufmatch->save( );
$newContact = true;
}
if ( $status ) {
return $newContact;
} else {
return $ufmatch;
}
}
/**
* update the email in the user object
*
* @param int $contactId id of the contact to delete
*
* @return void
* @access public
* @static
*/
static function updateUFEmail( $contactId ) {
$email = CRM_Contact_BAO_Contact::getPrimaryEmail( $contactId );
if ( ! $email ) {
return;
}
$ufmatch =& new CRM_Core_DAO_UFMatch( );
$ufmatch->contact_id = $contactId;
if ( ! $ufmatch->find( true ) || $ufmatch->email == $email ) {
// if object does not exist or the email has not changed
return;
}
// save the updated ufmatch object
$ufmatch->email = $email;
$ufmatch->save( );
$config =& CRM_Core_Config::singleton( );
if ( $config->userFramework == 'Drupal' ) {
$user = user_load( array( 'uid' => $ufmatch->uf_id ) );
user_save( $user, array( 'mail' => $email ) );
$user = user_load( array( 'uid' => $ufmatch->uf_id ) );
}
}
/**
* Update the email value for the contact and user profile
*
* @param $contactId Int Contact ID of the user
* @param $email String email to be modified for the user
*
* @return void
* @access public
* @static
*/
static function updateContactEmail($contactId, $emailAddress)
{
$ufmatch =& new CRM_Core_DAO_UFMatch( );
$ufmatch->contact_id = $contactId;
if ( $ufmatch->find( true ) ) {
// Save the email in UF Match table
$ufmatch->email = $emailAddress;
$ufmatch->save( );
//check if the primary email for the contact exists
//$contactDetails[1] - email
//$contactDetails[3] - location id
$contactDetails = CRM_Contact_BAO_Contact::getEmailDetails($contactId);
if (trim($contactDetails[1])) {
//update if record is found
$query ="UPDATE civicrm_contact, civicrm_location,civicrm_email
SET email = %1
WHERE civicrm_location.entity_table = 'civicrm_contact'
AND civicrm_contact.id = civicrm_location.entity_id
AND civicrm_location.is_primary = 1
AND civicrm_location.id = civicrm_email.location_id
AND civicrm_email.is_primary = 1
AND civicrm_contact.id = %2";
$p = array( 1 => array( $emailAddress, 'String' ),
2 => array( $contactId , 'Integer' ) );
$dao =& CRM_Core_DAO::executeQuery( $query, $p );
} else {
//else insert a new email record
$email =& new CRM_Core_DAO_Email();
$email->location_id = $contactDetails[3];
$email->is_primary = 1;
$email->email = $emailAddress;
$email->save( );
$emailID = $email->id;
}
require_once 'CRM/Core/BAO/Log.php';
// we dont know the email id, so we use the location id
CRM_Core_BAO_Log::register( $contactId,
'civicrm_location',
$contactDetails[3] );
}
}
/**
* Delete the object records that are associated with this contact
*
* @param int $contactID id of the contact to delete
*
* @return void
* @access public
* @static
*/
static function deleteContact( $contactID ) {
$ufmatch =& new CRM_Core_DAO_UFMatch( );
$ufmatch->contact_id = $contactID;
$ufmatch->delete( );
}
/**
* Delete the object records that are associated with this cms user
*
* @param int $ufID id of the user to delete
*
* @return void
* @access public
* @static
*/
static function deleteUser( $ufID ) {
$ufmatch =& new CRM_Core_DAO_UFMatch( );
$ufmatch->uf_id = $ufID;
$ufmatch->delete( );
}
/**
* get the contact_id given a uf_id
*
* @param int $ufID Id of UF for which related contact_id is required
*
* @return int contact_id on success, null otherwise
* @access public
* @static
*/
static function getContactId( $ufID ) {
if (!isset($ufID)) {
return null;
}
$ufmatch =& new CRM_Core_DAO_UFMatch( );
$ufmatch->uf_id = $ufID;
if ( $ufmatch->find( true ) ) {
return $ufmatch->contact_id;
}
return null;
}
/**
* get the uf_id given a contact_id
*
* @param int $contactID ID of the contact for which related uf_id is required
*
* @return int uf_id of the given contact_id on success, null otherwise
* @access public
* @static
*/
static function getUFId( $contactID ) {
if (!isset($contactID)) {
return null;
}
$ufmatch =& new CRM_Core_DAO_UFMatch( );
$ufmatch->contact_id = $contactID;
if ( $ufmatch->find( true ) ) {
return $ufmatch->uf_id;
}
return null;
}
/**
* get the list of contact_id
*
*
* @return int contact_id on success, null otherwise
* @access public
* @static
*/
static function getContactIDs() {
$id = array();
$dao =& new CRM_Core_DAO_UFMatch();
$dao->find();
while ($dao->fetch()) {
$id[] = $dao->contact_id;
}
return $id;
}
}
?>
| zakiya/Peoples-History | sites/all/modules/civicrm/CRM/Core/BAO/UFMatch.php | PHP | gpl-2.0 | 14,673 |
package br.com.br.gatend.GestaoCliente.v1.model.vo;
import oracle.jbo.server.ViewObjectImpl;
// ---------------------------------------------------------------------
// --- File generated by Oracle ADF Business Components Design Time.
// --- Wed Jul 16 14:20:16 BRT 2014
// --- Custom code may be added to this class.
// --- Warning: Do not modify method signatures of generated methods.
// ---------------------------------------------------------------------
public class FndDocumentsVOImpl extends ViewObjectImpl {
/**
* This is the default constructor (do not remove).
*/
public FndDocumentsVOImpl() {
}
}
| mmacedoeu/adf_gcli | Model/src/br/com/br/gatend/GestaoCliente/v1/model/vo/FndDocumentsVOImpl.java | Java | gpl-2.0 | 663 |
/*
* RapidMiner
*
* Copyright (C) 2001-2008 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.example.set;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.AttributeRole;
import com.rapidminer.example.AttributeTransformation;
import com.rapidminer.example.Attributes;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.Statistics;
import com.rapidminer.example.table.ExampleTable;
/**
* An implementation of ExampleSet that allows the replacement of missing values
* on the fly. Missing values will be replaced by the average of all other values
* or by the mean.
*
* @author Ingo Mierswa
* @version $Id: ReplaceMissingExampleSet.java,v 1.8 2008/05/09 19:22:49 ingomierswa Exp $
*/
public class ReplaceMissingExampleSet extends AbstractExampleSet {
private static final long serialVersionUID = -5662936146589379273L;
/** Currently used attribute weights. Used also for example creation. */
private Map<String, Double> replacementMap;
/** The parent example set. */
private ExampleSet parent;
public ReplaceMissingExampleSet(ExampleSet exampleSet) {
this(exampleSet, null);
}
public ReplaceMissingExampleSet(ExampleSet exampleSet, Map<String, Double> replacementMap) {
this.parent = (ExampleSet)exampleSet.clone();
if (replacementMap == null) {
this.replacementMap = new HashMap<String, Double>();
for (Attribute attribute : parent.getAttributes())
addReplacement(attribute);
} else {
this.replacementMap = replacementMap;
}
Iterator<AttributeRole> a = this.parent.getAttributes().allAttributeRoles();
while (a.hasNext()) {
AttributeRole role = a.next();
Attribute currentAttribute = role.getAttribute();
currentAttribute.addTransformation(new AttributeTransformationReplaceMissing(this.replacementMap));
}
}
/** Clone constructor. */
public ReplaceMissingExampleSet(ReplaceMissingExampleSet exampleSet) {
this.parent = (ExampleSet)exampleSet.parent.clone();
this.replacementMap = new HashMap<String, Double>();
for (String name : exampleSet.replacementMap.keySet()) {
this.replacementMap.put(name, Double.valueOf(exampleSet.replacementMap.get(name).doubleValue()));
}
Iterator<AttributeRole> a = this.parent.getAttributes().allAttributeRoles();
while (a.hasNext()) {
AttributeRole role = a.next();
Attribute currentAttribute = role.getAttribute();
AttributeTransformation transformation = currentAttribute.getLastTransformation();
if (transformation != null)
if (transformation instanceof AttributeTransformationReplaceMissing)
((AttributeTransformationReplaceMissing)transformation).setReplacementMap(this.replacementMap);
}
}
public Map<String, Double> getReplacementMap() {
return this.replacementMap;
}
public void addReplacement(Attribute attribute) {
recalculateAttributeStatistics(attribute);
if (attribute.isNominal())
this.replacementMap.put(attribute.getName(), getStatistics(attribute, Statistics.MODE));
else
this.replacementMap.put(attribute.getName(), getStatistics(attribute, Statistics.AVERAGE));
}
public Attributes getAttributes() {
return this.parent.getAttributes();
}
public boolean equals(Object o) {
if (!super.equals(o))
return false;
if (!(o instanceof ReplaceMissingExampleSet))
return false;
boolean result = super.equals(o);
if (result) {
Map<String,Double> otherMap = ((ReplaceMissingExampleSet)o).replacementMap;
if (this.replacementMap.size() != otherMap.size())
return false;
for (String name : this.replacementMap.keySet()) {
if (!this.replacementMap.get(name).equals(otherMap.get(name)))
return false;
}
}
return true;
}
public int hashCode() {
return super.hashCode() ^ replacementMap.hashCode();
}
/**
* Creates a new example set reader.
*/
public Iterator<Example> iterator() {
return new AttributesExampleReader(parent.iterator(), this);
}
public Example getExample(int index) {
return this.parent.getExample(index);
}
public ExampleTable getExampleTable() {
return parent.getExampleTable();
}
public int size() {
return parent.size();
}
}
| ntj/ComplexRapidMiner | src/com/rapidminer/example/set/ReplaceMissingExampleSet.java | Java | gpl-2.0 | 5,304 |
package com.lionsteel.tiles.Scenes.GameScenes;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.modifier.ScaleModifier;
import org.andengine.entity.modifier.SequenceEntityModifier;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.text.Text;
import org.andengine.util.debug.Debug;
import org.andengine.util.modifier.ease.EaseCubicIn;
import org.andengine.util.modifier.ease.EaseCubicOut;
import com.lionsteel.tiles.SharedResources;
import com.lionsteel.tiles.SongManager;
import com.lionsteel.tiles.BaseClasses.PracticeGameScene;
import com.lionsteel.tiles.BaseClasses.TilesMenuButton;
import com.lionsteel.tiles.BaseClasses.TilesMenuScene;
import com.lionsteel.tiles.BaseClasses.TouchControl;
import com.lionsteel.tiles.Constants.Difficulty;
import com.lionsteel.tiles.Constants.GameMode;
import com.lionsteel.tiles.Constants.TilesConstants;
import com.lionsteel.tiles.Scenes.MenuScenes.SetupScene;
public class PracticeGameOverScene extends TilesMenuScene implements TilesConstants
{
final Text titleText;
final Text holdToRestartText;
final Text gameModeLabel;
final Text difficultyLabel;
final Text difficultyValue;
final Text labelOne;
final Text labelTwo;
final Text valueOne;
final Text valueTwo;
final Text newRecordText;
final TouchControl restartTouchControl;
final float START_Y = 80;
public PracticeGameOverScene()
{
super();
this.setBackgroundEnabled(false);
final Rectangle background = new Rectangle(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, activity.getVertexBufferObjectManager());
background.setColor(0, 0, 0, OVERLAY_BACKGROUND_ALPHA);
this.attachChild(background);
background.setZIndex(BACKGROUND_Z);
gameModeLabel = new Text(0, 0, SharedResources.getInstance().headingFont, "Time-Attack", 20, activity.getVertexBufferObjectManager());
gameModeLabel.setScale(.9f);
gameModeLabel.setPosition((CAMERA_WIDTH - gameModeLabel.getWidth()) / 2, START_Y);
titleText = new Text(0, 0, SharedResources.getInstance().headingFont, "Results", activity.getVertexBufferObjectManager());
titleText.setPosition((CAMERA_WIDTH - titleText.getWidth()) / 2, gameModeLabel.getY() + gameModeLabel.getHeight() + LABEL_SPACING);
this.attachChild(titleText);
holdToRestartText = new Text(0, 0, SharedResources.getInstance().mFont, "Hold to restart", activity.getVertexBufferObjectManager());
holdToRestartText.setPosition((CAMERA_WIDTH - holdToRestartText.getWidth()) / 2, CAMERA_HEIGHT - holdToRestartText.getHeight() - 50);
this.attachChild(holdToRestartText);
difficultyLabel = new Text(0, 0, SharedResources.getInstance().mFont, "Difficulty", 20, activity.getVertexBufferObjectManager());
difficultyValue = new Text(0, 0, SharedResources.getInstance().mFont, "Normal", activity.getVertexBufferObjectManager());
labelOne = new Text(0, 0, SharedResources.getInstance().mFont, "Label One", 20, activity.getVertexBufferObjectManager());
labelTwo = new Text(0, 0, SharedResources.getInstance().mFont, "Label Two", 20, activity.getVertexBufferObjectManager());
valueOne = new Text(0, 0, SharedResources.getInstance().mFont, "0", 20, activity.getVertexBufferObjectManager());
valueTwo = new Text(0, 0, SharedResources.getInstance().mFont, "0", 20, activity.getVertexBufferObjectManager());
newRecordText = new Text(0, 0, SharedResources.getInstance().mFont, "New Record!", activity.getVertexBufferObjectManager());
valueOne.setColor(VALUE_TEXT_COLOR);
valueTwo.setColor(VALUE_TEXT_COLOR);
difficultyValue.setColor(VALUE_TEXT_COLOR);
updateTextPositions();
this.attachChild(gameModeLabel);
this.attachChild(difficultyLabel);
this.attachChild(difficultyValue);
this.attachChild(labelOne);
this.attachChild(labelTwo);
this.attachChild(valueOne);
this.attachChild(valueTwo);
this.attachChild(newRecordText);
//Set this above because this text can bounce if it's a new record
valueTwo.setZIndex(FOREGROUND_Z);
restartTouchControl = new TouchControl("Ready", new Runnable()
{
@Override
public void run()
{
if (mParentScene instanceof PracticeGameScene)
((PracticeGameScene) mParentScene).restartGame();
else
Debug.e(mParentScene + " not PracticeGameScene");
}
}, null);
restartTouchControl.setPosition((CAMERA_WIDTH - restartTouchControl.outerImage.getWidth()) / 2, CAMERA_HEIGHT - restartTouchControl.outerImage.getHeight() - 100);
this.attachChild(restartTouchControl);
final TilesMenuButton quitButton = new TilesMenuButton(SharedResources.getInstance().exitGameButtonRegion, new Runnable()
{
@Override
public void run()
{
activity.onBackPressed();
}
});
quitButton.setPosition(CAMERA_WIDTH - 3 - quitButton.getWidth(), (CAMERA_HEIGHT - quitButton.getHeight()) / 2);
addButton(quitButton);
this.sortChildren();
}
public void setLabels(final String labelOne, final String labelTwo)
{
this.labelOne.setText(labelOne);
this.labelTwo.setText(labelTwo);
updateTextPositions();
}
public void setValues(final CharSequence valueOne, final CharSequence valueTwo)
{
this.gameModeLabel.setText(GameMode.getName(SetupScene.getGameMode()));
this.difficultyValue.setText(Difficulty.getName(SetupScene.getDifficulty()));
this.valueOne.setText(valueOne);
this.valueTwo.setText(valueTwo);
this.valueTwo.clearEntityModifiers();
this.valueTwo.setScale(1.0f);
this.valueTwo.setRotation(0);
newRecordText.clearEntityModifiers();
newRecordText.setVisible(false);
updateTextPositions();
}
private void updateTextPositions()
{
this.gameModeLabel.setX((CAMERA_WIDTH - gameModeLabel.getWidth()) / 2);
this.difficultyLabel.setPosition((CAMERA_WIDTH - difficultyLabel.getWidth()) / 2, titleText.getY() + titleText.getHeight() + LABEL_SPACING * 4);
this.difficultyValue.setPosition((CAMERA_WIDTH - difficultyValue.getWidth()) / 2, difficultyLabel.getY() + difficultyLabel.getHeight() + LABEL_SPACING);
this.labelOne.setPosition((CAMERA_WIDTH - this.labelOne.getWidth()) / 2, difficultyValue.getY() + difficultyValue.getHeight() + LABEL_SPACING * 2);
this.valueOne.setPosition(labelOne.getX() + (labelOne.getWidth() - valueOne.getWidth()) / 2, labelOne.getY() + labelOne.getHeight() + LABEL_SPACING);
this.labelTwo.setPosition((CAMERA_WIDTH - this.labelTwo.getWidth()) / 2, valueOne.getY() + valueOne.getHeight() + LABEL_SPACING * 2);
this.valueTwo.setPosition(labelTwo.getX() + (labelTwo.getWidth() - valueTwo.getWidth()) / 2, labelTwo.getY() + labelTwo.getHeight() + LABEL_SPACING);
this.newRecordText.setPosition((CAMERA_WIDTH-newRecordText.getWidth())/2, valueTwo.getY()+valueTwo.getHeight()+LABEL_SPACING*2);
}
@Override
public void logFlurryEvent()
{
}
@Override
public void registerTouchAreas()
{
registerTouchArea(restartTouchControl.outerImage);
super.registerTouchAreas();
}
@Override
public void initScene()
{
restartTouchControl.initButton();
SongManager.getInstance().setVolumeMultiplier(MUFFLED_VOLUME);
}
public void pulseNewRecord()
{
final float pulseSeconds = 1.0f;
final float PULSE_SCALE = 1.6f;
final float PULSE_ROTATION = 3;
this.valueTwo.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(pulseSeconds / 2, 1.0f, PULSE_SCALE, EaseCubicOut.getInstance()), new ScaleModifier(pulseSeconds / 2, PULSE_SCALE, 1.0f, EaseCubicIn.getInstance()))));
this.valueTwo.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new RotationModifier(pulseSeconds, -PULSE_ROTATION, PULSE_ROTATION), new RotationModifier(pulseSeconds, PULSE_ROTATION, -PULSE_ROTATION))));
this.newRecordText.setVisible(true);
this.newRecordText.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(pulseSeconds / 2, 1.0f, PULSE_SCALE, EaseCubicOut.getInstance()), new ScaleModifier(pulseSeconds / 2, PULSE_SCALE, 1.0f, EaseCubicIn.getInstance()))));
this.newRecordText.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new RotationModifier(pulseSeconds, -PULSE_ROTATION / 4, PULSE_ROTATION / 4), new RotationModifier(pulseSeconds, PULSE_ROTATION / 4, -PULSE_ROTATION / 4))));
}
@Override
protected void exitScene()
{
// TODO Auto-generated method stub
}
}
| maggardJosh/Tiles | src/com/lionsteel/tiles/Scenes/GameScenes/PracticeGameOverScene.java | Java | gpl-2.0 | 8,347 |
package com.dynamo2.myerp.dynamicform.dao;
import java.util.Collections;
import java.util.List;
import javax.persistence.Query;
import com.dynamo2.myerp.dynamicform.dao.entities.resultmap.FormMDStatisticsEntry;
import org.springframework.stereotype.Repository;
import com.dynamo2.myerp.AbstractBaseDAO;
import com.dynamo2.myerp.dynamicform.dao.entities.FormMetadata;
@Repository("formMetadataDAO")
public class FormMetadataDAO extends AbstractBaseDAO<FormMetadata> {
public FormMetadata findFormMetadataByName(String formName) {
Query q = em.createNamedQuery("findFormMetadataByName");
q.setParameter(1, formName);
List rst = q.getResultList();
if (rst == null || rst.isEmpty()) {
return null;
}
return (FormMetadata) rst.get(0);
}
public List<FormMetadata> listAll() {
Query q = em.createNamedQuery("listAll");
List rst = q.getResultList();
if (rst == null || rst.isEmpty()) {
return Collections.emptyList();
}
return rst;
}
public List<FormMetadata> listAllByCategory(String category) {
Query q = em.createNamedQuery("listAllByCategory");
q.setParameter(1, category.toLowerCase());
return q.getResultList();
}
public List<FormMetadata> listByParentForm(Long parentFormID) {
Query q = em.createNamedQuery("listByParentForm");
q.setParameter(1, parentFormID);
return q.getResultList();
}
public List<FormMDStatisticsEntry> statisticsByStatus() {
Query q = em.createNamedQuery("statisticsByStatus");
return q.getResultList();
}
public void updateCategory(FormMetadata fm){
Query q = em.createQuery("update table form_metadata set nav_category_id=? and seq_number=? where id=?");
q.setParameter(0,fm.getNavCategoryId());
q.setParameter(1,fm.getSeqNumber());
q.setParameter(2,fm.getId());
q.executeUpdate();
}
}
| dynamo2/tianma | mycrm/src/main/java/com/dynamo2/myerp/dynamicform/dao/FormMetadataDAO.java | Java | gpl-2.0 | 1,872 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package researchpaper;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
*
* @author aditya
*/
public interface MergeThreadCompleteListener {
Set<MergeThread> runningThreads = new CopyOnWriteArraySet<MergeThread>();
public void notifyOnThreadComplete(MergeThread thread);
public void addSource(MergeThread thread);
public void removeSource(MergeThread thread);
public boolean allThreadsfinished();
}
| adityashah30/distributedsort | src/researchpaper/MergeThreadCompleteListener.java | Java | gpl-2.0 | 555 |
<?php
// MyDMS. Document Management System
// Copyright (C) 2010 Matteo Lucarelli
//
// 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., 675 Mass Ave, Cambridge, MA 02139, USA.
include("../inc/inc.Settings.php");
include("../inc/inc.DBInit.php");
include("../inc/inc.Utils.php");
include("../inc/inc.Language.php");
include("../inc/inc.ClassUI.php");
include("../inc/inc.Authentication.php");
if (!$user->isAdmin()) {
UI::exitError(getMLText("admin_tools"),getMLText("access_denied"));
}
if (isset($_GET["logname"])) $logname=$_GET["logname"];
else $logname=NULL;
if (isset($_GET["mode"])) $mode=$_GET["mode"];
else $mode='web';
$tmp = explode('.', basename($_SERVER['SCRIPT_FILENAME']));
$view = UI::factory($theme, $tmp[1], array('dms'=>$dms, 'user'=>$user, 'logname'=>$logname, 'mode'=>$mode, 'contentdir'=>$settings->_contentDir));
if($view) {
$view->show();
exit;
}
?>
| JustLikeIcarus/SeedDMS | out/out.LogManagement.php | PHP | gpl-2.0 | 1,528 |
<?php
require_once '../lib/DataSourceResult.php';
require_once '../lib/Kendo/Autoload.php';
require_once '../include/header.php';
?>
<div class="demo-section k-rtl">
<h2>Select Continents</h2>
<?php
$multiselect = new \Kendo\UI\MultiSelect('select');
$multiselect->dataTextField('text')
->dataValueField('value')
->dataSource(array(
array('text' => 'Africa', 'value' => '1'),
array('text' => 'Europe', 'value' => '2'),
array('text' => 'Asia', 'value' => '3'),
array('text' => 'North America', 'value' => '4'),
array('text' => 'South America', 'value' => '5'),
array('text' => 'Antarctica', 'value' => '6'),
array('text' => 'Australia', 'value' => '7')
));
echo $multiselect->render();
?>
<style scoped>
.demo-section {
width: 250px;
margin: 35px auto 50px;
padding: 30px;
}
.demo-section h2 {
text-transform: uppercase;
font-size: 1.2em;
margin-bottom: 10px;
}
</style>
</div>
<?php require_once '../include/footer.php'; ?>
| kabsila/wordpress | new/wrappers/php/multiselect/right-to-left-support.php | PHP | gpl-2.0 | 1,197 |
<?php
/*
Template Name: Search_results
*/
?>
<?php get_header(); ?>
<ul class="columna primera">
<?php blogsfera_widget_my_blog(); ?>
<?php blogsfera_widget_chat(); ?>
<?php blogsfera_widget_most_read(); ?>
<?php blogsfera_widget_news(); ?>
</ul>
<ul class="columna">
<?php blogsfera_widget_search_results(); ?>
<?php blogsfera_widget_recent_users(); ?>
<?php blogsfera_widget_recent_articles(); ?>
</ul>
<ul class="columna">
<?php blogsfera_widget_search(); ?>
<?php blogsfera_widget_avisos(array('blog_id' => 2)); ?>
<?php blogsfera_widget_tag_cloud(); ?>
</ul>
<?php get_footer(); ?>
| alx/blogsfera | wp-content/themes/portal/search_results.php | PHP | gpl-2.0 | 602 |
# -*- coding: utf-8 -*-
from flask import Flask
from flask.ext.pymongo import PyMongo
import config
from views import diary
def create_app(cfg):
app = Flask(__name__)
app.config.from_object(cfg)
return app
# Application creation.
app = create_app(config)
# Database configuration.
db = PyMongo()
# Blueprints registration.
app.register_blueprint(diary)
if __name__ == '__main__':
app.run()
| GruPy-RN/agenda_flask | diary/__init__.py | Python | gpl-2.0 | 416 |
//-----------------------------------------------------------------------------
// Class: CParaMeshXMLFile
// Authors: LiXizhi
// Emails: LiXizhi@yeah.net
// Company: ParaEngine Corporation
// Date: 2007.12.16
// Desc:
//-----------------------------------------------------------------------------
#include "ParaEngine.h"
#include "FileManager.h"
#include "BaseObject.h"
#ifdef PARAENGINE_MOBILE
#include <tinyxml2.h>
#else
#include <tinyxml.h>
#include <xpath_processor.h>
#endif
#include "ParaMeshXMLFile.h"
#include "memdebug.h"
using namespace ParaEngine;
/** @def larger than which mesh file can not be loaded. */
#define SUPPORTED_MESH_FILE_VERSION 0
CParaMeshXMLFile::CParaMeshXMLFile(void)
{
m_nType = TYPE_MESH_LOD;
m_nPrimaryShader = TECH_SIMPLE_MESH_NORMAL;
m_nVersion = 0;
m_bHasBoundingBox = false;
m_vMinPos = Vector3(0,0,0);
m_vMaxPos = Vector3(0,0,0);
}
CParaMeshXMLFile::~CParaMeshXMLFile(void)
{
}
bool ParaEngine::CParaMeshXMLFile::LoadFromFile( const string& filename )
{
// auto set parent directory to be the parent directory of the input file.
return LoadFromFile(filename, CParaFile::GetParentDirectoryFromPath(filename));
}
bool ParaEngine::CParaMeshXMLFile::LoadFromFile(const string& filename, const string& parentDir)
{
CParaFile file(filename.c_str());
if(!file.isEof())
{
SetParentDirectory(parentDir);
// load
return LoadFromBuffer(file.getBuffer(), (int)file.getSize());
}
return false;
}
/** sample ParaEngine mesh xml file
<mesh version=1 type=0>
<boundingbox minx=0 miny=0 minz=0 maxx=1 maxy=1 maxz=1/>
<shader index=3/>
<submesh loddist=10 filename="LOD_10.x"/>
<submesh loddist=50 filename="LOD_50.x"/>
</mesh>
*/
bool ParaEngine::CParaMeshXMLFile::LoadFromBuffer(const char* pData, int nSize)
{
#ifdef PARAENGINE_MOBILE
namespace TXML = tinyxml2;
try
{
TXML::XMLDocument doc(true, TXML::COLLAPSE_WHITESPACE);
doc.Parse(pData, nSize);
TXML::XMLElement* pRoot = doc.RootElement();
if (pRoot)
{
pRoot->QueryIntAttribute("version", &m_nVersion);
if (m_nVersion < SUPPORTED_MESH_FILE_VERSION)
{
OUTPUT_LOG("can not load para mesh xml file. because of a lower file version.\n");
}
int nType = 0;
pRoot->QueryIntAttribute("type", &nType);
m_nType = (ParaMeshXMLType)nType;
for (TXML::XMLNode* pChild = pRoot->FirstChild(); pChild != 0; pChild = pChild->NextSibling())
{
TXML::XMLElement* pElement = pChild->ToElement();
if (pElement)
{
std::string tagName = pElement->Name();
if (tagName == "boundingbox")
{
pElement->QueryFloatAttribute("minx", &m_vMinPos.x);
pElement->QueryFloatAttribute("miny", &m_vMinPos.y);
pElement->QueryFloatAttribute("minz", &m_vMinPos.z);
pElement->QueryFloatAttribute("maxx", &m_vMaxPos.x);
pElement->QueryFloatAttribute("maxy", &m_vMaxPos.y);
pElement->QueryFloatAttribute("maxz", &m_vMaxPos.z);
}
else if (tagName == "shader")
{
pElement->QueryIntAttribute("index", &m_nPrimaryShader);
// TODO: for shader parameters
for (TXML::XMLNode* pSubChild = pElement->FirstChild(); pSubChild != 0; pSubChild = pSubChild->NextSibling())
{
TXML::XMLElement* pParamElement = pSubChild->ToElement();
if (pParamElement)
{
std::string tagName = pParamElement->Name();
if (tagName == "params")
{
CParameter p;
// param name
p.SetName(pParamElement->Attribute("name", ""));
p.SetTypeByString(pParamElement->Attribute("type", ""));
p.SetValueByString(pParamElement->GetText());
m_paramBlock.AddParameter(p);
}
}
}
}
else if (tagName == "submesh")
{
CSubMesh meshInfo;
pElement->QueryFloatAttribute("loddist", &meshInfo.m_fToCameraDist);
std::string filepath = pElement->Attribute("filename");
// check if it is relative path or absolute path
if (filepath.find('/') != string::npos || filepath.find('\\') != string::npos)
meshInfo.m_sFileName = filepath;
else
meshInfo.m_sFileName = m_sParentDirectory + filepath;
m_SubMeshes.push_back(meshInfo);
}
}
}
}
}
catch (...)
{
OUTPUT_LOG("error parsing xml file %s**.xml \n", m_sParentDirectory.c_str());
return false;
}
return m_SubMeshes.size() > 0;
#else
TiXmlDocument doc;
try
{
doc.Parse(pData, 0, TIXML_DEFAULT_ENCODING);
TiXmlElement* pRoot = doc.RootElement();
if (pRoot != 0)
{
// get mesh file version
TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/@version");
TinyXPath::expression_result res = xpathProc.er_compute_xpath();
TinyXPath::node_set* pNodeSet = res.nsp_get_node_set();
if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0)
{
const TiXmlAttribute* att = pNodeSet->XAp_get_attribute_in_set(0);
m_nVersion = att->IntValue();
}
if (m_nVersion < SUPPORTED_MESH_FILE_VERSION)
{
OUTPUT_LOG("can not load para mesh xml file. because of a lower file version.\n");
}
{
// get mesh type
TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/@type");
TinyXPath::expression_result res = xpathProc.er_compute_xpath();
TinyXPath::node_set* pNodeSet = res.nsp_get_node_set();
if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0)
{
const TiXmlAttribute* att = pNodeSet->XAp_get_attribute_in_set(0);
m_nType = (ParaMeshXMLType)att->IntValue();
}
}
{
// get mesh bounding box
TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/boundingbox");
TinyXPath::expression_result res = xpathProc.er_compute_xpath();
TinyXPath::node_set* pNodeSet = res.nsp_get_node_set();
if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0)
{
const TiXmlElement* pElem = pNodeSet->XNp_get_node_in_set(0)->ToElement();
// parse attributes
const TiXmlAttribute* pAttr = pElem->FirstAttribute();
if (pAttr) {
m_bHasBoundingBox = true;
for (; pAttr; pAttr = pAttr->Next())
{
string sName = pAttr->Name();
if (sName == "minx")
{
m_vMinPos.x = (float)(pAttr->DoubleValue());
}
else if (sName == "miny")
{
m_vMinPos.y = (float)(pAttr->DoubleValue());
}
else if (sName == "minz")
{
m_vMinPos.z = (float)(pAttr->DoubleValue());
}
else if (sName == "maxx")
{
m_vMaxPos.x = (float)(pAttr->DoubleValue());
}
else if (sName == "maxy")
{
m_vMaxPos.y = (float)(pAttr->DoubleValue());
}
else if (sName == "maxz")
{
m_vMaxPos.z = (float)(pAttr->DoubleValue());
}
}
}
}
}
{
// get shader index.
TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/shader/@index");
TinyXPath::expression_result res = xpathProc.er_compute_xpath();
TinyXPath::node_set* pNodeSet = res.nsp_get_node_set();
if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0)
{
const TiXmlAttribute* att = pNodeSet->XAp_get_attribute_in_set(0);
m_nPrimaryShader = att->IntValue();
}
}
{
// get shader parameters.
TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/shader/param");
TinyXPath::expression_result res = xpathProc.er_compute_xpath();
TinyXPath::node_set* pNodeSet = res.nsp_get_node_set();
if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0)
{
int nCount = pNodeSet->u_get_nb_node_in_set();
for (int i = 0; i < nCount; ++i)
{
// for each parameter
const TiXmlNode* node = pNodeSet->XNp_get_node_in_set(i);
CParameter p;
{
// param name
TinyXPath::xpath_processor xpathProc1(node->ToElement(), "@name");
TinyXPath::expression_result res1 = xpathProc1.er_compute_xpath();
TinyXPath::node_set* pNodeSet1 = res1.nsp_get_node_set();
if (pNodeSet1 != 0 && pNodeSet1->u_get_nb_node_in_set() > 0)
{
const TiXmlAttribute* att = pNodeSet1->XAp_get_attribute_in_set(0);
p.SetName(att->Value());
}
}
{
// get type
TinyXPath::xpath_processor xpathProc1(node->ToElement(), "@type");
TinyXPath::expression_result res1 = xpathProc1.er_compute_xpath();
TinyXPath::node_set* pNodeSet1 = res1.nsp_get_node_set();
if (pNodeSet1 != 0 && pNodeSet1->u_get_nb_node_in_set() > 0)
{
const TiXmlAttribute* att = pNodeSet1->XAp_get_attribute_in_set(0);
p.SetTypeByString(att->Value());
}
}
const TiXmlElement * pParamElement = node->ToElement();
if (pParamElement)
{
// get text value
p.SetValueByString(pParamElement->GetText());
m_paramBlock.AddParameter(p);
}
}
}
}
{
// get mesh info.
TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/submesh");
TinyXPath::expression_result res = xpathProc.er_compute_xpath();
TinyXPath::node_set* pNodeSet = res.nsp_get_node_set();
if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0)
{
int nCount = pNodeSet->u_get_nb_node_in_set();
m_SubMeshes.resize(nCount);
for (int i = 0; i < nCount; ++i)
{
// for each sub meshes
const TiXmlNode* node = pNodeSet->XNp_get_node_in_set(i);
CSubMesh& meshInfo = m_SubMeshes[i];
{
// LOD to camera distance
TinyXPath::xpath_processor xpathProc1(node->ToElement(), "@loddist");
TinyXPath::expression_result res1 = xpathProc1.er_compute_xpath();
TinyXPath::node_set* pNodeSet1 = res1.nsp_get_node_set();
if (pNodeSet1 != 0 && pNodeSet1->u_get_nb_node_in_set() > 0)
{
const TiXmlAttribute* att = pNodeSet1->XAp_get_attribute_in_set(0);
meshInfo.m_fToCameraDist = (float)(att->DoubleValue());
}
}
{
// file name of the mesh
TinyXPath::xpath_processor xpathProc1(node->ToElement(), "@filename");
TinyXPath::expression_result res1 = xpathProc1.er_compute_xpath();
TinyXPath::node_set* pNodeSet1 = res1.nsp_get_node_set();
if (pNodeSet1 != 0 && pNodeSet1->u_get_nb_node_in_set() > 0)
{
const TiXmlAttribute* att = pNodeSet1->XAp_get_attribute_in_set(0);
string filepath = att->Value();
// check if it is relative path or absolute path
if (filepath.find('/') != string::npos || filepath.find('\\') != string::npos)
meshInfo.m_sFileName = filepath;
else
meshInfo.m_sFileName = m_sParentDirectory + filepath;
}
}
}
}
}
}
else
{
OUTPUT_LOG("error parsing xml file %s**.xml \n", m_sParentDirectory.c_str());
}
}
catch (...)
{
OUTPUT_LOG("error parsing xml file %s**.xml \n", m_sParentDirectory.c_str());
}
return m_SubMeshes.size() > 0;
#endif
}
bool ParaEngine::CParaMeshXMLFile::SaveToFile( const string& filename )
{
return false;
}
| LiXizhi/NPLRuntime | Client/trunk/ParaEngineClient/3dengine/ParaMeshXMLFile.cpp | C++ | gpl-2.0 | 10,909 |
package eu.maydu.gwt.validation.client.i18n;
public class StandardValidationMessagesImpl_en implements eu.maydu.gwt.validation.client.i18n.StandardValidationMessagesImpl {
public java.lang.String validator_assertFalse() {
return "Assertion failed";
}
public java.lang.String validator_pattern() {
return "Incorrect pattern";
}
public java.lang.String validator_ean() {
return "Invalid EAN";
}
public java.lang.String validator_creditCard() {
return "Invalid credit card number";
}
public java.lang.String min(int minValue,int actualValue) {
return "Minimum value for this field is '" + minValue + "'. You entered '" + actualValue + "'";
}
public java.lang.String max(double maxValue,double actualValue) {
return "Maximum value for this field is '" + maxValue + "'. You entered '" + actualValue + "'";
}
public java.lang.String regexNotFulfilled() {
return "The text does not fulfill the given regular expression";
}
public java.lang.String length(int minLength,int maxLength,int actualLength) {
return "Needs a length between '" + minLength + "' and '" + maxLength + "'. Was '" + actualLength + "'";
}
public java.lang.String validator_notNull() {
return "Must be given";
}
public java.lang.String notInRange(double min,double max,double value) {
return "Value '" + value + "' lies beyond the boundaries [" + min + "," + max + "]";
}
public java.lang.String validator_range() {
return "Not in range";
}
public java.lang.String max(int maxValue,int actualValue) {
return "Maximum value for this field is '" + maxValue + "'. You entered '" + actualValue + "'";
}
public java.lang.String notADouble() {
return "Not a floating point number";
}
public java.lang.String notALong() {
return "Not a whole number";
}
public java.lang.String notEqual() {
return "Should not be equal";
}
public java.lang.String validator_assertTrue() {
return "Assertion failed";
}
public java.lang.String mustSelectValue() {
return "Please select a value";
}
public java.lang.String equal() {
return "Should be equal";
}
public java.lang.String unparsableDate() {
return "Wrong date format";
}
public java.lang.String notARegEx() {
return "No valid regular expression given";
}
public java.lang.String notNull() {
return "Must be given";
}
public java.lang.String validator_future() {
return "Must be a future date";
}
public java.lang.String isNull() {
return "Should not be given";
}
public java.lang.String notInRange(float min,float max,float value) {
return "Value '" + value + "' lies beyond the boundaries [" + min + "," + max + "]";
}
public java.lang.String notAValidTimeWithSecondsRequired(java.lang.String parameter) {
return "'" + parameter + "' is not a valid time (seconds must be given)";
}
public java.lang.String min(float minValue,float actualValue) {
return "Minimum value for this field is '" + minValue + "'. You entered '" + actualValue + "'";
}
public java.lang.String validator_size() {
return "Incorrect number of elements";
}
public java.lang.String validator_past() {
return "Must be a past date";
}
public java.lang.String validator_email() {
return "Not a well-formed email address";
}
public java.lang.String notAValidEmail(java.lang.String givenEmailInput) {
return "'" + givenEmailInput + "' is not a valid email address";
}
public java.lang.String notAFloat() {
return "Not a floating point number";
}
public java.lang.String stringsNotEqual() {
return "Strings must be equal";
}
public java.lang.String notInRange(int min,int max,int value) {
return "Value '" + value + "' lies beyond the boundaries [" + min + "," + max + "]";
}
public java.lang.String notAValidCharacter(char c) {
return "Not a valid character: '" + c + "'";
}
public java.lang.String validator_max() {
return "Too big";
}
public java.lang.String validator_notEmpty() {
return "May not be null or empty";
}
public java.lang.String max(long maxValue,long actualValue) {
return "Maximum value for this field is '" + maxValue + "'. You entered '" + actualValue + "'";
}
public java.lang.String notAnInteger() {
return "Not a whole number";
}
public java.lang.String validator_min() {
return "Too small";
}
public java.lang.String validator_length() {
return "Length not correct";
}
public java.lang.String notInRange(long min,long max,long value) {
return "Value '" + value + "' lies beyond the boundaries [" + min + "," + max + "]";
}
public java.lang.String notEmpty() {
return "Mustn't be empty";
}
public java.lang.String min(long minValue,long actualValue) {
return "Minimum value for this field is '" + minValue + "'. You entered '" + actualValue + "'";
}
public java.lang.String noDateGiven() {
return "No date entered";
}
public java.lang.String notAValidTimeWithoutSeconds(java.lang.String parameter) {
return "'" + parameter + "' is not a valid time (seconds must not be given)";
}
public java.lang.String max(float maxValue,float actualValue) {
return "Maximum value for this field is '" + maxValue + "'. You entered '" + actualValue + "'";
}
public java.lang.String validator_digits() {
return "Numeric value out of bounds";
}
public java.lang.String notAValidTimeWithSecondsOptionally(java.lang.String parameter) {
return "'" + parameter + "' is not a valid time (seconds may be given)";
}
public java.lang.String min(double minValue,double actualValue) {
return "Minimum value for this field is '" + minValue + "'. You entered '" + actualValue + "'";
}
}
| midaboghetich/netnumero | gen/eu/maydu/gwt/validation/client/i18n/StandardValidationMessagesImpl_en.java | Java | gpl-2.0 | 5,885 |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package se.sics.kola.node;
public abstract class PElementValue extends Node
{
// Empty body
}
| kompics/kola | src/main/java/se/sics/kola/node/PElementValue.java | Java | gpl-2.0 | 168 |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import os
import sys
def main():
args = parseArgs(sys.argv)
# get analogy files in the analogy directory
# http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python
resultFns = [os.path.join(args.results, fn) for fn in
next(os.walk(args.results))[2]]
glbCorrCnt = 0
glbLineCnt = 0
semCorrCnt = 0
semLineCnt = 0
synCorrCnt = 0
synLineCnt = 0
for resultFn in resultFns:
lineCnt = 0
corrCnt = 0
ansInQuCnt = 0
with open(resultFn, 'rb') as resultF:
# print(resultFn)
for result in resultF:
words = result.split()
# print(words)
if words[4] == '**NO_EMBEDDING_FOR_A_WORD**':
continue
if len(words) < 5:
break
if words[3] == words[4]:
corrCnt += 1
if words[4] in words[:3]:
ansInQuCnt += 1
lineCnt += 1
if lineCnt < 1:
continue
acc = float(corrCnt) / lineCnt
ansInQu = float(ansInQuCnt) / lineCnt
print('{:s} {:0.3f} {:0.3f}'.format(
os.path.basename(resultFn),
acc, ansInQu))
glbLineCnt += lineCnt
glbCorrCnt += corrCnt
if os.path.basename(resultFn).startswith('gram'):
synCorrCnt += corrCnt
synLineCnt += lineCnt
else:
semCorrCnt += corrCnt
semLineCnt += lineCnt
if semLineCnt > 0:
print('Sem Av {:0.3f}'.format(float(semCorrCnt) / semLineCnt))
if synLineCnt > 0:
print('Syn Av {:0.3f}'.format(float(synCorrCnt) / synLineCnt))
print('Average {:0.3f}'.format(float(glbCorrCnt) / glbLineCnt))
def parseArgs(args):
parser = argparse.ArgumentParser(
description='Evaluate analogy results. Written in Python 2.7.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('results',
type=validDirectory,
help='The directory containing result files.')
return parser.parse_args()
def validDirectory(dirName):
if os.path.isdir(dirName):
return dirName
msg = 'Directory "{:s}" does not exist.'.format(dirName)
raise argparse.ArgumentTypeError(msg)
if __name__ == '__main__':
main()
| ppegusii/cs689-mini1 | src/evaluate.py | Python | gpl-2.0 | 2,517 |
<?php
/**
* WURFL API
*
* LICENSE
*
* This file is released under the GNU General Public License. Refer to the
* COPYING file distributed with this package.
*
* Copyright (c) 2008-2009, WURFL-Pro S.r.l., Rome, Italy
*
*
*
* @category WURFL
* @package WURFL_Handlers
* @copyright WURFL-PRO SRL, Rome, Italy
* @license
* @version $id$
*/
/**
* KDDIUserAgentHandler
*
*
* @category WURFL
* @package WURFL_Handlers
* @copyright WURFL-PRO SRL, Rome, Italy
* @license
* @version $id$
*/
class WURFL_Handlers_KDDIHandler extends WURFL_Handlers_Handler {
protected $prefix = "KDDI";
function __construct($wurflContext, $userAgentNormalizer = null) {
parent::__construct ( $wurflContext, $userAgentNormalizer );
}
/**
* Intercept all UAs containing "KDDI"
*
* @param string $userAgent
* @return boolean
*/
public function canHandle($userAgent) {
return WURFL_Handlers_Utils::checkIfContains ( $userAgent, "KDDI" );
}
/**
*/
function lookForMatchingUserAgent($userAgent) {
$tolerance = $this->tolerance ( $userAgent );
return WURFL_Handlers_Utils::risMatch ( array_keys ( $this->userAgentsWithDeviceID ), $userAgent, $tolerance );
}
/**
*
* @param string $userAgent
* @return string
*/
function applyRecoveryMatch($userAgent) {
if (WURFL_Handlers_Utils::checkIfContains ( $userAgent, "Opera" )) {
return "opera";
}
return "opwv_v62_generic";
}
private function tolerance($userAgent) {
if (WURFL_Handlers_Utils::checkIfStartsWith ( $userAgent, "KDDI/" )) {
return WURFL_Handlers_Utils::secondSlash ( $userAgent );
}
if (WURFL_Handlers_Utils::checkIfStartsWith ( $userAgent, "KDDI" )) {
return WURFL_Handlers_Utils::firstSlash ( $userAgent );
}
return WURFL_Handlers_Utils::indexOfOrLength ( $userAgent, ")" );
}
}
?> | chisimba/modules | wurfl/resources/WURFL/Handlers/KDDIHandler.php | PHP | gpl-2.0 | 1,840 |
package Servlets;
import org.json.JSONException;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* Created by matan on 01/10/15.
*/
@WebServlet(name = "login")
public class Logout extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
session.invalidate();
JSONObject result = new JSONObject();
try
{
result.put("success", 0);
} catch (JSONException e)
{
e.printStackTrace();
}
response.getWriter().print(result.toString());
}
}
| matanso/OASSIS | src/main/java/Servlets/Logout.java | Java | gpl-2.0 | 1,072 |
/*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Emil Ong
*/
package com.caucho.jaxb.property;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Collection;
public class XmlListBooleanArrayProperty extends XmlListArrayProperty {
public XmlListBooleanArrayProperty()
{
super(BooleanProperty.PRIMITIVE_PROPERTY);
}
protected Object read(String in)
throws IOException, JAXBException
{
String[] tokens = in.split("\\s+");
boolean[] array = new boolean[tokens.length];
for (int i = 0; i < tokens.length; i++)
array[i] = DatatypeConverter.parseBoolean(tokens[i]);
return array;
}
}
| christianchristensen/resin | modules/extra/src/com/caucho/jaxb/property/XmlListBooleanArrayProperty.java | Java | gpl-2.0 | 1,852 |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.similarities.AfterEffectL;
import org.apache.lucene.search.similarities.BM25Similarity;
import org.apache.lucene.search.similarities.BasicModelP;
import org.apache.lucene.search.similarities.DFRSimilarity;
import org.apache.lucene.search.similarities.LMDirichletSimilarity;
import org.apache.lucene.search.similarities.NormalizationH2;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class SearchOhsumedFiles {
public static class SearchResult {
public String queryId;
public String results[];
public double scores[];
}
private SearchOhsumedFiles() {
}
public static void main(String[] args) throws Exception {
String index = null;
String queries = null;
String runId = null;
float threshold = 0.0f;
for (int i = 0; i < args.length; i++) {
if ("-index".equals(args[i])) {
index = args[i + 1];
i++;
} else if ("-queries".equals(args[i])) {
queries = args[i + 1];
i++;
} else if ("-runid".equals(args[i])) {
runId = args[i + 1];
i++;
} else if ("-threshold".equals(args[i])) {
threshold = Float.parseFloat(args[i + 1]);
i++;
}
}
Similarity simfn = null;
if ("bm25".equals(runId)) {
simfn = new BM25Similarity();
} else if ("dfr".equals(runId)) {
simfn = new DFRSimilarity(new BasicModelP(), new AfterEffectL(),
new NormalizationH2());
} else if ("lm".equals(runId)) {
simfn = new LMDirichletSimilarity();
} else {
throw new IllegalArgumentException("No such similarity model: "
+ runId);
}
runSearch(index, queries, runId, threshold, simfn);
}
public static Map<String, String[]> runSearch(String index, String queries,
String runId, float threshold, Similarity simfn)
throws IOException, ParseException {
HashMap<String, String[]> results = new HashMap<String, String[]>();
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(
index)));
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(simfn);
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41);
BufferedReader in = null;
if (queries != null) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(
queries), "UTF-8"));
} else {
in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
}
MultiFieldQueryParser queryParser = new MultiFieldQueryParser(
Version.LUCENE_41, new String[] { "contents", "title" },
analyzer);
String titleQ = null, contentQ = null;
SearchResult searchResult = null;
List<SearchResult> resultsList = new ArrayList<SearchResult>();
while (true) {
assert (queries != null);
String line = in.readLine();
if (line == null || line.length() == -1) {
break;
}
if (line.contains("<top>")) {
searchResult = new SearchResult();
resultsList.add(searchResult);
continue;
} else if (line.startsWith("<num>")) {
assert (searchResult != null);
searchResult.queryId = line.split(":")[1].trim();
} else if (line.startsWith("<title>")) {
titleQ = line.split(">")[1].trim();
} else if (line.startsWith("<desc>")) {
line = in.readLine();
contentQ = line;
} else if (line.startsWith("</top>")) {
// Query query = queryParser.parse(QueryParser.escape(titleQ) +
// " " +
// QueryParser.escape(contentQ));
BooleanQuery query = new BooleanQuery();
query.add(queryParser.parse(QueryParser.escape(titleQ)),
BooleanClause.Occur.SHOULD);
query.add(queryParser.parse(QueryParser.escape(contentQ)),
BooleanClause.Occur.SHOULD);
/*
* Query query = queryParser.parse(Version.LUCENE_41, new
* String[] { QueryParser.escape(contentQ),
* QueryParser.escape(titleQ) }, new String[] { "contents",
* "title" }, analyzer);
*/
// System.out.println("Searching for: " +
// query.toString(field));
results.put(
searchResult.queryId,
performSearch(in, searcher, query,
searchResult.queryId, runId == null ? "null"
: runId, threshold));
} else {
continue;
}
}
reader.close();
return results;
}
public static String[] performSearch(BufferedReader in,
IndexSearcher searcher, Query query, String queryId, String runId,
float threshold) throws IOException {
ArrayList<String> resultsList = new ArrayList<String>();
TopDocs results = searcher.search(query, 100);
ScoreDoc[] hits = results.scoreDocs;
// not sure if dataset may have duplicates
HashSet<String> docSet = new HashSet<String>();
int start = 0;
int end = 100;
for (int i = start; i < end; i++) {
Document doc = searcher.doc(hits[i].doc);
String docno = doc.get("docno");
assert (docno != null);
if (docSet.contains(docno))
continue;
docSet.add(docno);
if (isRelevant(threshold, hits[i].score / results.getMaxScore())) {
String result = queryId + " Q0 " + docno + " " + i + " "
+ hits[i].score + " " + runId;
resultsList.add(result);
System.out.println(result);
} else
break;
}
return (String[]) resultsList.toArray(new String[resultsList.size()]);
}
private static boolean isRelevant(float threshold, float normalizedScore) {
if ((normalizedScore - threshold) > 0.0000001)
return true;
return false;
}
}
| darthcodus/Lucene-TREC-OHSUMED | src/SearchOhsumedFiles.java | Java | gpl-2.0 | 6,310 |
<?php
class Xlib_XListaDados_FieldFilter_CPF extends Xlib_XListaDados_FieldFilterAbstract {
private $punct = true;
public function getInstance ( $field , $label = "" , $punct = false ) {
return new Xlib_XListaDados_FieldFilter_CPF ( $field , $label , $punct );
}
public function formatQueryFilter ( ) {
$value = Request::get($this->filterContainer."[".$this->field."]");
if ( $value === "" ) return null ;
if ( !$this->punct ) $value = preg_replace ( '/[^\d]+/' , '' , $value );
return eval ( "return \"" . $this->template . "\" ;") ;
}
public function getPunct ( ) {
return $this->punct;
}
/**
* Remove a pontuação para buscar no banco
* @param [type] $punct [description]
*/
public function setPunct ( $punct ) {
$this->punct = (bool) $punct ;
return $this;
}
/**
*
* @param [type] $field [description]
* @param string $label [description]
* @param boolean $punct false se o CPF é salvo no banco sem pontuação. true se é salvo com pontuação
*/
public function __construct ( $field , $label = "" , $punct = false ) {
$this->setField ( $field );
$this->setLabel ( $label );
$this->setPunct ( $punct );
}
public function getFieldFormatter ( ) {
$script =
'var tmp=this.value.replace(/[^\d]+/g,\'\');console.log(tmp);switch(tmp.length){case 0:case 1:case 2:case 3:return;case 4:case 5:case 6:this.value=tmp.replace(/^(\d{3})(\d+)/,\'$1.$2\');return;case 7:case 8:case 9:this.value=tmp.replace(/^(\d{3})(\d{3})(\d+)/,\'$1.$2.$3\');return;default:this.value=tmp.replace(/^(\d{3})(\d{3})(\d{3})(\d{1,2})(.*)/,\'$1.$2.$3-$4\')}'
;
return $script ;
}
/**
* Muitas vezes você vai querer sobrescrever este método
* @return type
*/
public function __toString ( ) {
$output = $this->getSufix() ;
$attributeSet = $this->getAttributeSet ( );
$attributeSet['style'] = empty ( $attributeSet['style'] ) ? "width:125px" : $attributeSet['style'] . ";width:125px" ;
$attributeSet['placeholder'] = "___.___.___-__";
$attributeSet['onKeyPress'] = $this->getFieldFormatter();
$attributeSet['onKeyUp'] = $this->getFieldFormatter();
$attributeSet['onKeyDown'] = $this->getFieldFormatter();
$attributeSet['maxlength'] = '14';
$labelAttributeSet = array ( 'for' => $attributeSet['id'] , "class" => "control-label" );
if ( empty ( $this->label ) ) $labelAttributeSet['class'] = 'sr-only';
$output .= "<div class=\"form-group\">";
$output .= "<label " . $this->getAttributeSetAsString ( $labelAttributeSet ) . " >" . $this->label . "</label><br/>" ;
$output .= "<input " . $this->getAttributeSetAsString ( $attributeSet ) . " >";
$output .= "</div>";
// $output .= "
// <script>
// $(function(){
// $(\"#".$attributeSet['id']."\").datepicker();
// });
// </script>
// " ;
$output .= $this->getPrefix ();
return $output;
}
} | hugoofab/XLibrary | XListaDados/FieldFilter/CPF.php | PHP | gpl-2.0 | 3,135 |
package FSMBuilder.FSMmodel;
import FSMBuilder.FSMfunctions.constants.Ifile;
import FSMBuilder.FSMfunctions.constants.Imisc;
import java.awt.geom.Line2D;
/**
* Base class for all types of transitions
* @author Logan Fine
*/
public abstract class Ctrans extends CbasicFSMObject {
protected final Cnode m_from;
protected final Cnode m_to;
/**
* Default constructor
* @param from source node
* @param to finish node
*/
public Ctrans(Cnode from, Cnode to) {
super();
if (from != null && to != null) {
m_from = from;
m_to = to;
} else
throw new RuntimeException("Ctransition creation on null nodes");
}
/**
* from-node getter
* @return Cnode
*/
public Cnode getFrom() {
return m_from;
}
/**
* to-node getter
* @return Cnode
*/
public Cnode getTo() {
return m_to;
}
@Override
public boolean setLabel(Clabel l) {
if (l != null) {
m_label = l;
m_label.parse_transition();
}
return l != null;
}
@Override
public boolean hasCoords(Integer x, Integer y) {
if (x != null && y != null) {
Line2D l = new Line2D.Double(m_from.m_center.m_x, m_from.m_center.m_y,
m_to.m_center.m_x, m_to.m_center.m_y);
int toleration = 10;
int width = 20;
int height = 20;
return l.intersects(x - toleration, y - toleration, width, height);
}
return false;
}
@Override
public String toString() {
return Ifile.TYPE_TRANS + Ifile.DELIMITER + m_from.m_center.toString() +
m_to.m_center.toString() + super.toString();
}
@Override
public boolean equals(Object other) {
if (other == null || ! this.getClass().equals(other.getClass()))
return false;
if (other == this)
return true;
Ctrans t = (Ctrans) other;
return m_from.equals(t.m_from) && m_to.equals(t.m_to) &&
m_label.equals(t.m_label);
}
@Override
public int hashCode() {
return Imisc.TRANS_HASH;
}
} | nzt4567/fsa | src/main/java/FSMBuilder/FSMmodel/Ctrans.java | Java | gpl-2.0 | 2,291 |
<?php
namespace Drupal\facets\Plugin\facets\query_type;
use Drupal\facets\QueryType\QueryTypePluginBase;
use Drupal\facets\Result\Result;
/**
* Provides support for range facets within the Search API scope.
*
* This is the default implementation that works with all backends.
*
* @FacetsQueryType(
* id = "search_api_range",
* label = @Translation("Range"),
* )
*/
class SearchApiRange extends QueryTypePluginBase {
/**
* The backend's native query object.
*
* @var \Drupal\search_api\Query\QueryInterface
*/
protected $query;
/**
* {@inheritdoc}
*/
public function execute() {
$query = $this->query;
// Only alter the query when there's an actual query object to alter.
if (!empty($query)) {
$operator = $this->facet->getQueryOperator();
$field_identifier = $this->facet->getFieldIdentifier();
$exclude = $this->facet->getExclude();
// Set the options for the actual query.
$options = &$query->getOptions();
$options['search_api_facets'][$field_identifier] = [
'field' => $field_identifier,
'limit' => $this->facet->getHardLimit(),
'operator' => $this->facet->getQueryOperator(),
'min_count' => $this->facet->getMinCount(),
'missing' => FALSE,
];
// Add the filter to the query if there are active values.
$active_items = $this->facet->getActiveItems();
if (count($active_items)) {
$filter = $query->createConditionGroup($operator, ['facet:' . $field_identifier]);
foreach ($active_items as $value) {
$filter->addCondition($field_identifier, $value, $exclude ? 'NOT BETWEEN' : 'BETWEEN');
}
$query->addConditionGroup($filter);
}
}
}
/**
* {@inheritdoc}
*/
public function build() {
$query_operator = $this->facet->getQueryOperator();
if (!empty($this->results)) {
$facet_results = [];
foreach ($this->results as $key => $result) {
if ($result['count'] || $query_operator == 'or') {
$count = $result['count'];
$result_filter = trim($result['filter'], '"');
$result = new Result($result_filter, $result_filter, $count);
$facet_results[] = $result;
}
}
$this->facet->setResults($facet_results);
}
return $this->facet;
}
}
| YashiMalhotra/drupalsolr | modules/contrib/facets/src/Plugin/facets/query_type/SearchApiRange.php | PHP | gpl-2.0 | 2,345 |
<!--footer start here-->
<div class="footer">
<div class="container">
<div class="footer-main">
<div class="col-md-4 footer-grid wow bounceIn" data-wow-delay="0.4s">
<h3>NUESTRA FILOSOFÍA </h3>
<P>Gestionar y posicionar, de manera creativa y
auténtica, la imagen como empleador de
una compañía como elemento de atracción,
motivación y retención de actuales
empleados y potenciales.</P>
<h5>Contacto:<br> <a href="mailto:indentidadesrh@gmail.com">indentidadesrh@gmail.com</a></h5>
<h6>(809)329-9393</h6>
<h5>Siguenos en:</h5>
<a href="http://instagram.com/identidadrh/"><img src="images/ins.png" class="img"></a>
<a HREF="https://www.facebook.com/identidadrh"><img src="images/fb.png" class="img"></A>
<a HREF="https://twitter.com/IdentidadRH"><img src="images/tw.png" class="img"></A>
<a href="https://www.linkedin.com/company/3501860?trk=tyah&trkInfo=idx%3A1-1-1%2CtarId%3A1423497567513%2Ctas%3Aidentidad+rh
"><img src="images/link.png" class="img"></a>
</div>
<div class="col-md-4 footer-grid wow bounceIn" data-wow-delay="0.4s">
<h3>¿Cómo lo logramos?</h3>
<img src="images/c4.jpg" alt=""/>
<p>Realizamos un diagnóstico de la imagen de la empresa tanto interno como externo. </p>
<p>Diseñamos un plan de marca interno y externo como empleador.</p>
<div class="ftr-bwn">
<a href="about.php">Leer Mas</a>
</div>
</div>
<div class="col-md-4 footer-grid wow bounceIn" data-wow-delay="0.4s">
<h3> Identidad RH SRL</h3>
<ul class="ftr-list">
<li><a href="about.php">Quienes Somos?</a></li>
<li><a href="contact.php">Contacto.</a></li>
<li><a href="service.php">Servicios</a></li>
<li><a href="#">Expo Empleo</a></li>
<li><a href="english.php">English 4 a Career</a></li>
</ul>
</div>
<div class="clearfix"> </div>
</div>
</div>
</div>
<!--footer end here--> | Acostangel/expoempleo | Pasantia/includes/footer.php | PHP | gpl-2.0 | 1,971 |
package dmesg
// #include <sys/syslog.h>
import "C"
// Facility models well-known log facilities (see man klogctl)
type Facility uint
const (
LOG_KERN = C.LOG_KERN // kernel messages
LOG_USER = C.LOG_USER // random user-level messages
LOG_MAIL = C.LOG_MAIL // mail system
LOG_DAEMON = C.LOG_DAEMON // system daemons
LOG_AUTH = C.LOG_AUTH // security/authorization messages
LOG_SYSLOG = C.LOG_SYSLOG // messages generated internally by syslogd
LOG_LPR = C.LOG_LPR // line printer subsystem
LOG_NEWS = C.LOG_NEWS // network news subsystem
LOG_UUCP = C.LOG_UUCP // UUCP subsystem
LOG_CRON = C.LOG_CRON // clock daemon
LOG_AUTHPRIV = C.LOG_AUTHPRIV // security/authorization messages (private)
LOG_FTP = C.LOG_FTP // ftp daemon
)
// MaskFacility extracts the facility (bottom 3 bits) from the integer value v.
func MaskFacility(v uint) Facility {
return Facility((v & 0x03fb) >> 3)
}
| vosst/csi | dmesg/facility.go | GO | gpl-2.0 | 981 |
<?php
/*
+---------------------------------------------------------------------------+
| Revive Adserver |
| http://www.revive-adserver.com |
| |
| Copyright: See the COPYRIGHT.txt file. |
| License: GPLv2 or later, see the LICENSE.txt file. |
+---------------------------------------------------------------------------+
*/
// Other
// Measures
// Common Invocation Parameters
// Iframe
// PopUp
// XML-RPC
// Support for 3rd party server clicktracking
// Support for cachebusting code
// IMG invocation selected for tracker with appended code
$GLOBALS['strWarning'] = "Cảnh báo";
// Local Invocation
| sgreiner/revive-adserver | lib/max/language/vi/invocation.lang.php | PHP | gpl-2.0 | 865 |
/**
* This class is generated by jOOQ
*/
package schema.process_engine.tables;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.5.4"
},
comments = "This class is generated by jOOQ"
)
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class ActHiTaskinst extends org.jooq.impl.TableImpl<schema.process_engine.tables.records.ActHiTaskinstRecord> {
private static final long serialVersionUID = -477092330;
/**
* The reference instance of <code>process-engine.ACT_HI_TASKINST</code>
*/
public static final schema.process_engine.tables.ActHiTaskinst ACT_HI_TASKINST = new schema.process_engine.tables.ActHiTaskinst();
/**
* The class holding records for this type
*/
@Override
public java.lang.Class<schema.process_engine.tables.records.ActHiTaskinstRecord> getRecordType() {
return schema.process_engine.tables.records.ActHiTaskinstRecord.class;
}
/**
* The column <code>process-engine.ACT_HI_TASKINST.ID_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> ID_ = createField("ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64).nullable(false), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.PROC_DEF_ID_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> PROC_DEF_ID_ = createField("PROC_DEF_ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.TASK_DEF_KEY_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> TASK_DEF_KEY_ = createField("TASK_DEF_KEY_", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.PROC_INST_ID_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> PROC_INST_ID_ = createField("PROC_INST_ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.EXECUTION_ID_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> EXECUTION_ID_ = createField("EXECUTION_ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.ACT_INST_ID_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> ACT_INST_ID_ = createField("ACT_INST_ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.NAME_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> NAME_ = createField("NAME_", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.PARENT_TASK_ID_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> PARENT_TASK_ID_ = createField("PARENT_TASK_ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.DESCRIPTION_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> DESCRIPTION_ = createField("DESCRIPTION_", org.jooq.impl.SQLDataType.VARCHAR.length(4000), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.OWNER_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> OWNER_ = createField("OWNER_", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.ASSIGNEE_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> ASSIGNEE_ = createField("ASSIGNEE_", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.START_TIME_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.sql.Timestamp> START_TIME_ = createField("START_TIME_", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.END_TIME_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.sql.Timestamp> END_TIME_ = createField("END_TIME_", org.jooq.impl.SQLDataType.TIMESTAMP, this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.DURATION_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.Long> DURATION_ = createField("DURATION_", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.DELETE_REASON_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> DELETE_REASON_ = createField("DELETE_REASON_", org.jooq.impl.SQLDataType.VARCHAR.length(4000), this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.PRIORITY_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.Integer> PRIORITY_ = createField("PRIORITY_", org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.DUE_DATE_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.sql.Timestamp> DUE_DATE_ = createField("DUE_DATE_", org.jooq.impl.SQLDataType.TIMESTAMP, this, "");
/**
* The column <code>process-engine.ACT_HI_TASKINST.FOLLOW_UP_DATE_</code>.
*/
public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.sql.Timestamp> FOLLOW_UP_DATE_ = createField("FOLLOW_UP_DATE_", org.jooq.impl.SQLDataType.TIMESTAMP, this, "");
/**
* Create a <code>process-engine.ACT_HI_TASKINST</code> table reference
*/
public ActHiTaskinst() {
this("ACT_HI_TASKINST", null);
}
/**
* Create an aliased <code>process-engine.ACT_HI_TASKINST</code> table reference
*/
public ActHiTaskinst(java.lang.String alias) {
this(alias, schema.process_engine.tables.ActHiTaskinst.ACT_HI_TASKINST);
}
private ActHiTaskinst(java.lang.String alias, org.jooq.Table<schema.process_engine.tables.records.ActHiTaskinstRecord> aliased) {
this(alias, aliased, null);
}
private ActHiTaskinst(java.lang.String alias, org.jooq.Table<schema.process_engine.tables.records.ActHiTaskinstRecord> aliased, org.jooq.Field<?>[] parameters) {
super(alias, schema.process_engine.Process_engine.PROCESS_ENGINE, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.UniqueKey<schema.process_engine.tables.records.ActHiTaskinstRecord> getPrimaryKey() {
return schema.process_engine.Keys.KEY_ACT_HI_TASKINST_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public java.util.List<org.jooq.UniqueKey<schema.process_engine.tables.records.ActHiTaskinstRecord>> getKeys() {
return java.util.Arrays.<org.jooq.UniqueKey<schema.process_engine.tables.records.ActHiTaskinstRecord>>asList(schema.process_engine.Keys.KEY_ACT_HI_TASKINST_PRIMARY);
}
/**
* {@inheritDoc}
*/
@Override
public schema.process_engine.tables.ActHiTaskinst as(java.lang.String alias) {
return new schema.process_engine.tables.ActHiTaskinst(alias, this);
}
/**
* Rename this table
*/
public schema.process_engine.tables.ActHiTaskinst rename(java.lang.String name) {
return new schema.process_engine.tables.ActHiTaskinst(name, null);
}
}
| marcoargenti/Cleaner | src/main/java/schema/process_engine/tables/ActHiTaskinst.java | Java | gpl-2.0 | 7,875 |
<?php
/*************************************************************************************
* tsql.php
* --------
* Author: Duncan Lock (dunc@dflock.co.uk)
* Copyright: (c) 2006 Duncan Lock (http://dflock.co.uk/), Nigel McNie (http://qbnz.com/highlighter)
* Release Version: 1.0.7.15
* CVS Revision Version: $Revision: 1.8.2.6 $
* Date Started: 2005/11/22
* Last Modified: $Date: 2006/09/23 02:05:48 $
*
* T-SQL language file for GeSHi.
*
* CHANGES
* -------
* 2004/01/23 (1.0.0)
* - First Release
*
* TODO (updated 2006/01/23)
* -------------------------
*
*************************************************************************************
*
* This file is part of GeSHi.
*
* GeSHi 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.
*
* GeSHi 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 GeSHi; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
************************************************************************************/
$language_data = array (
'LANG_NAME' => 'T-SQL',
'COMMENT_SINGLE' => array(1 => '--'),
'COMMENT_MULTI' => array('/*' => '*/'),
'CASE_KEYWORDS' => GESHI_CAPS_UPPER,
'QUOTEMARKS' => array("'", '"'),
'ESCAPE_CHAR' => '\\',
'KEYWORDS' => array(
1 => array(
/*
This will be highlighted in blue
*/
// Datatypes
'bigint', 'int', 'smallint', 'tinyint', 'bit', 'decimal', 'numeric', 'money',
'smallmoney', 'float', 'real', 'datetime', 'smalldatetime', 'char', 'varchar',
'text', 'nchar', 'nvarchar', 'ntext', 'binary', 'varbinary', 'image', 'cursor',
'sql_variant', 'table', 'timestamp', 'uniqueidentifier',
// Keywords
'ABSOLUTE', 'ACTION', 'ADD', 'ADMIN', 'AFTER', 'AGGREGATE', 'ALIAS', 'ALLOCATE', 'ALTER', 'ARE', 'ARRAY', 'AS',
'ASC', 'ASSERTION', 'AT', 'AUTHORIZATION', 'BACKUP', 'BEFORE', 'BEGIN', 'BINARY', 'BIT', 'BLOB', 'BOOLEAN', 'BOTH', 'BREADTH',
'BREAK', 'BROWSE', 'BULK', 'BY', 'CALL', 'CASCADE', 'CASCADED', 'CASE', 'CAST', 'CATALOG', 'CHAR', 'CHARACTER', 'CHECK', 'CHECKPOINT',
'CLASS', 'CLOB', 'CLOSE', 'CLUSTERED', 'COALESCE', 'COLLATE', 'COLLATION', 'COLUMN', 'COMMIT', 'COMPLETION', 'COMPUTE', 'CONNECT',
'CONNECTION', 'CONSTRAINT', 'CONSTRAINTS', 'CONSTRUCTOR', 'CONTAINS', 'CONTAINSTABLE', 'CONTINUE', 'CONVERT', 'CORRESPONDING', 'CREATE',
'CUBE', 'CURRENT', 'CURRENT_DATE', 'CURRENT_PATH', 'CURRENT_ROLE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER',
'CURSOR', 'CYCLE', 'DATA', 'DATABASE', 'DATE', 'DAY', 'DBCC', 'DEALLOCATE', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DEFERRABLE',
'DEFERRED', 'DELETE', 'DENY', 'DEPTH', 'DEREF', 'DESC', 'DESCRIBE', 'DESCRIPTOR', 'DESTROY', 'DESTRUCTOR', 'DETERMINISTIC',
'DIAGNOSTICS', 'DICTIONARY', 'DISCONNECT', 'DISK', 'DISTINCT', 'DISTRIBUTED', 'DOMAIN', 'DOUBLE', 'DROP', 'DUMMY', 'DUMP', 'DYNAMIC',
'EACH', 'ELSE', 'END', 'END-EXEC', 'EQUALS', 'ERRLVL', 'ESCAPE', 'EVERY', 'EXCEPT', 'EXCEPTION', 'EXEC', 'EXECUTE', 'EXIT',
'EXTERNAL', 'FALSE', 'FETCH', 'FILE', 'FILLFACTOR', 'FIRST', 'FLOAT', 'FOR', 'FOREIGN', 'FOUND', 'FREE', 'FREETEXT', 'FREETEXTTABLE',
'FROM', 'FULL', 'FUNCTION', 'GENERAL', 'GET', 'GLOBAL', 'GOTO', 'GRANT', 'GROUP', 'GROUPING', 'HAVING', 'HOLDLOCK', 'HOST', 'HOUR',
'IDENTITY', 'IDENTITY_INSERT', 'IDENTITYCOL', 'IF', 'IGNORE', 'IMMEDIATE', 'INDEX', 'INDICATOR', 'INITIALIZE', 'INITIALLY',
'INNER', 'INOUT', 'INPUT', 'INSERT', 'INT', 'INTEGER', 'INTERSECT', 'INTERVAL', 'INTO', 'IS', 'ISOLATION', 'ITERATE', 'KEY',
'KILL', 'LANGUAGE', 'LARGE', 'LAST', 'LATERAL', 'LEADING', 'LEFT', 'LESS', 'LEVEL', 'LIMIT', 'LINENO', 'LOAD', 'LOCAL',
'LOCALTIME', 'LOCALTIMESTAMP', 'LOCATOR', 'MAP', 'MATCH', 'MINUTE', 'MODIFIES', 'MODIFY', 'MODULE', 'MONTH', 'NAMES', 'NATIONAL',
'NATURAL', 'NCHAR', 'NCLOB', 'NEW', 'NEXT', 'NO', 'NOCHECK', 'NONCLUSTERED', 'NONE', 'NULLIF', 'NUMERIC', 'OBJECT', 'OF',
'OFF', 'OFFSETS', 'OLD', 'ON', 'ONLY', 'OPEN', 'OPENDATASOURCE', 'OPENQUERY', 'OPENROWSET', 'OPENXML', 'OPERATION', 'OPTION',
'ORDER', 'ORDINALITY', 'OUT', 'OUTPUT', 'OVER', 'PAD', 'PARAMETER', 'PARAMETERS', 'PARTIAL', 'PATH', 'PERCENT', 'PLAN',
'POSTFIX', 'PRECISION', 'PREFIX', 'PREORDER', 'PREPARE', 'PRESERVE', 'PRIMARY', 'PRINT', 'PRIOR', 'PRIVILEGES', 'PROC', 'PROCEDURE',
'PUBLIC', 'RAISERROR', 'READ', 'READS', 'READTEXT', 'REAL', 'RECONFIGURE', 'RECURSIVE', 'REF', 'REFERENCES', 'REFERENCING', 'RELATIVE',
'REPLICATION', 'RESTORE', 'RESTRICT', 'RESULT', 'RETURN', 'RETURNS', 'REVOKE', 'RIGHT', 'ROLE', 'ROLLBACK', 'ROLLUP', 'ROUTINE', 'ROW',
'ROWGUIDCOL', 'ROWS', 'RULE', 'SAVE', 'SAVEPOINT', 'SCHEMA', 'SCOPE', 'SCROLL', 'SEARCH', 'SECOND', 'SECTION', 'SELECT',
'SEQUENCE', 'SESSION', 'SESSION_USER', 'SET', 'SETS', 'SETUSER', 'SHUTDOWN', 'SIZE', 'SMALLINT', 'SPACE', 'SPECIFIC',
'SPECIFICTYPE', 'SQL', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'START', 'STATE', 'STATEMENT', 'STATIC', 'STATISTICS', 'STRUCTURE',
'SYSTEM_USER', 'TABLE', 'TEMPORARY', 'TERMINATE', 'TEXTSIZE', 'THAN', 'THEN', 'TIME', 'TIMESTAMP', 'TIMEZONE_HOUR', 'TIMEZONE_MINUTE',
'TO', 'TOP', 'TRAILING', 'TRAN', 'TRANSACTION', 'TRANSLATION', 'TREAT', 'TRIGGER', 'TRUE', 'TRUNCATE', 'TSEQUAL', 'UNDER', 'UNION',
'UNIQUE', 'UNKNOWN', 'UNNEST', 'UPDATE', 'UPDATETEXT', 'USAGE', 'USE', 'USER', 'USING', 'VALUE', 'VALUES', 'VARCHAR', 'VARIABLE',
'VARYING', 'VIEW', 'WAITFOR', 'WHEN', 'WHENEVER', 'WHERE', 'WHILE', 'WITH', 'WITHOUT', 'WORK', 'WRITE', 'WRITETEXT', 'YEAR', 'ZONE',
'UNCOMMITTED', 'NOCOUNT',
),
2 => array(
/*
Built-in functions
Highlighted in pink.
*/
//Configuration Functions
'@@DATEFIRST','@@OPTIONS','@@DBTS','@@REMSERVER','@@LANGID','@@SERVERNAME',
'@@LANGUAGE','@@SERVICENAME','@@LOCK_TIMEOUT','@@SPID','@@MAX_CONNECTIONS','@@TEXTSIZE',
'@@MAX_PRECISION','@@VERSION','@@NESTLEVEL',
//Cursor Functions
'@@CURSOR_ROWS','@@FETCH_STATUS',
//Date and Time Functions
'DATEADD','DATEDIFF','DATENAME','DATEPART','DAY','GETDATE','GETUTCDATE','MONTH','YEAR',
//Mathematical Functions
'ABS','DEGREES','RAND','ACOS','EXP','ROUND','ASIN','FLOOR','SIGN',
'ATAN','LOG','SIN','ATN2','LOG10','SQUARE','CEILING','PI','SQRT','COS',
'POWER','TAN','COT','RADIANS',
//Meta Data Functions
'COL_LENGTH','fn_listextendedproperty','COL_NAME','FULLTEXTCATALOGPROPERTY',
'COLUMNPROPERTY','FULLTEXTSERVICEPROPERTY','DATABASEPROPERTY','INDEX_COL',
'DATABASEPROPERTYEX','INDEXKEY_PROPERTY','DB_ID','INDEXPROPERTY','DB_NAME',
'OBJECT_ID','FILE_ID','OBJECT_NAME','FILE_NAME','OBJECTPROPERTY','FILEGROUP_ID',
'@@PROCID','FILEGROUP_NAME','SQL_VARIANT_PROPERTY','FILEGROUPPROPERTY',
'TYPEPROPERTY','FILEPROPERTY',
//Security Functions
'fn_trace_geteventinfo','IS_SRVROLEMEMBER','fn_trace_getfilterinfo','SUSER_SID',
'fn_trace_getinfo','SUSER_SNAME','fn_trace_gettable','USER_ID','HAS_DBACCESS',
'IS_MEMBER',
//String Functions
'ASCII','NCHAR','SOUNDEX','CHAR','PATINDEX','SPACE','CHARINDEX',
'REPLACE','STR','DIFFERENCE','QUOTENAME','STUFF','LEFT','REPLICATE',
'SUBSTRING','LEN','REVERSE','UNICODE','LOWER','RIGHT','UPPER','LTRIM',
'RTRIM',
//System Functions
'APP_NAME','COLLATIONPROPERTY','@@ERROR','fn_helpcollations',
'fn_servershareddrives','fn_virtualfilestats','FORMATMESSAGE',
'GETANSINULL','HOST_ID','HOST_NAME','IDENT_CURRENT','IDENT_INCR',
'IDENT_SEED','@@IDENTITY','ISDATE','ISNUMERIC','PARSENAME','PERMISSIONS',
'@@ROWCOUNT','ROWCOUNT_BIG','SCOPE_IDENTITY','SERVERPROPERTY','SESSIONPROPERTY',
'STATS_DATE','@@TRANCOUNT','USER_NAME',
//System Statistical Functions
'@@CONNECTIONS','@@PACK_RECEIVED','@@CPU_BUSY','@@PACK_SENT',
'fn_virtualfilestats','@@TIMETICKS','@@IDLE','@@TOTAL_ERRORS','@@IO_BUSY',
'@@TOTAL_READ','@@PACKET_ERRORS','@@TOTAL_WRITE',
//Text and Image Functions
'TEXTPTR','TEXTVALID',
//Aggregate functions
'AVG', 'MAX', 'BINARY_CHECKSUM', 'MIN', 'CHECKSUM', 'SUM', 'CHECKSUM_AGG',
'STDEV', 'COUNT', 'STDEVP', 'COUNT_BIG', 'VAR', 'GROUPING', 'VARP'
),
3 => array(
/*
System stored procedures
Higlighted dark brown
*/
//Active Directory Procedures
'sp_ActiveDirectory_Obj', 'sp_ActiveDirectory_SCP',
//Catalog Procedures
'sp_column_privileges', 'sp_special_columns', 'sp_columns', 'sp_sproc_columns',
'sp_databases', 'sp_statistics', 'sp_fkeys', 'sp_stored_procedures', 'sp_pkeys',
'sp_table_privileges', 'sp_server_info', 'sp_tables',
//Cursor Procedures
'sp_cursor_list', 'sp_describe_cursor_columns', 'sp_describe_cursor', 'sp_describe_cursor_tables',
//Database Maintenance Plan Procedures
'sp_add_maintenance_plan', 'sp_delete_maintenance_plan_db', 'sp_add_maintenance_plan_db',
'sp_delete_maintenance_plan_job', 'sp_add_maintenance_plan_job', 'sp_help_maintenance_plan',
'sp_delete_maintenance_plan',
//Distributed Queries Procedures
'sp_addlinkedserver', 'sp_indexes', 'sp_addlinkedsrvlogin', 'sp_linkedservers', 'sp_catalogs',
'sp_primarykeys', 'sp_column_privileges_ex', 'sp_serveroption', 'sp_columns_ex',
'sp_table_privileges_ex', 'sp_droplinkedsrvlogin', 'sp_tables_ex', 'sp_foreignkeys',
//Full-Text Search Procedures
'sp_fulltext_catalog', 'sp_help_fulltext_catalogs_cursor', 'sp_fulltext_column',
'sp_help_fulltext_columns', 'sp_fulltext_database', 'sp_help_fulltext_columns_cursor',
'sp_fulltext_service', 'sp_help_fulltext_tables', 'sp_fulltext_table',
'sp_help_fulltext_tables_cursor', 'sp_help_fulltext_catalogs',
//Log Shipping Procedures
'sp_add_log_shipping_database', 'sp_delete_log_shipping_database', 'sp_add_log_shipping_plan',
'sp_delete_log_shipping_plan', 'sp_add_log_shipping_plan_database',
'sp_delete_log_shipping_plan_database', 'sp_add_log_shipping_primary',
'sp_delete_log_shipping_primary', 'sp_add_log_shipping_secondary',
'sp_delete_log_shipping_secondary', 'sp_can_tlog_be_applied', 'sp_get_log_shipping_monitor_info',
'sp_change_monitor_role', 'sp_remove_log_shipping_monitor', 'sp_change_primary_role',
'sp_resolve_logins', 'sp_change_secondary_role', 'sp_update_log_shipping_monitor_info',
'sp_create_log_shipping_monitor_account', 'sp_update_log_shipping_plan',
'sp_define_log_shipping_monitor', 'sp_update_log_shipping_plan_database',
//OLE Automation Extended Stored Procedures
'sp_OACreate', 'sp_OAMethod', 'sp_OADestroy', 'sp_OASetProperty', 'sp_OAGetErrorInfo',
'sp_OAStop', 'sp_OAGetProperty',
//Replication Procedures
'sp_add_agent_parameter', 'sp_enableagentoffload', 'sp_add_agent_profile',
'sp_enumcustomresolvers', 'sp_addarticle', 'sp_enumdsn', 'sp_adddistpublisher',
'sp_enumfullsubscribers', 'sp_adddistributiondb', 'sp_expired_subscription_cleanup',
'sp_adddistributor', 'sp_generatefilters', 'sp_addmergealternatepublisher',
'sp_getagentoffloadinfo', 'sp_addmergearticle', 'sp_getmergedeletetype', 'sp_addmergefilter',
'sp_get_distributor', 'sp_addmergepublication', 'sp_getqueuedrows', 'sp_addmergepullsubscription',
'sp_getsubscriptiondtspackagename', 'sp_addmergepullsubscription_agent', 'sp_grant_publication_access',
'sp_addmergesubscription', 'sp_help_agent_default', 'sp_addpublication', 'sp_help_agent_parameter',
'sp_addpublication_snapshot', 'sp_help_agent_profile', 'sp_addpublisher70', 'sp_helparticle',
'sp_addpullsubscription', 'sp_helparticlecolumns', 'sp_addpullsubscription_agent', 'sp_helparticledts',
'sp_addscriptexec', 'sp_helpdistpublisher', 'sp_addsubscriber', 'sp_helpdistributiondb',
'sp_addsubscriber_schedule', 'sp_helpdistributor', 'sp_addsubscription', 'sp_helpmergealternatepublisher',
'sp_addsynctriggers', 'sp_helpmergearticle', 'sp_addtabletocontents', 'sp_helpmergearticlecolumn',
'sp_adjustpublisheridentityrange', 'sp_helpmergearticleconflicts', 'sp_article_validation',
'sp_helpmergeconflictrows', 'sp_articlecolumn', 'sp_helpmergedeleteconflictrows', 'sp_articlefilter',
'sp_helpmergefilter', 'sp_articlesynctranprocs', 'sp_helpmergepublication', 'sp_articleview',
'sp_helpmergepullsubscription', 'sp_attachsubscription', 'sp_helpmergesubscription', 'sp_browsesnapshotfolder',
'sp_helppublication', 'sp_browsemergesnapshotfolder', 'sp_help_publication_access', 'sp_browsereplcmds',
'sp_helppullsubscription', 'sp_change_agent_parameter', 'sp_helpreplfailovermode', 'sp_change_agent_profile',
'sp_helpreplicationdboption', 'sp_changearticle', 'sp_helpreplicationoption', 'sp_changedistpublisher',
'sp_helpsubscriberinfo', 'sp_changedistributiondb', 'sp_helpsubscription', 'sp_changedistributor_password',
'sp_ivindexhasnullcols', 'sp_changedistributor_property', 'sp_helpsubscription_properties', 'sp_changemergearticle',
'sp_link_publication', 'sp_changemergefilter', 'sp_marksubscriptionvalidation', 'sp_changemergepublication',
'sp_mergearticlecolumn', 'sp_changemergepullsubscription', 'sp_mergecleanupmetadata', 'sp_changemergesubscription',
'sp_mergedummyupdate', 'sp_changepublication', 'sp_mergesubscription_cleanup', 'sp_changesubscriber',
'sp_publication_validation', 'sp_changesubscriber_schedule', 'sp_refreshsubscriptions', 'sp_changesubscriptiondtsinfo',
'sp_reinitmergepullsubscription', 'sp_changesubstatus', 'sp_reinitmergesubscription', 'sp_change_subscription_properties',
'sp_reinitpullsubscription', 'sp_check_for_sync_trigger', 'sp_reinitsubscription', 'sp_copymergesnapshot',
'sp_removedbreplication', 'sp_copysnapshot', 'sp_repladdcolumn', 'sp_copysubscription', 'sp_replcmds',
'sp_deletemergeconflictrow', 'sp_replcounters', 'sp_disableagentoffload', 'sp_repldone', 'sp_drop_agent_parameter',
'sp_repldropcolumn', 'sp_drop_agent_profile', 'sp_replflush', 'sp_droparticle', 'sp_replicationdboption',
'sp_dropanonymouseagent', 'sp_replication_agent_checkup', 'sp_dropdistpublisher', 'sp_replqueuemonitor',
'sp_dropdistributiondb', 'sp_replsetoriginator', 'sp_dropmergealternatepublisher', 'sp_replshowcmds',
'sp_dropdistributor', 'sp_repltrans', 'sp_dropmergearticle', 'sp_restoredbreplication', 'sp_dropmergefilter',
'sp_revoke_publication_access', 'sp_scriptsubconflicttable', 'sp_dropmergepublication', 'sp_script_synctran_commands',
'sp_dropmergepullsubscription', 'sp_setreplfailovermode', 'sp_showrowreplicainfo', 'sp_dropmergesubscription',
'sp_subscription_cleanup', 'sp_droppublication', 'sp_table_validation', 'sp_droppullsubscription',
'sp_update_agent_profile', 'sp_dropsubscriber', 'sp_validatemergepublication', 'sp_dropsubscription',
'sp_validatemergesubscription', 'sp_dsninfo', 'sp_vupgrade_replication', 'sp_dumpparamcmd',
//Security Procedures
'sp_addalias', 'sp_droprolemember', 'sp_addapprole', 'sp_dropserver', 'sp_addgroup', 'sp_dropsrvrolemember',
'sp_addlinkedsrvlogin', 'sp_dropuser', 'sp_addlogin', 'sp_grantdbaccess', 'sp_addremotelogin',
'sp_grantlogin', 'sp_addrole', 'sp_helpdbfixedrole', 'sp_addrolemember', 'sp_helpgroup',
'sp_addserver', 'sp_helplinkedsrvlogin', 'sp_addsrvrolemember', 'sp_helplogins', 'sp_adduser',
'sp_helpntgroup', 'sp_approlepassword', 'sp_helpremotelogin', 'sp_changedbowner', 'sp_helprole',
'sp_changegroup', 'sp_helprolemember', 'sp_changeobjectowner', 'sp_helprotect', 'sp_change_users_login',
'sp_helpsrvrole', 'sp_dbfixedrolepermission', 'sp_helpsrvrolemember', 'sp_defaultdb', 'sp_helpuser',
'sp_defaultlanguage', 'sp_MShasdbaccess', 'sp_denylogin', 'sp_password', 'sp_dropalias', 'sp_remoteoption',
'sp_dropapprole', 'sp_revokedbaccess', 'sp_dropgroup', 'sp_revokelogin', 'sp_droplinkedsrvlogin',
'sp_setapprole', 'sp_droplogin', 'sp_srvrolepermission', 'sp_dropremotelogin', 'sp_validatelogins', 'sp_droprole',
//SQL Mail Procedures
'sp_processmail', 'xp_sendmail', 'xp_deletemail', 'xp_startmail', 'xp_findnextmsg', 'xp_stopmail', 'xp_readmail',
//SQL Profiler Procedures
'sp_trace_create', 'sp_trace_setfilter', 'sp_trace_generateevent', 'sp_trace_setstatus', 'sp_trace_setevent',
//SQL Server Agent Procedures
'sp_add_alert', 'sp_help_jobhistory', 'sp_add_category', 'sp_help_jobschedule', 'sp_add_job',
'sp_help_jobserver', 'sp_add_jobschedule', 'sp_help_jobstep', 'sp_add_jobserver', 'sp_help_notification',
'sp_add_jobstep', 'sp_help_operator', 'sp_add_notification', 'sp_help_targetserver',
'sp_add_operator', 'sp_help_targetservergroup', 'sp_add_targetservergroup', 'sp_helptask',
'sp_add_targetsvrgrp_member', 'sp_manage_jobs_by_login', 'sp_addtask', 'sp_msx_defect',
'sp_apply_job_to_targets', 'sp_msx_enlist', 'sp_delete_alert', 'sp_post_msx_operation',
'sp_delete_category', 'sp_purgehistory', 'sp_delete_job', 'sp_purge_jobhistory', 'sp_delete_jobschedule',
'sp_reassigntask', 'sp_delete_jobserver', 'sp_remove_job_from_targets', 'sp_delete_jobstep',
'sp_resync_targetserver', 'sp_delete_notification', 'sp_start_job', 'sp_delete_operator',
'sp_stop_job', 'sp_delete_targetserver', 'sp_update_alert', 'sp_delete_targetservergroup',
'sp_update_category', 'sp_delete_targetsvrgrp_member', 'sp_update_job', 'sp_droptask',
'sp_update_jobschedule', 'sp_help_alert', 'sp_update_jobstep', 'sp_help_category',
'sp_update_notification', 'sp_help_downloadlist', 'sp_update_operator', 'sp_helphistory',
'sp_update_targetservergroup', 'sp_help_job', 'sp_updatetask', 'xp_sqlagent_proxy_account',
//System Procedures
'sp_add_data_file_recover_suspect_db', 'sp_helpconstraint', 'sp_addextendedproc',
'sp_helpdb', 'sp_addextendedproperty', 'sp_helpdevice', 'sp_add_log_file_recover_suspect_db',
'sp_helpextendedproc', 'sp_addmessage', 'sp_helpfile', 'sp_addtype', 'sp_helpfilegroup',
'sp_addumpdevice', 'sp_helpindex', 'sp_altermessage', 'sp_helplanguage', 'sp_autostats',
'sp_helpserver', 'sp_attach_db', 'sp_helpsort', 'sp_attach_single_file_db', 'sp_helpstats',
'sp_bindefault', 'sp_helptext', 'sp_bindrule', 'sp_helptrigger', 'sp_bindsession',
'sp_indexoption', 'sp_certify_removable', 'sp_invalidate_textptr', 'sp_configure',
'sp_lock', 'sp_create_removable', 'sp_monitor', 'sp_createstats', 'sp_procoption',
'sp_cycle_errorlog', 'sp_recompile', 'sp_datatype_info', 'sp_refreshview', 'sp_dbcmptlevel',
'sp_releaseapplock', 'sp_dboption', 'sp_rename', 'sp_dbremove', 'sp_renamedb',
'sp_delete_backuphistory', 'sp_resetstatus', 'sp_depends', 'sp_serveroption', 'sp_detach_db',
'sp_setnetname', 'sp_dropdevice', 'sp_settriggerorder', 'sp_dropextendedproc', 'sp_spaceused',
'sp_dropextendedproperty', 'sp_tableoption', 'sp_dropmessage', 'sp_unbindefault', 'sp_droptype',
'sp_unbindrule', 'sp_executesql', 'sp_updateextendedproperty', 'sp_getapplock', 'sp_updatestats',
'sp_getbindtoken', 'sp_validname', 'sp_help', 'sp_who',
//Web Assistant Procedures
'sp_dropwebtask', 'sp_makewebtask', 'sp_enumcodepages', 'sp_runwebtask',
//XML Procedures
'sp_xml_preparedocument', 'sp_xml_removedocument',
//General Extended Procedures
'xp_cmdshellxp_logininfo', 'xp_enumgroups', 'xp_msver', 'xp_findnextmsgxp_revokelogin',
'xp_grantlogin', 'xp_sprintf', 'xp_logevent', 'xp_sqlmaint', 'xp_loginconfig', 'xp_sscanf',
//API System Stored Procedures
'sp_cursor', 'sp_cursorclose', 'sp_cursorexecute', 'sp_cursorfetch', 'sp_cursoropen',
'sp_cursoroption', 'sp_cursorprepare', 'sp_cursorunprepare', 'sp_execute', 'sp_prepare', 'sp_unprepare',
//Misc
'sp_createorphan', 'sp_droporphans', 'sp_reset_connection', 'sp_sdidebug'
),
4 => array(
//Function/sp's higlighted brown.
'fn_helpcollations', 'fn_listextendedproperty ', 'fn_servershareddrives',
'fn_trace_geteventinfo', 'fn_trace_getfilterinfo', 'fn_trace_getinfo',
'fn_trace_gettable', 'fn_virtualfilestats',
),
),
'SYMBOLS' => array(
'!', '!=', '%', '&', '&&', '(', ')', '*', '+', '-', '/', '<', '<<', '<=',
'<=>', '<>', '=', '>', '>=', '>>', '^', 'ALL', 'AND', 'ANY', 'BETWEEN', 'CROSS',
'EXISTS', 'IN', 'JOIN', 'LIKE', 'NOT', 'NULL', 'OR', 'OUTER', 'SOME', '|', '||', '~'
),
'CASE_SENSITIVE' => array(
GESHI_COMMENTS => true,
1 => false,
2 => false,
3 => false,
4 => false,
),
'STYLES' => array(
'KEYWORDS' => array(
1 => 'color: #0000FF;',
2 => 'color: #FF00FF;',
3 => 'color: #AF0000;',
4 => 'color: #AF0000;'
),
'COMMENTS' => array(
1 => 'color: #008080;',
'MULTI' => 'color: #008080;'
),
'ESCAPE_CHAR' => array(
0 => 'color: #000099; font-weight: bold;'
),
'BRACKETS' => array(
0 => 'color: #808080;'
),
'STRINGS' => array(
0 => 'color: #FF0000;'
),
'NUMBERS' => array(
0 => 'color: #000;'
),
'METHODS' => array(
1 => 'color: #202020;',
2 => 'color: #202020;'
),
'SYMBOLS' => array(
0 => 'color: #808080;'
),
'REGEXPS' => array(
),
'SCRIPT' => array(
)
),
'URLS' => array(
1 => '',
2 => '',
3 => '',
4 => ''
),
'OOLANG' => true,
'OBJECT_SPLITTERS' => array(
1 => '.'
),
'REGEXPS' => array(
),
'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array(
),
'HIGHLIGHT_STRICT_BLOCK' => array(
)
);
?>
| SOSWEB-CH/atelier-rl | inc/geshi/tsql.php | PHP | gpl-2.0 | 21,616 |
import os
import sys
import unittest
from unittest.mock import patch, MagicMock
sys.path.append(os.path.join(os.path.dirname(__file__), '../../src/'))
from katello.agent.pulp import libdnf
@unittest.skipIf('dnf' not in sys.modules, "Dnf not present")
class TestLibDnf(unittest.TestCase):
def test_package_update_on_advisories(self):
advisories = set(["RHSA-1000"])
packages = set([("foo","1.0"), ("bar","2.0")])
def applicable_advisories(items):
self.assertEqual(advisories, items.ids)
return [(MagicMock(), packages)]
mock_libdnf = MagicMock()
mock_libdnf.__enter__ = lambda instance: instance
mock_libdnf.applicable_advisories = applicable_advisories
with patch('katello.agent.pulp.libdnf.LibDnf', return_value= mock_libdnf):
package = libdnf.Package()
package.update([],advisories)
#strip the evrs out of the package
packages = set([pack[0] for pack in packages])
mock_libdnf.upgrade.assert_called_with(packages)
def test_package_update_all(self):
advisories = set()
packages = set()
mock_libdnf = MagicMock()
mock_libdnf.__enter__ = lambda instance: instance
with patch('katello.agent.pulp.libdnf.LibDnf', return_value= mock_libdnf):
package = libdnf.Package()
package.update(packages, advisories)
#strip the evrs out of the package
mock_libdnf.upgrade.assert_called_with(packages)
| Katello/katello-agent | test/test_katello/test_agent/test_pulp/test_libdnf.py | Python | gpl-2.0 | 1,456 |
package com.ag.common.http.builder;
import com.ag.common.http.request.PostFileRequest;
import com.ag.common.http.request.RequestCall;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import okhttp3.MediaType;
public class PostFileBuilder extends OkHttpRequestBuilder
{
private File file;
private MediaType mediaType;
public OkHttpRequestBuilder file(File file)
{
this.file = file;
return this;
}
public OkHttpRequestBuilder mediaType(MediaType mediaType)
{
this.mediaType = mediaType;
return this;
}
@Override
public RequestCall build()
{
return new PostFileRequest(url, tag, params, headers, file, mediaType).build();
}
@Override
public PostFileBuilder url(String url)
{
this.url = url;
return this;
}
@Override
public PostFileBuilder tag(Object tag)
{
this.tag = tag;
return this;
}
@Override
public PostFileBuilder headers(Map<String, String> headers)
{
this.headers = headers;
return this;
}
@Override
public PostFileBuilder addHeader(String key, String val)
{
if (this.headers == null)
{
headers = new LinkedHashMap<>();
}
headers.put(key, val);
return this;
}
}
| ZhanJohn/AG_Modules | ag_common/src/main/java/com/ag/common/http/builder/PostFileBuilder.java | Java | gpl-2.0 | 1,360 |
# config/unicorn.rb
worker_processes Integer(ENV["WEB_CONCURRENCY"] || 3)
timeout 35
preload_app true
before_fork do |server, worker|
Signal.trap 'TERM' do
puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
Process.kill 'QUIT', Process.pid
end
defined?(ActiveRecord::Base) and
ActiveRecord::Base.connection.disconnect!
end
after_fork do |server, worker|
Signal.trap 'TERM' do
puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT'
end
defined?(ActiveRecord::Base) and
ActiveRecord::Base.establish_connection
end
| bl4ckdu5t/vitabiotics | config/unicorn.rb | Ruby | gpl-2.0 | 602 |
<?php
$this->currencies = array (
'adp' => 'Andorran Peseta',
'aed' => 'United Arab Emirates Dirham',
'afa' => 'Afghani (1927-2002)',
'afn' => 'Afghani',
'all' => 'Albanian Lek',
'amd' => 'Armenian Dram',
'ang' => 'Netherlands Antillan Guilder',
'aoa' => 'Angolan Kwanza',
'aok' => 'Angolan Kwanza (1977-1990)',
'aon' => 'Angolan New Kwanza (1990-2000)',
'aor' => 'Angolan Kwanza Reajustado (1995-1999)',
'ara' => 'Argentine Austral',
'arp' => 'Argentine Peso (1983-1985)',
'ars' => 'Argentine Peso',
'ats' => 'Austrian Schilling',
'aud' => 'Australian Dollar',
'awg' => 'Aruban Guilder',
'azm' => 'Azerbaijanian Manat',
'bad' => 'Bosnia-Herzegovina Dinar',
'bam' => 'Bosnia-Herzegovina Convertible Mark',
'bbd' => 'Barbados Dollar',
'bdt' => 'Bangladesh Taka',
'bec' => 'Belgian Franc (convertible)',
'bef' => 'Belgian Franc',
'bel' => 'Belgian Franc (financial)',
'bgl' => 'Bulgarian Hard Lev',
'bgn' => 'Bulgarian New Lev',
'bhd' => 'Bahraini Dinar',
'bif' => 'Burundi Franc',
'bmd' => 'Bermudan Dollar',
'bnd' => 'Brunei Dollar',
'bob' => 'Boliviano',
'bop' => 'Bolivian Peso',
'bov' => 'Bolivian Mvdol',
'brb' => 'Brazilian Cruzeiro Novo (1967-1986)',
'brc' => 'Brazilian Cruzado',
'bre' => 'Brazilian Cruzeiro (1990-1993)',
'brl' => 'Brazilian Real',
'brn' => 'Brazilian Cruzado Novo',
'brr' => 'Brazilian Cruzeiro',
'bsd' => 'Bahamian Dollar',
'btn' => 'Bhutan Ngultrum',
'buk' => 'Burmese Kyat',
'bwp' => 'Botswanan Pula',
'byb' => 'Belarussian New Ruble (1994-1999)',
'byr' => 'Belarussian Ruble',
'bzd' => 'Belize Dollar',
'cad' => 'Canadian Dollar',
'cdf' => 'Congolese Franc Congolais',
'che' => 'WIR Euro',
'chf' => 'Swiss Franc',
'chw' => 'WIR Franc',
'clf' => 'Chilean Unidades de Fomento',
'clp' => 'Chilean Peso',
'cny' => 'Chinese Yuan Renminbi',
'cop' => 'Colombian Peso',
'cou' => 'Unidad de Valor Real',
'crc' => 'Costa Rican Colon',
'csd' => 'Serbian Dinar',
'csk' => 'Czechoslovak Hard Koruna',
'cup' => 'Cuban Peso',
'cve' => 'Cape Verde Escudo',
'cyp' => 'Cyprus Pound',
'czk' => 'Czech Republic Koruna',
'ddm' => 'East German Ostmark',
'dem' => 'Deutsche Mark',
'djf' => 'Djibouti Franc',
'dkk' => 'Danish Krone',
'dop' => 'Dominican Peso',
'dzd' => 'Algerian Dinar',
'ecs' => 'Ecuador Sucre',
'ecv' => 'Ecuador Unidad de Valor Constante (UVC)',
'eek' => 'Estonian Kroon',
'egp' => 'Egyptian Pound',
'eqe' => 'Ekwele',
'ern' => 'Eritrean Nakfa',
'esa' => 'Spanish Peseta (A account)',
'esb' => 'Spanish Peseta (convertible account)',
'esp' => 'Spanish Peseta',
'etb' => 'Ethiopian Birr',
'eur' => 'Euro',
'fim' => 'Finnish Markka',
'fjd' => 'Fiji Dollar',
'fkp' => 'Falkland Islands Pound',
'frf' => 'French Franc',
'gbp' => 'British Pound Sterling',
'gek' => 'Georgian Kupon Larit',
'gel' => 'Georgian Lari',
'ghc' => 'Ghana Cedi',
'gip' => 'Gibraltar Pound',
'gmd' => 'Gambia Dalasi',
'gnf' => 'Guinea Franc',
'gns' => 'Guinea Syli',
'gqe' => 'Equatorial Guinea Ekwele Guineana',
'grd' => 'Greek Drachma',
'gtq' => 'Guatemala Quetzal',
'gwe' => 'Portuguese Guinea Escudo',
'gwp' => 'Guinea-Bissau Peso',
'gyd' => 'Guyana Dollar',
'hkd' => 'Hong Kong Dollar',
'hnl' => 'Hoduras Lempira',
'hrd' => 'Croatian Dinar',
'hrk' => 'Croatian Kuna',
'htg' => 'Haitian Gourde',
'huf' => 'Hungarian Forint',
'idr' => 'Indonesian Rupiah',
'iep' => 'Irish Pound',
'ilp' => 'Israeli Pound',
'ils' => 'Israeli New Sheqel',
'inr' => 'Indian Rupee',
'iqd' => 'Iraqi Dinar',
'irr' => 'Iranian Rial',
'isk' => 'Icelandic Krona',
'itl' => 'Italian Lira',
'jmd' => 'Jamaican Dollar',
'jod' => 'Jordanian Dinar',
'jpy' => 'Japanese Yen',
'kes' => 'Kenyan Shilling',
'kgs' => 'Kyrgystan Som',
'khr' => 'Cambodian Riel',
'kmf' => 'Comoro Franc',
'kpw' => 'North Korean Won',
'krw' => 'South Korean Won',
'kwd' => 'Kuwaiti Dinar',
'kyd' => 'Cayman Islands Dollar',
'kzt' => 'Kazakhstan Tenge',
'lak' => 'Laotian Kip',
'lbp' => 'Lebanese Pound',
'lkr' => 'Sri Lanka Rupee',
'lrd' => 'Liberian Dollar',
'lsl' => 'Lesotho Loti',
'lsm' => 'Maloti',
'ltl' => 'Lithuanian Lita',
'ltt' => 'Lithuanian Talonas',
'luc' => 'Luxembourg Convertible Franc',
'luf' => 'Luxembourg Franc',
'lul' => 'Luxembourg Financial Franc',
'lvl' => 'Latvian Lats',
'lvr' => 'Latvian Ruble',
'lyd' => 'Libyan Dinar',
'mad' => 'Moroccan Dirham',
'maf' => 'Moroccan Franc',
'mdl' => 'Moldovan Leu',
'mga' => 'Madagascar Ariary',
'mgf' => 'Madagascar Franc',
'mkd' => 'Macedonian Denar',
'mlf' => 'Mali Franc',
'mmk' => 'Myanmar Kyat',
'mnt' => 'Mongolian Tugrik',
'mop' => 'Macao Pataca',
'mro' => 'Mauritania Ouguiya',
'mtl' => 'Maltese Lira',
'mtp' => 'Maltese Pound',
'mur' => 'Mauritius Rupee',
'mvr' => 'Maldive Islands Rufiyaa',
'mwk' => 'Malawi Kwacha',
'mxn' => 'Mexican Peso',
'mxp' => 'Mexican Silver Peso (1861-1992)',
'mxv' => 'Mexican Unidad de Inversion (UDI)',
'myr' => 'Malaysian Ringgit',
'mze' => 'Mozambique Escudo',
'mzm' => 'Mozambique Metical',
'nad' => 'Namibia Dollar',
'ngn' => 'Nigerian Naira',
'nic' => 'Nicaraguan Cordoba',
'nio' => 'Nicaraguan Cordoba Oro',
'nlg' => 'Netherlands Guilder',
'nok' => 'Norwegian Krone',
'npr' => 'Nepalese Rupee',
'nzd' => 'New Zealand Dollar',
'omr' => 'Oman Rial',
'pab' => 'Panamanian Balboa',
'pei' => 'Peruvian Inti',
'pen' => 'Peruvian Sol Nuevo',
'pes' => 'Peruvian Sol',
'pgk' => 'Papua New Guinea Kina',
'php' => 'Philippine Peso',
'pkr' => 'Pakistan Rupee',
'pln' => 'Polish Zloty',
'plz' => 'Polish Zloty (1950-1995)',
'pte' => 'Portuguese Escudo',
'pyg' => 'Paraguay Guarani',
'qar' => 'Qatari Rial',
'rhd' => 'Rhodesian Dollar',
'rol' => 'Romanian Leu',
'ron' => 'Romanian Leu',
'rub' => 'Russian Ruble',
'rur' => 'Russian Ruble (1991-1998)',
'rwf' => 'Rwandan Franc',
'sar' => 'Saudi Riyal',
'sbd' => 'Solomon Islands Dollar',
'scr' => 'Seychelles Rupee',
'sdd' => 'Sudanese Dinar',
'sdp' => 'Sudanese Pound',
'sek' => 'Swedish Krona',
'sgd' => 'Singapore Dollar',
'shp' => 'Saint Helena Pound',
'sit' => 'Slovenia Tolar',
'skk' => 'Slovak Koruna',
'sll' => 'Sierra Leone Leone',
'sos' => 'Somali Shilling',
'srd' => 'Surinam Dollar',
'srg' => 'Suriname Guilder',
'std' => 'Sao Tome and Principe Dobra',
'sur' => 'Soviet Rouble',
'svc' => 'El Salvador Colon',
'syp' => 'Syrian Pound',
'szl' => 'Swaziland Lilangeni',
'thb' => 'Thai Baht',
'tjr' => 'Tajikistan Ruble',
'tjs' => 'Tajikistan Somoni',
'tmm' => 'Turkmenistan Manat',
'tnd' => 'Tunisian Dinar',
'top' => 'Tonga Paʻanga',
'tpe' => 'Timor Escudo',
'trl' => 'Turkish Lira',
'try' => 'New Turkish Lira',
'ttd' => 'Trinidad and Tobago Dollar',
'twd' => 'Taiwan New Dollar',
'tzs' => 'Tanzanian Shilling',
'uah' => 'Ukrainian Hryvnia',
'uak' => 'Ukrainian Karbovanetz',
'ugs' => 'Ugandan Shilling (1966-1987)',
'ugx' => 'Ugandan Shilling',
'usd' => 'US Dollar',
'usn' => 'US Dollar (Next day)',
'uss' => 'US Dollar (Same day)',
'uyp' => 'Uruguay Peso (1975-1993)',
'uyu' => 'Uruguay Peso Uruguayo',
'uzs' => 'Uzbekistan Sum',
'veb' => 'Venezuelan Bolivar',
'vnd' => 'đồng',
'vuv' => 'Vanuatu Vatu',
'wst' => 'Western Samoa Tala',
'xaf' => 'CFA Franc BEAC',
'xag' => 'Silver',
'xau' => 'Gold',
'xba' => 'European Composite Unit',
'xbb' => 'European Monetary Unit',
'xbc' => 'European Unit of Account (XBC)',
'xbd' => 'European Unit of Account (XBD)',
'xcd' => 'East Caribbean Dollar',
'xdr' => 'Special Drawing Rights',
'xeu' => 'European Currency Unit',
'xfo' => 'French Gold Franc',
'xfu' => 'French UIC-Franc',
'xof' => 'CFA Franc BCEAO',
'xpd' => 'Palladium',
'xpf' => 'CFP Franc',
'xpt' => 'Platinum',
'xre' => 'RINET Funds',
'xts' => 'Testing Currency Code',
'xxx' => 'No Currency',
'ydd' => 'Yemeni Dinar',
'yer' => 'Yemeni Rial',
'yud' => 'Yugoslavian Hard Dinar',
'yum' => 'Yugoslavian Noviy Dinar',
'yun' => 'Yugoslavian Convertible Dinar',
'zal' => 'South African Rand (financial)',
'zar' => 'South African Rand',
'zmk' => 'Zambian Kwacha',
'zrn' => 'Zairean New Zaire',
'zrz' => 'Zairean Zaire',
'zwd' => 'Zimbabwe Dollar',
); | prdatur/soopfw | language/currencies/vi.php | PHP | gpl-2.0 | 8,370 |
<?php
/**
* @package AcyMailing for Joomla!
* @version 4.5.0
* @author acyba.com
* @copyright (C) 2009-2013 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><?php
jimport( 'joomla.html.parameter' );
class acymailingView extends JView{
}
class acymailingControllerCompat extends JController{
}
function acymailing_loadResultArray(&$db){
return $db->loadResultArray();
}
function acymailing_loadMootools($loadMootoolsMoreLib = false){
JHTML::_('behavior.mootools');
}
function acymailing_getColumns($table){
$db = JFactory::getDBO();
$allfields = $db->getTableFields($table);
return reset($allfields);
}
function acymailing_getEscaped($value, $extra = false) {
$db = JFactory::getDBO();
return $db->getEscaped($value, $extra);
}
function acymailing_getFormToken() {
return JUtility::getToken();
}
if(!class_exists('acyParameter')){
class acyParameter extends JParameter{}
}
| QuyICDAC/icdacgov | administrator/components/com_acymailing/compat/compat1.php | PHP | gpl-2.0 | 1,044 |
/*
* WordPress.com MetaDNS
*/
#ifndef __H_WPMETABACKEND_HH__
#define __H_WPMETABACKEND_HH__
#include <cstring>
#include <vector>
#include <random>
#include <map>
#include <chrono>
#include <pdns/namespaces.hh>
#include <pdns/dnsbackend.hh>
#include <pdns/dnspacket.hh>
#include "defines.h"
#include "database.hh"
#include "hashring.hh"
#include "hashcache.hh"
#include "poolcache.hh"
#include "cache.hh"
typedef std::mt19937 oRandom;
std::uniform_int_distribution<uint32_t> uint_dist;
struct Vec_Sorter {
bool operator()( const std::vector<string>& lhs, const std::vector<string>& rhs )
{
return ( lhs[VEC_random_value] < rhs[VEC_random_value] );
}
};
class WPMetaBackend : public DNSBackend {
public:
WPMetaBackend( const string &suffix = "" );
~WPMetaBackend();
WPMetaBackend *parent;
void lookup( const QType &qtype, const string &domain_name, DNSPacket *packet = NULL, int domain_id = -1 );
bool list( const string &target, int domain_id );
bool get( DNSResourceRecord &r );
bool getSOA( const string &domain_name, SOAData &soadata, DNSPacket* packet );
private:
Database *m_db;
Hash_Cache m_HC;
Pool_Cache m_PC;
Cache<std::string, SOA> m_SC;
Cache<std::string, Records> m_RC;
Cache<std::string, Lookup> m_LC;
vector<vector<std::string> > m_results;
oRandom m_random;
string m_qname;
string m_origin;
uint32_t m_cache_purge_counter;
int query_db( const string& p_sql );
int query_db( const string& p_sql, Database::result_t& result );
bool prepare_records( const string& query_domain, const Database::result_t& p_results );
void send_from_hash_cache( const uint64_t& pool_house_id, const std::string& query_domain, const Database::row_t& rrow );
void send_from_pool_cache( const uint64_t& pool_house_id, const Database::row_t& rrow );
bool serve_from_cache( const string& lcase_domain_name, const string& lcase_org_query );
string build_sql_from_lookup_cache( string sqlfields );
};
#endif // __H_WPMETABACKEND_HH__
| Automattic/metadns | src/wpmetabackend.hh | C++ | gpl-2.0 | 1,972 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Colecciones")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Colecciones")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c2b407e5-79b2-49c4-8317-6b802d5b7a42")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| UNAH-SISTEMAS/2015.3.oop | 4_Colecciones/Colecciones/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,398 |
<?php
/**
* @file
* Hooks provided by Requirement Dashboard.
*/
/**
* Add requirement dashboards to be created
*
* Allows other modules to create providers for requirement dashboards
*
*/
function hook_requirement_dashboard_provider() {
// this is the machine name used on permissions page / elsewhere
$dashboards['provider_name'] = array(
// required: name of the module invoking this
'title' => 'Title of the Dashboard',
// required: menu path for accessing this
'path' => 'pathname',
);
// you can define as many providers as you want though including only 1 is more modular
$dashboards['og'] = array(
'title' => 'Group Status',
'path' => 'node/%node/og_status',
);
return $dashboards;
}
/**
* Implements hook_requirement_dashboard_provider_alter().
*/
function hook_requirement_dashboard_provider_alter(&$dashboards) {
}
/**
* Add requirments to dashboard providers
*
* Allows other modules to define requirements
* Valid severities are:
* REQUIREMENT_INFO
* REQUIREMENT_OK
* REQUIREMENT_WARNING
* REQUIREMENT_ERROR
*
*/
function hook_dashboard_requirements($provider) {
// always include a switch statement with each case being the name of a provider
switch ($provider) {
case 'provider':
// something to make this info dynamic
$calculated_value = 'something dynamic';
// you can define requirements much like the core requirements hook
$requirements['requirement_name'] = array(
// required: The title to appear in the first column
'title' => t('Title'),
// required: The value to display in the 2nd column, most likely something variable
'value' => $calculated_value,
// required: The class that should be applied, this should be calculated in most instances
'severity' => REQUIREMENT_INFO,
);
break;
case 'og':
// example requirement from the group provider
$group = og_group_get_context();
$requirements['name'] = array(
'title' => t('Group Name'),
'value' => $group->title,
'severity' => REQUIREMENT_INFO,
);
break;
}
return $requirements;
}
/**
* Implements hook_dashboard_requirements_alter().
*/
function hook_dashboard_requirements_alter(&$requirements, $provider) {
}
| eleonel/Drupaltech | profiles/elms/modules/contrib/requirement_dashboard/requirement_dashboard.api.php | PHP | gpl-2.0 | 2,304 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace proyectoprogra
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| Axel030/ProyectoFinal | proyectoprogra/proyectoprogra/Program.cs | C# | gpl-2.0 | 515 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib, urllib2
import xbmcplugin, xbmcaddon, xbmcgui, xbmc
import sys, os, re, json, base64, operator, datetime, time
from resources.local import *
pluginhandle = int(sys.argv[1])
addon = xbmcaddon.Addon()
settings = xbmcaddon.Addon( id = "plugin.video.tele.ml" )
domain = base64.b64decode(settings.getSetting("domain"))
icon_path = os.path.join(xbmc.translatePath(os.path.join(xbmc.translatePath(os.path.join(xbmc.translatePath(os.path.join("special://","home")),"addons")),"plugin.video.tele.ml")),"icon.png")
def parameters_string_to_dict(parameters):
paramDict = {}
if parameters:
paramPairs = parameters[1:].split("&")
for paramsPair in paramPairs:
paramSplits = paramsPair.split('=')
if (len(paramSplits)) == 2:
paramDict[paramSplits[0]] = paramSplits[1]
return paramDict
def translation(id):
return addon.getLocalizedString(id).encode('utf-8','ignore')
def get_list(query,data):
req = urllib2.Request(domain+'api-json-33/'+query+'.php')
f = urllib2.urlopen(req,data)
html = f.read()
f.close()
return html
def info_display(channel_info):
if ";;;" in channel_info:
channel_display = ""
nb_line = 0
nb_content = int(float(settings.getSetting("nb_epg_program")))
get_timezone = datetime.datetime.utcnow() - datetime.datetime.now()
prog_list = channel_info.split(';;;')
prog_list.pop()
for prog in prog_list:
prog_data = prog.split(';;')
progtime = datetime.datetime.fromtimestamp(time.mktime(time.strptime(prog_data[0],"%Y-%m-%d %H:%M:%S")))
displaytime = progtime - get_timezone
if ( displaytime > datetime.datetime.now() ) :
if ( nb_line < nb_content-1 ):
channel_display += displaytime.strftime("%H:%M")+" - "+prog_data[1]+"[CR]"
nb_line += 1
else:
channel_display = "[B]"+displaytime.strftime("%H:%M")+" - "+prog_data[1]+"[/B][CR]"
return channel_display.replace("\\", "")
else:
return channel_info.replace("\\", "")
def addDir(name, url, mode, iconimage, fanart, desc=""):
u = sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)
xbmcplugin.addSortMethod(pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
ok = True
liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
if ( fanart != '' ):
liz.setProperty("Fanart_Image", fanart)
liz.setInfo(type="Video", infoLabels={"Title": name, "Plot": desc})
ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True)
return ok
def categories(mode,url,path,img):
hide_adult = ( settings.getSetting( "hide_adult" ) == "true" )
empty_category = ( settings.getSetting( "empty_category" ) == "true" )
data_list = json.loads(get_list(mode,urllib.urlencode({'hide_adult': hide_adult,'empty_category': empty_category})))
if (len(data_list) > 0):
for (category_id, category_info) in data_list.items():
add_category(category_info[0], category_id, url, domain+'images/'+path+'/'+category_id+'.'+img, domain+'images/channels/'+category_info[3]+'.jpg', category_info[4], category_info[2], category_info[1])
xbmcplugin.endOfDirectory(pluginhandle)
def add_category(name, url, mode, iconimage, fanart, working, nb_channels, desc=""):
u = sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)
xbmcplugin.addSortMethod(pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
ok = True
if (working == 0):
name = name+" | "+translation(30023)
liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
if ( fanart != '' ):
liz.setProperty("Fanart_Image", fanart)
liz.setInfo(type="Video", infoLabels={"Title": name, "Plot": desc, "Genre": str(nb_channels)+" "+translation(30003)})
ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True)
return ok
def channels(mode,url):
hide_adult = ( settings.getSetting( "hide_adult" ) == "true" )
broken_channel = ( settings.getSetting( "broken_channel" ) == "true" )
epg_display = ( settings.getSetting( "epg_display" ) == "true" )
data_list = json.loads(get_list(mode,urllib.urlencode({'content_id': url, 'hide_adult': hide_adult, 'broken_channel': broken_channel, 'epg_display': epg_display})))
if (len(data_list) > 0):
sorted_data_list = sorted(data_list.items(), key=lambda k: int(k[0]))
for (channel_info) in (sorted_data_list):
add_channel(channel_info[1][0], channel_info[1][2], 'sources', domain+'images/channels/'+channel_info[1][2]+'.png', domain+'images/channels/'+channel_info[1][2]+'.jpg', "", channel_info[1][3], channel_info[1][4], channel_info[1][1])
xbmcplugin.endOfDirectory(pluginhandle)
def add_channel(name, url, mode, iconimage, fanart, channel_nb, genre, working, desc=""):
u = sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)
xbmcplugin.addSortMethod(pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
xbmcplugin.addSortMethod(pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
ok = True
if (working == 0):
name = name+" | "+translation(30023)
liz = xbmcgui.ListItem(name.replace("\\", ""), iconImage=iconimage, thumbnailImage=iconimage)
if ( fanart != '' ):
liz.setProperty("Fanart_Image", fanart)
liz.setInfo(type="Video", infoLabels={"Title": name.replace("\\", ""), "Plot": info_display(desc), "Genre": genre})
ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=False)
return ok
def sources(mode,url):
source_list = []
display_list = []
broken_stream = ( settings.getSetting( "broken_stream" ) == "true" )
geo_block = ( settings.getSetting( "geo_block" ) == "true" )
ext_player = ( settings.getSetting( "ext_player" ) == "true" )
decay_stream = ( settings.getSetting( "decay_stream" ) == "true" )
email = settings.getSetting( "email" )
password = settings.getSetting( "password" )
data_list = json.loads(get_list(mode,urllib.urlencode({'channel_id': url, 'broken_stream': broken_stream, 'geo_block': geo_block, 'ext_player': ext_player, 'decay_stream': decay_stream, 'email': email, 'password': password})))
if (len(data_list) > 0):
dialog = xbmcgui.Dialog()
try:
for (source_id, source_info) in sorted(data_list.items(), key=operator.itemgetter(1), reverse=True):
source_list.append(source_id)
stream_txt = str(source_info[0])+" px | "+source_info[1].upper()
if ( source_info[3] != 'no' ):
stream_txt = stream_txt+" | "+source_info[3].upper()+" "+translation(30019)
if ( int(source_info[4]) != 0 ):
if (int (source_info[4]) > 24):
stream_txt = stream_txt+" | +"+str(int(source_info[4])/24)+" "+translation(30024)
else:
stream_txt = stream_txt+" | +"+source_info[4]+" "+translation(30020)
if ( source_info[5] != 'no' ):
stream_txt = stream_txt+" | "+translation(30021)
if ( source_info[2] == 'no' ):
stream_txt = stream_txt+" | "+translation(30022)
display_list.append(stream_txt)
stream_url = source_info[6]
video_source = dialog.select(translation(30007), display_list)
if (not video_source == -1 ):
play_video("play_video", source_list[video_source],stream_url)
except:
xbmcgui.Dialog().ok(translation(30017), '[B]'+translation(30030)+'...[/B]', translation(30029))
def play_video(mode,stream_id,stream_url):
xbmc.executebuiltin("XBMC.Notification(%s,%s,%s,%s)" % (translation(30017),translation(30018)+'...',3000,icon_path))
data_list = json.loads(get_list(mode,urllib.urlencode({'stream_id': stream_id, 'stream_url': stream_url})))
if (len(data_list) > 0):
for (stream_id, stream_info) in data_list.items():
liz = xbmcgui.ListItem(stream_info[1], iconImage=domain+'images/channels/'+stream_info[2]+'.png', thumbnailImage=domain+'images/channels/'+stream_info[2]+'.png')
xbmc.Player( xbmc.PLAYER_CORE_MPLAYER ).play(url_convert(stream_info[0]),listitem=liz)
params = parameters_string_to_dict(sys.argv[2])
mode = urllib.unquote_plus(params.get('mode', ''))
url = urllib.unquote_plus(params.get('url', ''))
name = urllib.unquote_plus(params.get('name', ''))
if mode == 'play_video':
play_video(mode,url)
elif mode == 'sources':
sources(mode,url)
elif mode == 'channel_cont':
channels(mode,url)
elif mode == 'channel_coun':
channels(mode,url)
elif mode == 'channel_count':
channels(mode,url)
elif mode == 'category':
categories('category','channel_cont','contents','jpg')
elif mode == 'country':
categories('country','channel_coun','countries','png')
elif mode == 'langage':
categories('language','channel_count','languages','png')
elif mode == 'channel_all':
channels('channel_all',"")
else:
channel_display = ( int(settings.getSetting("category")) )
if channel_display == 0:
categories('category','channel_cont','contents','jpg')
elif channel_display == 1:
categories('country','channel_coun','countries','png')
elif channel_display == 2:
categories('language','channel_count','languages','png')
else:
channels('channel_all',"")
| idi2019/plugin.video.tele.ml | default.py | Python | gpl-2.0 | 9,683 |
from sdssgaussfitter import gaussfit
import numpy as np
import os,sys
from util import utils
from util.readDict import readDict
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def aperture(startpx,startpy,radius=7):
r = radius
length = 2*r
height = length
allx = xrange(startpx-int(np.ceil(length/2.0)),startpx+int(np.floor(length/2.0))+1)
ally = xrange(startpy-int(np.ceil(height/2.0)),startpy+int(np.floor(height/2.0))+1)
pixx = []
pixy = []
mask=np.ones((46,44))
for x in allx:
for y in ally:
if (np.abs(x-startpx))**2+(np.abs(y-startpy))**2 <= (r)**2 and 0 <= y and y < 46 and 0 <= x and x < 44:
mask[y,x]=0.
return mask
#def gaussian(height, center_x, center_y, width_x, width_y,offset):
# """Returns a gaussian function with the given parameters"""
# width_x = float(width_x)
# width_y = float(width_y)
# return lambda x,y: height*np.exp(-(((center_x-x)/width_x)**2+((center_y-y)/width_y)**2)/2)+offset
#testy = np.array([[gaussian(2,10,10,3,3,5)(x,y) for y in range(46)] for x in range(44)])
#utils.plotArray(testy,cbar=True)
param = readDict()
#param.read_from_file('G158-100params.dict')
#param.read_from_file('pg0220params.dict')
#param.read_from_file('landolt9542params.dict')
#param.read_from_file('corot18params.dict')
if len(sys.argv)<2:
print "Provide file name to fit. Syntax >>python fitPsf.py objectparams.dict [filenumber]"
sys.exit(1)
#read in parameter file as command line argument
param.read_from_file(sys.argv[1])
#provide optional file number if the object in the param file has alternate .npz files to be specified individually
fileNum = None
if len(sys.argv)>2:
fileNum = "_"+str(sys.argv[2])
npzLoadFile = param['npzLoadFile']
npzfitpsf = param['npzfitpsf']
giffitpsf = param['giffitpsf']
if fileNum != None:
npzLoadFile = npzLoadFile.split('.')[0]+fileNum+'.'+npzLoadFile.split('.')[1]
npzfitpsf = npzfitpsf.split('.')[0]+fileNum+'.'+npzfitpsf.split('.')[1]
giffitpsf = giffitpsf.split('.')[0]+fileNum+'.'+giffitpsf.split('.')[1]
FramesPerFile = param['FramesPerFile']
#NumFiles = param['NumFiles']
#for filenum in range(len(NumFiles)):
# if NumFiles[filenum] > 0:
# NumFiles[filenum] = NumFiles[filenum]*FramesPerFile
#NumFrames = NumFiles
NumFrames = 31
print "There should be this many frames: ", NumFrames
guessX = param['guessX'][0]
guessY = param['guessY'][0]
stackDict = np.load(npzLoadFile)
stack = stackDict['stack']
wvls = stackDict['wvls']
print "The file actually has this many: ", len(wvls)
paramsList = []
errorsList = []
fitImgList = []
chisqList = []
plt.ion()
for iFrame in range(0,np.shape(stack)[0]):
frame = stack[iFrame,:,:]
#print "Frame max= ", np.nanmax(frame,axis=None)
#frame *= CorrFactors
#print "Corrected Frame max= ", np.nanmax(frame,axis=None)
nanMask = np.isnan(frame)
#for interval in xrange(len(NumFrames)-1):
# if NumFrames[interval] != NumFrames[interval+1]:
# if NumFrames[interval] < iFrame <= NumFrames[interval+1]:
# guessX = guessX[interval]
# guessY = guessY[interval]
# print guessX, guessY
'''
apertureMask = aperture(guessX,guessY,radius=4)
err = np.sqrt(frame) #divide by 2 to constrain PSF fit even tighter to avoid fitting to wrong peak if PSF is divided by dead pixels
err[frame > 100]=np.inf
#err[frame<10] = 100
frame[nanMask] = 0 #set to finite value that will be ignored
err[nanMask] = np.inf #ignore these data points
err[frame==0] = np.inf
err[apertureMask==1] = 1.0 #np.sqrt(frame[apertureMask==1])/2.0 #weight points closer to the expected psf higher
nearDeadCutoff = 1 #100/15 cps for 4000-6000 angstroms
err[frame<nearDeadCutoff] = np.inf
entireMask = (err==np.inf)
maFrame = np.ma.masked_array(frame,entireMask)
'''
apertureMask = aperture(guessX,guessY,radius=7)
#if iFrame < 19:
# err = np.ones(np.shape(frame))*10.0
#else:
# err = np.zeros(np.shape(frame))
err = np.ones(np.shape(frame))*10.0
#err = (frame)**(0.5)
err[apertureMask==1] = np.inf #weight points closer to the expected psf higher
#err[frame>100] = np.inf
frame[nanMask]=0#set to finite value that will be ignored
err[nanMask] = np.inf#ignore these data points
nearDeadCutoff=1#100/15 cps for 4000-6000 angstroms
err[frame<nearDeadCutoff] = np.inf
entireMask = (err==np.inf)
maFrame = np.ma.masked_array(frame,entireMask)
#try to make smart guesses about initial parameters
#guessAmp = np.max(frame[frame!=np.nan])
#guessHeight = np.median(frame)
#guessWidth = 1.5
guessAmp = 30.
guessHeight = 5.
guessWidth = 1.3
guessParams = [guessHeight,guessAmp,guessX,guessY,guessWidth]
limitedmin = 5*[True]
limitedmax = 5*[True]
minpars = [0,0,0,0,0.1] #default min pars, usually work fine
#minpars = [0,0,27,27,1] #tighter constraint on PSF width to avoid fitting wrong peak if PSF is divided by dead pixels
maxpars = [40,200,43,43,10]
#maxpars = [40,200,33,33,10]
''' #forced parameters for Landolt standard
if iFrame == 27:
minpars = [8,5,0,0,0.5]
maxpars = [30,25,43,45,1.1]
if iFrame == 28:
minpars = [8,5,0,0,0.5]
maxpars = [30,25,43,45,1.1]
if iFrame == 29:
minpars = [8,5,0,0,0.5]
maxpars = [30,25,43,45,1.1]
if iFrame == 30:
minpars = [8,5,0,0,0.5]
maxpars = [30,25,43,45,1.10]
'''
usemoments=[True,True,True,True,True] #doesn't use our guess values, default
#usemoments=[False,False,False,False,False]
print "=========================="
print wvls[iFrame]
print "frame ",iFrame
out = gaussfit(data=maFrame,err=err,params=guessParams,returnfitimage=True,quiet=True,limitedmin=limitedmin,limitedmax=limitedmax,minpars=minpars,maxpars=maxpars,circle=1,usemoments=usemoments,returnmp=True)
mp = out[0]
outparams = mp.params
paramErrors = mp.perror
chisq = mp.fnorm
dof = mp.dof
reducedChisq = chisq/dof
print "reducedChisq =", reducedChisq
fitimg = out[1]
chisqList.append([chisq,dof])
paramsList.append(outparams)
errorsList.append(paramErrors)
print "outparams = ", outparams
print "paramErrors = ", paramErrors
# expectedResiduals = np.ma.masked_array(np.sqrt(frame),mask=entireMask)
# residuals = np.ma.masked_array(np.abs(frame-fitimg),mask=entireMask)
# utils.plotArray(expectedResiduals,cbar=True)
# utils.plotArray(residuals,cbar=True)
# fig = plt.figure()
# ax = fig.add_subplot(111,projection='3d')
# x = np.arange(0,44)
# y = np.arange(0,46)
# X,Y = np.meshgrid(x,y)
# linearMask = np.ravel(entireMask==0)
# ax.plot_wireframe(X,Y,fitimg)
# ax.scatter(outparams[2],outparams[3],outparams[0]+outparams[1],c='black')
# ax.scatter(np.ravel(X)[linearMask],np.ravel(Y)[linearMask],np.ravel(frame)[linearMask],c='red')
#
fitimg[nanMask]=0
# print fitimg[np.isnan(fitimg)]
fitImgList.append(fitimg)
# utils.plotArray(frame,cbar=True)
# utils.plotArray(maFrame,cbar=True)
# utils.plotArray(fitimg,cbar=True)
# plt.show()
# utils.confirm('Enter to continue.')
# plt.close()
# plt.close()
# plt.close()
frame[nanMask]=np.nan
# fig = plt.figure()
# ax1=fig.add_subplot(211)
# ax2 = fig.add_subplot(212)
# for iRow in range(len(frame)):
# ax1.scatter(range(44),frame[iRow,:],c='red',marker='o',alpha=.5,label='data')
# ax1.scatter(range(44),fitimg[iRow,:],c='blue',marker='^',alpha=.5,label='fit')
# ax1.set_title('Fit seen along Cols')
# for iCol in range(np.shape(frame)[1]):
# ax2.scatter(range(46),frame[:,iCol],c='red',marker='o',alpha=.5,label='data')
# ax2.scatter(range(46),fitimg[:,iCol],c='blue',marker='^',alpha=.5,label='fit')
# ax2.set_title('Fit seen along Rows')
# plt.show()
plt.close()
print 'closed'
cube = np.array(fitImgList)
chisqs = np.array(chisqList)
params = np.array(paramsList)
errors = np.array(errorsList)
np.savez(npzfitpsf,fitImg=cube,params=params,errors=errors,chisqs=chisqs,wvls=wvls)
print 'saved'
utils.makeMovie(fitImgList,frameTitles=wvls, cbar=True, outName=giffitpsf, normMin=0, normMax=50)
| bmazin/ARCONS-pipeline | examples/Pal2012_landoltPhot/fitPsf.py | Python | gpl-2.0 | 8,372 |
"use strict";
var log = require( "../class.log" );
var realmConfig = require( "../../config.realm" ).config;
var quest = require( "../class.quest" );
exports.script = function( npcObject )
{
//
// Variables
//
var _iO = npcObject.getArgs().createdByInstanceObject,
_cooldownPointer = null;
var questIdConstant_62 = 49;
var questParameterNameConstant_63 = "q49_3AttackFirstTargetDummy";
var numberConstant_64 = 1;
//
// Events override
//
npcObject.events._add( "damageTake", function( args )
{
var fromCharacterObject_23 = args.fromCharacterObject;
var amount_24 = args.amount;
quest.questConditionUpdate(
{
characterObject: fromCharacterObject_23,
questId: questIdConstant_62,
parameterName: questParameterNameConstant_63,
value: numberConstant_64,
}
);
});
//
// Post all objects initialisation
//
this.postInit = function()
{
}
//
// Initialize
//
// bind to instance
npcObject.events._add( "afterInit", function( args )
{
npcObject.bindToInstance( _iO, function() { } );
});
}
| victoralex/gameleon | includes/classes/class.npc.js_files/npcScript.221.js | JavaScript | gpl-2.0 | 1,247 |
<?php
//custom post type portfolio
if(! function_exists( 'kilobyte_custom_post_type_portfolio' )):
function kilobyte_custom_post_type_portfolio(){
$labels = array(
'name'=>'Portfolio',
'singular_name'=>'Portfolio',
'add_new' => 'Add Portfolio',
'all_items' => 'All Portfolio',
'add_new_item'=> 'Add Portfolio',
'new_item' => 'New Portfolio',
'view_item' => 'View Portfolio',
'search_item' => 'Search Portfolio',
'not_found' => 'no items found',
'not_found_in_trash' => 'not found in trash',
'parent_item_colon' => 'parent'
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'publicaly_queryable' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' =>'post',
'heirarchical' => false,
'supports' => array(
'title',
'editor',
'thumbnail',
'excerpt',
'revisons',
'custom-fields',
),
'menu_position' => 5,
'rewrite' => array( 'slug' => 'portfolio','with_front' => false ),
'exclude_from_search' => false
);
register_post_type('post-type-portfolio',$args);
}
endif;
add_action('init','kilobyte_custom_post_type_portfolio' );
//custom post type Case Study
if(!function_exists( 'kilobyte_custom_post_type_casestudy')):
function kilobyte_custom_post_type_casestudy(){
$labels2 = array(
'name'=>'Case Study',
'singular_name'=>'Case Study',
'add_new' => 'Add Case Study',
'all_items' => 'All Case Study',
'add_new_item'=> 'Add Case Study',
'new_item' => 'New Case Study',
'view_item' => 'View Case Study',
'search_item' => 'Search Case Study',
'not_found' => 'no items found',
'not_found_in_trash' => 'not found in trash',
'parent_item_colon' => 'parent'
);
$args2 = array(
'labels' => $labels2,
'public' => true,
'has_archive' => true,
'publicaly_queryable' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'casestudy','with_front' => false ),
'capability_type' =>'post',
'heirarchical' => false,
'supports' => array(
'title',
'editor',
'thumbnail',
'excerpt',
'revisons',
'post_formats',
'custom-fields'
),
'menu_position' => 6,
'exclude_from_search' => false
);
register_post_type('post-type-casestudy',$args2);
}
endif;
add_action('init','kilobyte_custom_post_type_casestudy' );
//custom taxonomies
if ( ! function_exists( 'kilobyte_custom_taxonomy')):
function kilobyte_custom_taxonomy(){
$labels = array(
'name' => 'Portfolio types',
'singular_name' => 'Portfolio types',
'search_items' => 'search types',
'all_items' => 'all types',
'parent_item' => 'parent Type',
'parent_item_colon' => 'parent Type',
'edit_item' => 'edit Type',
'update_item' => 'update Type',
'new_item_name' => 'new type Name',
'menu_name' => 'Portfolio types'
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'portfolio/type','with_front' => false ),
);
register_taxonomy('Portfolio Types',array('post-type-portfolio'),$args );
}
endif;
add_action('init','kilobyte_custom_taxonomy' );
// taxonomy for casestudy
if ( ! function_exists( 'kilobyte_custom_taxonomy_casestudy')):
function kilobyte_custom_taxonomy_casestudy(){
$labels = array(
'name' => 'Casestudy type',
'singular_name' => 'Casestudy type',
'search_items' => 'search types',
'all_items' => 'all types',
'parent_item' => 'parent Type',
'parent_item_colon' => 'parent Type',
'edit_item' => 'edit Type',
'update_item' => 'update Type',
'new_item_name' => 'new type Name',
'menu_name' => 'Casestudy type'
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'casestudy/type' ),
);
register_taxonomy('Casestudy type',array('post-type-casestudy'),$args );
}
endif;
add_action('init','kilobyte_custom_taxonomy_casestudy' );
//custom post type Personal blogs
if(!function_exists( 'kilobyte_custom_post_type_Personalblogs')):
function kilobyte_custom_post_type_Personalblogs(){
$labels = array(
'name'=>'Personal blogs',
'singular_name'=>'Personal blogs',
'add_new' => 'Add Personal blogs',
'all_items' => 'All Personal blogs',
'add_new_item'=> 'Add Personal blogs',
'new_item' => 'New Personal blogs',
'view_item' => 'View Personal blogs',
'search_item' => 'Search Personal blogs',
'not_found' => 'no items found',
'not_found_in_trash' => 'not found in trash',
'parent_item_colon' => 'parent'
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'publicaly_queryable' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'Personalblogs','with_front' => false ),
'capability_type' =>'post',
'heirarchical' => false,
'supports' => array(
'title',
'editor',
'thumbnail',
'excerpt',
'revisons',
'post_formats',
'custom-fields'
),
'menu_position' => 7,
'exclude_from_search' => false
);
register_post_type('Personalblogs',$args);
}
endif;
add_action('init','kilobyte_custom_post_type_Personalblogs' );
// taxonomy for Personalblogs
if ( ! function_exists( 'kilobyte_custom_taxonomy_Personalblogs')):
function kilobyte_custom_taxonomy_Personalblogs(){
$labels = array(
'name' => 'Personalblogs type',
'singular_name' => 'Personalblogs type',
'search_items' => 'search types',
'all_items' => 'all types',
'parent_item' => 'parent Type',
'parent_item_colon' => 'parent Type',
'edit_item' => 'edit Type',
'update_item' => 'update Type',
'new_item_name' => 'new type Name',
'menu_name' => 'Personalblogs type'
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'Personalblogs' ),
);
register_taxonomy('Personalblogs type',array('post-type-Personalblogs'),$args );
}
endif;
add_action('init','kilobyte_custom_taxonomy_Personalblogs' );
| shubham9411/kilobyte | inc/custom-posttype.php | PHP | gpl-2.0 | 6,356 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest19157")
public class BenchmarkTest19157 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] values = request.getParameterValues("foo");
String param;
if (values.length != 0)
param = request.getParameterValues("foo")[0];
else param = null;
String bar = doSomething(param);
try {
javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) Test Case");
throw new ServletException(e);
} catch (java.security.NoSuchProviderException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) Test Case");
throw new ServletException(e);
} catch (javax.crypto.NoSuchPaddingException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) Test Case");
throw new ServletException(e);
}
response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) executed");
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
String bar = valuesList.get(1); // get the last 'safe' value
return bar;
}
}
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest19157.java | Java | gpl-2.0 | 3,011 |
<?php
/**
* @file
* Hooks provided the Entity module.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Inform the base system and the Field API about one or more entity types.
*
* Inform the system about one or more entity types (i.e., object types that
* can be loaded via entity_load() and, optionally, to which fields can be
* attached).
*
* @return
* An array whose keys are entity type names and whose values identify
* properties of those types that the system needs to know about:
* - label: The human-readable name of the type.
* - entity class: The name of the entity class, defaults to
* Drupal\Core\Entity\Entity. The entity class must implement EntityInterface.
* - controller class: The name of the class that is used to load the objects.
* The class has to implement the
* Drupal\Core\Entity\EntityStorageControllerInterface interface. Leave blank
* to use the Drupal\Core\Entity\DatabaseStorageController implementation.
* - render controller class: The name of the class that is used to render
* the entities. Deafaults to Drupal\Core\Entity\EntityRenderController.
* - form controller class: An associative array where the keys are the names
* of the different form operations (such as creation, editing or deletion)
* and the values are the names of the controller classes. To facilitate
* supporting the case where an entity form varies only slightly between
* different operations, the name of the operation is passed also to the
* constructor of the form controller class. This way, one class can be used
* for multiple entity forms.
* - list controller class: The name of the class that is used to provide
* listings of the entity. The class must implement
* Drupal\Core\Entity\EntityListControllerInterface. Defaults to
* Drupal\Core\Entity\EntityListController.
* - base table: (used by Drupal\Core\Entity\DatabaseStorageController) The
* name of the entity type's base table.
* - static cache: (used by Drupal\Core\Entity\DatabaseStorageController)
* FALSE to disable static caching of entities during a page request.
* Defaults to TRUE.
* - field cache: (used by Field API loading and saving of field data) FALSE
* to disable Field API's persistent cache of field data. Only recommended
* if a higher level persistent cache is available for the entity type.
* Defaults to TRUE.
* - uri callback: A function taking an entity as argument and returning the
* URI elements of the entity, e.g. 'path' and 'options'. The actual entity
* URI can be constructed by passing these elements to url().
* - label callback: (optional) A function taking an entity and optional langcode
* argument, and returning the label of the entity. If langcode is omitted, the
* entity's default language is used.
*
* The entity label is the main string associated with an entity; for
* example, the title of a node or the subject of a comment. If there is an
* entity object property that defines the label, use the 'label' element
* of the 'entity keys' return value component to provide this information
* (see below). If more complex logic is needed to determine the label of
* an entity, you can instead specify a callback function here, which will
* be called to determine the entity label. See also the
* Drupal\Core\Entity\Entity::label() method, which implements this logic.
* - fieldable: Set to TRUE if you want your entity type to be fieldable.
* - translation: An associative array of modules registered as field
* translation handlers. Array keys are the module names, array values
* can be any data structure the module uses to provide field translation.
* Any empty value disallows the module to appear as a translation handler.
* - entity keys: An array describing how the Field API can extract the
* information it needs from the objects of the type. Elements:
* - id: The name of the property that contains the primary id of the
* entity. Every entity object passed to the Field API must have this
* property and its value must be numeric.
* - revision: The name of the property that contains the revision id of
* the entity. The Field API assumes that all revision ids are unique
* across all entities of a type. This entry can be omitted if the
* entities of this type are not versionable.
* - bundle: The name of the property that contains the bundle name for the
* entity. The bundle name defines which set of fields are attached to
* the entity (e.g. what nodes call "content type"). This entry can be
* omitted if this entity type exposes a single bundle (all entities have
* the same collection of fields). The name of this single bundle will be
* the same as the entity type.
* - label: The name of the property that contains the entity label. For
* example, if the entity's label is located in $entity->subject, then
* 'subject' should be specified here. If complex logic is required to
* build the label, a 'label callback' should be defined instead (see
* the 'label callback' section above for details).
* - uuid (optional): The name of the property that contains the universally
* unique identifier of the entity, which is used to distinctly identify
* an entity across different systems.
* - bundle keys: An array describing how the Field API can extract the
* information it needs from the bundle objects for this type (e.g
* $vocabulary objects for terms; not applicable for nodes). This entry can
* be omitted if this type's bundles do not exist as standalone objects.
* Elements:
* - bundle: The name of the property that contains the name of the bundle
* object.
* - bundles: An array describing all bundles for this object type. Keys are
* bundles machine names, as found in the objects' 'bundle' property
* (defined in the 'entity keys' entry above). Elements:
* - label: The human-readable name of the bundle.
* - uri callback: Same as the 'uri callback' key documented above for the
* entity type, but for the bundle only. When determining the URI of an
* entity, if a 'uri callback' is defined for both the entity type and
* the bundle, the one for the bundle is used.
* - admin: An array of information that allows Field UI pages to attach
* themselves to the existing administration pages for the bundle.
* Elements:
* - path: the path of the bundle's main administration page, as defined
* in hook_menu(). If the path includes a placeholder for the bundle,
* the 'bundle argument', 'bundle helper' and 'real path' keys below
* are required.
* - bundle argument: The position of the placeholder in 'path', if any.
* - real path: The actual path (no placeholder) of the bundle's main
* administration page. This will be used to generate links.
* - access callback: As in hook_menu(). 'user_access' will be assumed if
* no value is provided.
* - access arguments: As in hook_menu().
* - view modes: An array describing the view modes for the entity type. View
* modes let entities be displayed differently depending on the context.
* For instance, a node can be displayed differently on its own page
* ('full' mode), on the home page or taxonomy listings ('teaser' mode), or
* in an RSS feed ('rss' mode). Modules taking part in the display of the
* entity (notably the Field API) can adjust their behavior depending on
* the requested view mode. An additional 'default' view mode is available
* for all entity types. This view mode is not intended for actual entity
* display, but holds default display settings. For each available view
* mode, administrators can configure whether it should use its own set of
* field display settings, or just replicate the settings of the 'default'
* view mode, thus reducing the amount of display configurations to keep
* track of. Keys of the array are view mode names. Each view mode is
* described by an array with the following key/value pairs:
* - label: The human-readable name of the view mode
* - custom settings: A boolean specifying whether the view mode should by
* default use its own custom field display settings. If FALSE, entities
* displayed in this view mode will reuse the 'default' display settings
* by default (e.g. right after the module exposing the view mode is
* enabled), but administrators can later use the Field UI to apply custom
* display settings specific to the view mode.
*
* @see entity_load()
* @see entity_load_multiple()
* @see hook_entity_info_alter()
*/
function hook_entity_info() {
$return = array(
'node' => array(
'label' => t('Node'),
'entity class' => 'Drupal\node\Node',
'controller class' => 'Drupal\node\NodeStorageController',
'form controller class' => array(
'default' => 'Drupal\node\NodeFormController',
),
'base table' => 'node',
'revision table' => 'node_revision',
'uri callback' => 'node_uri',
'fieldable' => TRUE,
'translation' => array(
'locale' => TRUE,
),
'entity keys' => array(
'id' => 'nid',
'revision' => 'vid',
'bundle' => 'type',
'uuid' => 'uuid',
),
'bundle keys' => array(
'bundle' => 'type',
),
'bundles' => array(),
'view modes' => array(
'full' => array(
'label' => t('Full content'),
'custom settings' => FALSE,
),
'teaser' => array(
'label' => t('Teaser'),
'custom settings' => TRUE,
),
'rss' => array(
'label' => t('RSS'),
'custom settings' => FALSE,
),
),
),
);
// Search integration is provided by node.module, so search-related
// view modes for nodes are defined here and not in search.module.
if (module_exists('search')) {
$return['node']['view modes'] += array(
'search_index' => array(
'label' => t('Search index'),
'custom settings' => FALSE,
),
'search_result' => array(
'label' => t('Search result'),
'custom settings' => FALSE,
),
);
}
// Bundles must provide a human readable name so we can create help and error
// messages, and the path to attach Field admin pages to.
foreach (node_type_get_names() as $type => $name) {
$return['node']['bundles'][$type] = array(
'label' => $name,
'admin' => array(
'path' => 'admin/structure/types/manage/%node_type',
'real path' => 'admin/structure/types/manage/' . $type,
'bundle argument' => 4,
'access arguments' => array('administer content types'),
),
);
}
return $return;
}
/**
* Alter the entity info.
*
* Modules may implement this hook to alter the information that defines an
* entity. All properties that are available in hook_entity_info() can be
* altered here.
*
* @param $entity_info
* The entity info array, keyed by entity name.
*
* @see hook_entity_info()
*/
function hook_entity_info_alter(&$entity_info) {
// Set the controller class for nodes to an alternate implementation of the
// Drupal\Core\Entity\EntityStorageControllerInterface interface.
$entity_info['node']['controller class'] = 'Drupal\mymodule\MyCustomNodeStorageController';
}
/**
* Act on entities when loaded.
*
* This is a generic load hook called for all entity types loaded via the
* entity API.
*
* @param array $entities
* The entities keyed by entity ID.
* @param string $entity_type
* The type of entities being loaded (i.e. node, user, comment).
*/
function hook_entity_load($entities, $entity_type) {
foreach ($entities as $entity) {
$entity->foo = mymodule_add_something($entity);
}
}
/**
* Act on an entity before it is about to be created or updated.
*
* @param Drupal\Core\Entity\EntityInterface $entity
* The entity object.
*/
function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
$entity->changed = REQUEST_TIME;
}
/**
* Act on entities when inserted.
*
* @param Drupal\Core\Entity\EntityInterface $entity
* The entity object.
*/
function hook_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
// Insert the new entity into a fictional table of all entities.
db_insert('example_entity')
->fields(array(
'type' => $entity->entityType(),
'id' => $entity->id(),
'created' => REQUEST_TIME,
'updated' => REQUEST_TIME,
))
->execute();
}
/**
* Act on entities when updated.
*
* @param Drupal\Core\Entity\EntityInterface $entity
* The entity object.
*/
function hook_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
// Update the entity's entry in a fictional table of all entities.
db_update('example_entity')
->fields(array(
'updated' => REQUEST_TIME,
))
->condition('type', $entity->entityType())
->condition('id', $entity->id())
->execute();
}
/**
* Act before entity deletion.
*
* This hook runs after the entity type-specific predelete hook.
*
* @param Drupal\Core\Entity\EntityInterface $entity
* The entity object for the entity that is about to be deleted.
*/
function hook_entity_predelete(Drupal\Core\Entity\EntityInterface $entity) {
// Count references to this entity in a custom table before they are removed
// upon entity deletion.
$id = $entity->id();
$type = $entity->entityType();
$count = db_select('example_entity_data')
->condition('type', $type)
->condition('id', $id)
->countQuery()
->execute()
->fetchField();
// Log the count in a table that records this statistic for deleted entities.
$ref_count_record = (object) array(
'count' => $count,
'type' => $type,
'id' => $id,
);
drupal_write_record('example_deleted_entity_statistics', $ref_count_record);
}
/**
* Respond to entity deletion.
*
* This hook runs after the entity type-specific delete hook.
*
* @param Drupal\Core\Entity\EntityInterface $entity
* The entity object for the entity that has been deleted.
*/
function hook_entity_delete(Drupal\Core\Entity\EntityInterface $entity) {
// Delete the entity's entry from a fictional table of all entities.
db_delete('example_entity')
->condition('type', $entity->entityType())
->condition('id', $entity->id())
->execute();
}
/**
* Alter or execute an Drupal\Core\Entity\EntityFieldQuery.
*
* @param Drupal\Core\Entity\EntityFieldQuery $query
* An EntityFieldQuery. One of the most important properties to be changed is
* EntityFieldQuery::executeCallback. If this is set to an existing function,
* this function will get the query as its single argument and its result
* will be the returned as the result of EntityFieldQuery::execute(). This can
* be used to change the behavior of EntityFieldQuery entirely. For example,
* the default implementation can only deal with one field storage engine, but
* it is possible to write a module that can query across field storage
* engines. Also, the default implementation presumes entities are stored in
* SQL, but the execute callback could instead query any other entity storage,
* local or remote.
*
* Note the $query->altered attribute which is TRUE in case the query has
* already been altered once. This happens with cloned queries.
* If there is a pager, then such a cloned query will be executed to count
* all elements. This query can be detected by checking for
* ($query->pager && $query->count), allowing the driver to return 0 from
* the count query and disable the pager.
*/
function hook_entity_query_alter(Drupal\Core\Entity\EntityFieldQuery $query) {
$query->executeCallback = 'my_module_query_callback';
}
/**
* Act on entities being assembled before rendering.
*
* @param Drupal\Core\Entity\EntityInterface $entity
* The entity object.
* @param $view_mode
* The view mode the entity is rendered in.
* @param $langcode
* The language code used for rendering.
*
* The module may add elements to $entity->content prior to rendering. The
* structure of $entity->content is a renderable array as expected by
* drupal_render().
*
* @see hook_entity_view_alter()
* @see hook_comment_view()
* @see hook_node_view()
* @see hook_user_view()
*/
function hook_entity_view(Drupal\Core\Entity\EntityInterface $entity, $view_mode, $langcode) {
$entity->content['my_additional_field'] = array(
'#markup' => $additional_field,
'#weight' => 10,
'#theme' => 'mymodule_my_additional_field',
);
}
/**
* Alter the results of ENTITY_view().
*
* This hook is called after the content has been assembled in a structured
* array and may be used for doing processing which requires that the complete
* entity content structure has been built.
*
* If a module wishes to act on the rendered HTML of the entity rather than the
* structured content array, it may use this hook to add a #post_render
* callback. Alternatively, it could also implement hook_preprocess_HOOK() for
* the particular entity type template, if there is one (e.g., node.tpl.php).
* See drupal_render() and theme() for details.
*
* @param $build
* A renderable array representing the entity content.
* @param Drupal\Core\Entity\EntityInterface $entity
* The entity object being rendered.
*
* @see hook_entity_view()
* @see hook_comment_view_alter()
* @see hook_node_view_alter()
* @see hook_taxonomy_term_view_alter()
* @see hook_user_view_alter()
*/
function hook_entity_view_alter(&$build, Drupal\Core\Entity\EntityInterface $entity) {
if ($build['#view_mode'] == 'full' && isset($build['an_additional_field'])) {
// Change its weight.
$build['an_additional_field']['#weight'] = -10;
// Add a #post_render callback to act on the rendered HTML of the entity.
$build['#post_render'][] = 'my_module_node_post_render';
}
}
/**
* Act on entities as they are being prepared for view.
*
* Allows you to operate on multiple entities as they are being prepared for
* view. Only use this if attaching the data during the entity loading phase
* is not appropriate, for example when attaching other 'entity' style objects.
*
* @param array $entities
* The entities keyed by entity ID.
* @param string $entity_type
* The type of entities being viewed (i.e. node, user, comment).
*/
function hook_entity_prepare_view($entities, $entity_type) {
// Load a specific node into the user object for later theming.
if (!empty($entities) && $entity_type == 'user') {
$nodes = mymodule_get_user_nodes(array_keys($entities));
foreach ($entities as $uid => $entity) {
$entity->user_node = $nodes[$uid];
}
}
}
/**
* Change the view mode of an entity that is being displayed.
*
* @param string $view_mode
* The view_mode that is to be used to display the entity.
* @param Drupal\Core\Entity\EntityInterface $entity
* The entity that is being viewed.
* @param array $context
* Array with additional context information, currently only contains the
* langcode the entity is viewed in.
*/
function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
// For nodes, change the view mode when it is teaser.
if ($entity->entityType() == 'node' && $view_mode == 'teaser') {
$view_mode = 'my_custom_view_mode';
}
}
/**
* Define custom entity properties.
*
* @param string $entity_type
* The entity type for which to define entity properties.
*
* @return array
* An array of property information having the following optional entries:
* - definitions: An array of property definitions to add all entities of this
* type, keyed by property name. See
* Drupal\Core\TypedData\TypedDataManager::create() for a list of supported
* keys in property definitions.
* - optional: An array of property definitions for optional properties keyed
* by property name. Optional properties are properties that only exist for
* certain bundles of the entity type.
* - bundle map: An array keyed by bundle name containing the names of
* optional properties that entities of this bundle have.
*
* @see Drupal\Core\TypedData\TypedDataManager::create()
* @see hook_entity_field_info_alter()
* @see Drupal\Core\Entity\StorageControllerInterface::getPropertyDefinitions()
*/
function hook_entity_field_info($entity_type) {
if (mymodule_uses_entity_type($entity_type)) {
$info = array();
$info['definitions']['mymodule_text'] = array(
'type' => 'string_item',
'list' => TRUE,
'label' => t('The text'),
'description' => t('A text property added by mymodule.'),
'computed' => TRUE,
'class' => '\Drupal\mymodule\EntityComputedText',
);
if ($entity_type == 'node') {
// Add a property only to entities of the 'article' bundle.
$info['optional']['mymodule_text_more'] = array(
'type' => 'string_item',
'list' => TRUE,
'label' => t('More text'),
'computed' => TRUE,
'class' => '\Drupal\mymodule\EntityComputedMoreText',
);
$info['bundle map']['article'][0] = 'mymodule_text_more';
}
return $info;
}
}
/**
* Alter defined entity properties.
*
* @param array $info
* The property info array as returned by hook_entity_field_info().
* @param string $entity_type
* The entity type for which entity properties are defined.
*
* @see hook_entity_field_info()
*/
function hook_entity_field_info_alter(&$info, $entity_type) {
if (!empty($info['definitions']['mymodule_text'])) {
// Alter the mymodule_text property to use a custom class.
$info['definitions']['mymodule_text']['class'] = '\Drupal\anothermodule\EntityComputedText';
}
}
| dusik/realejuventudfan | core/includes/entity.api.php | PHP | gpl-2.0 | 22,131 |
/****************************************************************************
** $Id: qt/main.cpp 3.3.8 edited Jan 11 14:37 $
**
** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.
**
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
#include <qapplication.h>
#include "tooltip.h"
int main( int argc, char ** argv )
{
QApplication a( argc, argv );
TellMe mw;
mw.setCaption( "Qt Example - Dynamic Tool Tips" );
a.setMainWidget( &mw );
mw.show();
return a.exec();
}
| epatel/qt-mac-free-3.3.8 | examples/tooltip/main.cpp | C++ | gpl-2.0 | 679 |
#!/usr/bin/env python
#encoding: utf-8
# Martin Kersner, m.kersner@gmail.com
# 2016/03/17
from __future__ import print_function
import os
import sys
import glob,cv2
from PIL import Image as PILImage
import numpy as np
from utils import mat2png_hariharan,pascal_palette_invert
def main():
input_path, output_path = process_arguments(sys.argv)
if os.path.isdir(input_path) and os.path.isdir(output_path):
# glob.blob 返回所有匹配的文件路径列表
mat_files = glob.glob(os.path.join(input_path, '*.mat'))
convert_mat2png(mat_files, output_path)
else:
help('Input or output path does not exist!\n')
def process_arguments(argv):
num_args = len(argv)
input_path = None
output_path = None
if num_args == 3:
input_path = argv[1]
output_path = argv[2]
else:
help()
if not os.path.exists(output_path):
os.makedirs(output_path)
return input_path, output_path
def convert_mat2png(mat_files, output_path):
if not mat_files:
help('Input directory does not contain any Matlab files!\n')
l2c = pascal_palette_invert()
for ind,mat in enumerate(mat_files):
print(ind,mat)
numpy_img = mat2png_hariharan(mat)
color = np.zeros( numpy_img.shape + (3,))
for l in l2c.keys():
color[numpy_img == l,:] = l2c[l]
pil_img = PILImage.fromarray(color.astype('uint8'))
#pil_img = PILImage.fromarray(numpy_img).convert("RGB")
#for y in range(numpy_img.shape[0]):
# for x in range(numpy_img.shape[1]):
# c = l2c[numpy_img[y,x]]
# pil_img.putpixel((x,y),c)
#pil_img = PILImage.fromarray(numpy_img)
pil_img.save(os.path.join(output_path, modify_image_name(mat, 'png')))
# Extract name of image from given path, replace its extension with specified one
# and return new name only, not path.
def modify_image_name(path, ext):
return os.path.basename(path).split('.')[0] + '.' + ext
def help(msg=''):
print(msg +
'Usage: python mat2png.py INPUT_PATH OUTPUT_PATH\n'
'INPUT_PATH denotes path containing Matlab files for conversion.\n'
'OUTPUT_PATH denotes path where converted Png files ar going to be saved.'
, file=sys.stderr)
exit()
if __name__ == '__main__':
main()
| z01nl1o02/tests | voc/sbd_dataset/mat2png.py | Python | gpl-2.0 | 2,232 |
<?php
/**
* Part of Component Schedule files.
*
* @copyright Copyright (C) 2014 Asikart. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access
defined('_JEXEC') or die;
include_once JPATH_LIBRARIES . '/windwalker/src/init.php';
JForm::addFieldPath(WINDWALKER_SOURCE . '/Form/Fields');
JFormHelper::loadFieldClass('Modal');
/**
* Supports a modal picker.
*/
class JFormFieldTask_Modal extends JFormFieldModal
{
/**
* The form field type.
*
* @var string
* @since 1.6
*/
protected $type = 'Task_Modal';
/**
* List name.
*
* @var string
*/
protected $view_list = 'tasks';
/**
* Item name.
*
* @var string
*/
protected $view_item = 'task';
/**
* Extension name, eg: com_content.
*
* @var string
*/
protected $extension = 'com_schedule';
}
| skylying/ihealth-schedule | administrator/components/com_schedule/model/field/task/modal.php | PHP | gpl-2.0 | 864 |
package zhangXiaoXiang.s02_;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Bob
* @ClassName: HelloServlet
* @Description: servlet代码初探(本段注释来自《Servlet与JSP核心编程》,而不是张孝祥视频讲解)
* @1 servlet是常规的java代码:这段代码用了新的API,但不涉及新的语法
* @2 servlet和JSP API不属于java2 平台标准版(Java 2 Platform,Standard Edition,J2SE);他们是单独的规范
* @3 它对标准的类(HttpServlet)进行了扩展:servlet为应对HTTP提供了大量的基础结构
* @4 它覆盖了doGet方法:servlet用不同的方法响应不同类型的HTTP命令
* @date 2015年2月13日 下午1:14:27
*/
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = -2264760525610612443L;
/**
* servlet
*/
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException {
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<font size = 30 color=red>Hello servlet !</font><br>");
pw.println("<marquee>" + new java.util.Date() + "</marquee>");
pw.println("</html>");
}
}
| NorthFacing/step-by-Java | web-servletAndJsp/src/main/java/zhangXiaoXiang/s02_/HelloServlet.java | Java | gpl-2.0 | 1,343 |
package com.vv.minerlamp.entity;
import java.sql.Blob;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "staff")
public class Staff {
private Long id;
private Long workId;
private String name;
private Integer sex;
private String birthDate;
private String certificateNo;
private String eduLevel;
private String phone;
private String address;
private Long rackId;
private Long lampNo;
private Long professionId;
private String profession;
private Long departmentId;
private String department;
private Long clazzId;
private String clazz;
private Blob image;
private Date chargingLastTime; //ÃüÃûÓÐÎó£¬Êµ¼ÊÊÇ×¼±¸Ï¾®Ê±¼ä£¬¶ø²»ÊÇ¿ªÊ¼³äµçʱ¼ä
// public static final int BATTERY_NOTUSE = 0;
// public static final int BATTERY_UNDERGROUND = 1;
// public static final int BATTERY_CHARGING = 2;
// public static final int BATTERY_FULL = 3;
// public static final int BATTERY_ERROR = 4;
//
// public static final int BATTERY_ACTION_NEW = 0;
// public static final int BATTERY_ACTION_EDIT = 1;
// public static final int BATTERY_ACTION_DELETE = 2;
public static final int STAFF_MODEL_TYPE_1 = 1;
public static final int STAFF_MODEL_TYPE_2 = 2;
public Staff() {
}
public Staff(Long workId, String name, int sex, String birthDate,
String certificateNo, String eduLevel, String phone,
String address, Long rackId, Long lampNo, Long professionId,
String profession, Long departmentId, String department,
Long clazzId, String clazz, Blob image) {
super();
this.workId = workId;
this.name = name;
this.sex = sex;
this.birthDate = birthDate;
this.certificateNo = certificateNo;
this.eduLevel = eduLevel;
this.phone = phone;
this.address = address;
this.rackId = rackId;
this.lampNo = lampNo;
this.professionId = professionId;
this.profession = profession;
this.departmentId = departmentId;
this.department = department;
this.clazzId = clazzId;
this.clazz = clazz;
this.image = image;
}
@Id
@GeneratedValue
@Column(name = "ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "work_id", nullable = false)
public Long getWorkId() {
return workId;
}
public void setWorkId(Long workId) {
this.workId = workId;
}
@Column(name = "sex")
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
@Column(name = "birth_date")
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
@Column(name = "certificate_no")
public String getCertificateNo() {
return certificateNo;
}
public void setCertificateNo(String certificateNo) {
this.certificateNo = certificateNo;
}
@Column(name = "edu_level")
public String getEduLevel() {
return eduLevel;
}
public void setEduLevel(String eduLevel) {
this.eduLevel = eduLevel;
}
@Column(name = "phone")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Column(name = "address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Column(name = "rack_id")
public Long getRackId() {
return rackId;
}
public void setRackId(Long rackId) {
this.rackId = rackId;
}
@Column(name = "lamp_no")
public Long getLampNo() {
return lampNo;
}
public void setLampNo(Long lampNo) {
this.lampNo = lampNo;
}
@Column(name = "profession_id")
public Long getProfessionId() {
return professionId;
}
public void setProfessionId(Long professionId) {
this.professionId = professionId;
}
@Column(name = "profession")
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
@Column(name = "department_id")
public Long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Long departmentId) {
this.departmentId = departmentId;
}
@Column(name = "department")
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
@Column(name = "clazz_id")
public Long getClazzId() {
return clazzId;
}
public void setClazzId(Long clazzId) {
this.clazzId = clazzId;
}
@Column(name = "clazz")
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
@Column(name = "image")
public Blob getImage() {
return image;
}
public void setImage(Blob image) {
this.image = image;
}
@Column(name = "charging_lasttime")
public Date getChargingLastTime() {
return chargingLastTime;
}
public void setChargingLastTime(Date chargingLastTime) {
this.chargingLastTime = chargingLastTime;
}
@Override
public String toString() {
return name;
}
}
| vvdeng/MinerLampSystem | src/com/vv/minerlamp/entity/Staff.java | Java | gpl-2.0 | 5,423 |
package moviescraper.doctord.controller.xmlserialization;
import java.io.IOException;
import moviescraper.doctord.model.dataitem.Thumb;
/**
* Helper class for serializing a fanart object to and from XML
*/
public class KodiXmlFanartBean {
private String[] thumb;
public KodiXmlFanartBean(String[] thumb) {
super();
this.thumb = thumb;
}
public KodiXmlFanartBean(Thumb[] thumb) {
if (thumb.length == 0) {
this.thumb = new String[0];
} else {
this.thumb = new String[thumb.length];
for (int i = 0; i < thumb.length; i++) {
this.thumb[i] = thumb[i].getThumbURL().toString();
}
}
}
public String[] getThumb() {
return thumb;
}
public void setThumb(String[] thumb) {
this.thumb = thumb;
}
public Thumb[] toFanart() throws IOException {
Thumb[] fanart = new Thumb[thumb.length];
for (int i = 0; i < fanart.length; i++) {
fanart[i] = new Thumb(thumb[i]);
}
return fanart;
}
}
| DoctorD1501/JAVMovieScraper | src/main/java/moviescraper/doctord/controller/xmlserialization/KodiXmlFanartBean.java | Java | gpl-2.0 | 931 |
<?php
/**
* @version $Id$
* @package Koowa_Template
* @copyright Copyright (C) 2007 - 2012 Johan Janssens. All rights reserved.
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Abstract Template class
*
* @author Johan Janssens <johan@nooku.org>
* @package Koowa_Template
*/
abstract class KTemplateAbstract extends KObject implements KTemplateInterface
{
/**
* The template path
*
* @var string
*/
protected $_path;
/**
* The template data
*
* @var array
*/
protected $_data;
/**
* The template contents
*
* @var string
*/
protected $_content;
/**
* The set of template filters for templates
*
* @var array
*/
protected $_filters;
/**
* View object or identifier
*
* @var string|object
*/
protected $_view;
/**
* Counter
*
* Used to track recursive calls during template evaluation
*
* @var int
* @see _evaluate()
*/
private $__counter;
/**
* Constructor
*
* Prevent creating instances of this class by making the constructor private
*
* @param KConfig $config An optional KConfig object with configuration options
*/
public function __construct(KConfig $config)
{
parent::__construct($config);
// Set the view identifier
$this->_view = $config->view;
// Set the template data
$this->_data = $config->data;
// Mixin a command chain
$this->mixin(new KMixinCommandchain($config->append(array('mixer' => $this))));
//Attach the filters
$this->addFilter($config->filters);
//Reset the counter
$this->__counter = 0;
}
/**
* Initializes the options for the object
*
* Called from {@link __construct()} as a first step of object instantiation.
*
* @param KConfig $config An optional KConfig object with configuration options.
* @return void
*/
protected function _initialize(KConfig $config)
{
$config->append(array(
'data' => array(),
'filters' => array(),
'view' => null,
'command_chain' => new KCommandChain(),
'dispatch_events' => false,
'enable_callbacks' => false,
));
parent::_initialize($config);
}
/**
* Get the template path
*
* @return string
*/
public function getPath()
{
return $this->_path;
}
/**
* Get the template data
*
* @return mixed
*/
public function getData()
{
return $this->_data;
}
/**
* Get the template content
*
* @return string
*/
public function getContent()
{
return $this->_content;
}
/**
* Get the view object attached to the template
*
* @throws \UnexpectedValueException If the views doesn't implement the KViewInterface
* @return KViewInterface
*/
public function getView()
{
if(!$this->_view instanceof KViewAbstract)
{
//Make sure we have a view identifier
if(!($this->_view instanceof KServiceIdentifier)) {
$this->setView($this->_view);
}
$this->_view = $this->getService($this->_view);
//Make sure the view implements KViewAbstract
if(!$this->_view instanceof KViewAbstract)
{
throw new UnexpectedValueException(
'View: '.get_class($this->_view).' does not implement KViewInterface'
);
}
}
return $this->_view;
}
/**
* Method to set a view object attached to the controller
*
* @param mixed $view An object that implements KObjectServiceable, KServiceIdentifier object
* or valid identifier string
* @throws KTemplateException If the identifier is not a view identifier
* @return KTemplateAbstract
*/
public function setView($view)
{
if(!($view instanceof KViewAbstract))
{
if(empty($view) || (is_string($view) && strpos($view, '.') === false))
{
$identifier = clone $this->getIdentifier();
$identifier->path = array('view');
if ($view) {
$identifier->path[] = $view;
}
$identifier->name = KRequest::format() ? KRequest::format() : 'html';
}
else $identifier = $this->getIdentifier($view);
if($identifier->path[0] != 'view') {
throw new KTemplateException('Identifier: '.$identifier.' is not a view identifier');
}
$view = $identifier;
}
$this->_view = $view;
return $this;
}
/**
* Load a template by identifier
*
* This functions only accepts full identifiers of the format
* - com:[//application/]component.view.[.path].name
*
* @param string The template identifier
* @param array An associative array of data to be extracted in local template scope
* @throws \InvalidArgumentException If the template could not be found
* @return KTemplateAbstract
*/
public function loadIdentifier($template, $data = array())
{
//Identify the template
$identifier = $this->getIdentifier($template);
// Find the template
$file = $this->findFile(dirname($identifier->filepath).'/'.$identifier->name.'.php');
if ($file === false) {
throw new InvalidArgumentException('Template "' . $identifier->name . '" not found');
}
// Load the file
$this->loadFile($file, $data);
return $this;
}
/**
* Load a template by path
*
* @param string $file The template path
* @param array $data An associative array of data to be extracted in local template scope
* @return KTemplateAbstract
*/
public function loadFile($path, $data = array())
{
//Store the original path
$this->_path = $path;
//Get the file contents
$contents = file_get_contents($path);
//Load the contents
$this->loadString($contents, $data);
return $this;
}
/**
* Load a template from a string
*
* @param string $string The template contents
* @param array $data An associative array of data to be extracted in local template scope
* @return KTemplateAbstract
*/
public function loadString($string, $data = array())
{
$this->_content = $string;
// Merge the data
$this->_data = array_merge((array) $this->_data, $data);
// Process inline templates
if($this->__counter > 0) {
$this->render();
}
return $this;
}
/**
* Render the template
*
* @return string The rendered data
*/
public function render()
{
//Parse the template
$this->_parse($this->_content);
//Evaluate the template
$this->_evaluate($this->_content);
//Process the template only at the end of the render cycle.
if($this->__counter == 0) {
$this->_process($this->_content);
}
return $this->_content;
}
/**
* Check if the template is in a render cycle
*
* @return boolean Return TRUE if the template is being rendered
*/
public function isRendering()
{
return (bool) $this->_counter;
}
/**
* Check if a filter exists
*
* @param string The name of the filter
* @return boolean TRUE if the filter exists, FALSE otherwise
*/
public function hasFilter($filter)
{
return isset($this->_filters[$filter]);
}
/**
* Adds one or more filters for template transformation
*
* @param array Array of one or more behaviors to add.
* @return KTemplate
*/
public function addFilter($filters)
{
$filters = (array) KConfig::unbox($filters);
foreach($filters as $filter)
{
if(!($filter instanceof KTemplateFilterInterface)) {
$filter = $this->getFilter($filter);
}
//Enqueue the filter in the command chain
$this->getCommandChain()->enqueue($filter);
//Store the filter
$this->_filters[$filter->getIdentifier()->name] = $filter;
}
return $this;
}
/**
* Get a filter by identifier
*
* @return KTemplateFilterInterface
*/
public function getFilter($filter)
{
//Create the complete identifier if a partial identifier was passed
if(is_string($filter) && strpos($filter, '.') === false )
{
$identifier = clone $this->getIdentifier();
$identifier->path = array('template', 'filter');
$identifier->name = $filter;
}
else $identifier = KService::getIdentifier($filter);
if (!isset($this->_filters[$identifier->name]))
{
$filter = KService::get($identifier);
if(!($filter instanceof KTemplateFilterInterface)) {
throw new KTemplateException("Template filter $identifier does not implement KTemplateFilterInterface");
}
}
else $filter = $this->_filters[$identifier->name];
return $filter;
}
/**
* Get a template helper
*
* @param mixed KServiceIdentifierInterface
* @return KTemplateHelperInterface
*/
public function getHelper($helper)
{
//Create the complete identifier if a partial identifier was passed
if(is_string($helper) && strpos($helper, '.') === false )
{
$identifier = clone $this->getIdentifier();
$identifier->path = array('template','helper');
$identifier->name = $helper;
}
else $identifier = $this->getIdentifier($helper);
//Create the template helper
$helper = $this->getService($identifier, array('template' => $this));
//Check the helper interface
if(!($helper instanceof KTemplateHelperInterface)) {
throw new KTemplateHelperException("Template helper $identifier does not implement KTemplateHelperInterface");
}
return $helper;
}
/**
* Load a template helper
*
* This functions accepts a partial identifier, in the form of helper.function. If a partial
* identifier is passed a full identifier will be created using the template identifier.
*
* @param string Name of the helper, dot separated including the helper function to call
* @param mixed Parameters to be passed to the helper
* @return string Helper output
*/
public function renderHelper($identifier, $params = array())
{
//Get the function to call based on the $identifier
$parts = explode('.', $identifier);
$function = array_pop($parts);
$helper = $this->getHelper(implode('.', $parts));
//Call the helper function
if (!is_callable( array( $helper, $function ) )) {
throw new KTemplateHelperException( get_class($helper).'::'.$function.' not supported.' );
}
return $helper->$function($params);
}
/**
* Searches for the file
*
* @param string The file path to look for.
* @return mixed The full path and file name for the target file, or FALSE
* if the file is not found
*/
public function findFile($file)
{
$result = false;
$path = dirname($file);
// is the path based on a stream?
if (strpos($path, '://') === false)
{
// not a stream, so do a realpath() to avoid directory
// traversal attempts on the local file system.
$path = realpath($path); // needed for substr() later
$file = realpath($file);
}
// The substr() check added to make sure that the realpath()
// results in a directory registered so that non-registered directores
// are not accessible via directory traversal attempts.
if (file_exists($file) && substr($file, 0, strlen($path)) == $path) {
$result = $file;
}
// could not find the file in the set of paths
return $result;
}
/**
* Returns a directory path for temporary files
*
* @return string Folder path
*/
protected function _getTemporaryDirectory()
{
return JPATH_ROOT.'/tmp';
}
/**
* Creates a file with a unique file name
*
* @param string|null $directory Uses the result of _getTemporaryDirectory() by default
* @return string File path
*/
protected function _getTemporaryFile($directory = null)
{
if ($directory === null) {
$directory = $this->_getTemporaryDirectory();
}
$name = str_replace('.', '', uniqid('tmpl', true));
$path = $directory.'/'.$name;
touch($path);
return $path;
}
/**
* Parse and compile the template to PHP code
*
* This function passes the template through read filter chain and returns the result.
*
* @return string The parsed data
*/
protected function _parse(&$content)
{
$context = $this->getCommandContext();
$context->data = $content;
$this->getCommandChain()->run(KTemplateFilter::MODE_READ, $context);
$content = $context->data;
}
/**
* Evaluate the template using a simple sandbox
*
* This function writes the template to a temporary file and then includes it.
*
* @return string The evaluated data
* @see tempnam()
*/
protected function _evaluate(&$content)
{
//Increase counter
$this->__counter++;
//Create temporary file
$tempfile = $this->_getTemporaryFile();
//Write the template to the file
$handle = fopen($tempfile, "w+");
fwrite($handle, $content);
fclose($handle);
//Include the file
extract($this->_data, EXTR_SKIP);
ob_start();
include $tempfile;
$content = ob_get_clean();
unlink($tempfile);
//Reduce counter
$this->__counter--;;
}
/**
* Process the template
*
* This function passes the template through write filter chain and returns the result.
*
* @return string The rendered data
*/
protected function _process(&$content)
{
$context = $this->getCommandContext();
$context->data = $content;
$this->getCommandChain()->run(KTemplateFilter::MODE_WRITE, $context);
$content = $context->data;
}
/**
* Returns the template contents
*
* @return string
* @see getContents()
*/
public function __toString()
{
return $this->getContent();
}
}
| dwarkeshsoni/jsn_time_free_j3x | libraries/koowa/template/abstract.php | PHP | gpl-2.0 | 14,969 |
# -*- coding: utf-8 -*-
# Copyright(c) 2016-2020 Jonas Sjöberg <autonameow@jonasjberg.com>
# Source repository: https://github.com/jonasjberg/autonameow
#
# This file is part of autonameow.
#
# autonameow 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.
#
# autonameow 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 autonameow. If not, see <http://www.gnu.org/licenses/>.
import logging
from collections import defaultdict
from core import event
from core import logs
from core.datastore import repository
from core.datastore.query import QueryResponseFailure
from core.exceptions import AutonameowException
from core.model import genericfields
from util import sanity
log = logging.getLogger(__name__)
def _map_generic_sources(meowuri_class_map):
"""
Returns a dict keyed by provider classes storing sets of "generic"
fields as Unicode strings.
"""
klass_generic_meowuris_map = defaultdict(set)
for _, klass in meowuri_class_map.items():
# TODO: [TD0151] Fix inconsistent use of classes/instances.
# TODO: [TD0157] Look into analyzers 'FIELD_LOOKUP' attributes.
for _, field_metainfo in klass.metainfo().items():
generic_field_string = field_metainfo.get('generic_field')
if not generic_field_string:
continue
assert isinstance(generic_field_string, str)
generic_field_klass = genericfields.get_field_for_uri_leaf(generic_field_string)
if not generic_field_klass:
continue
assert issubclass(generic_field_klass, genericfields.GenericField)
generic_meowuri = generic_field_klass.uri()
if not generic_meowuri:
continue
klass_generic_meowuris_map[klass].add(generic_meowuri)
return klass_generic_meowuris_map
def _get_meowuri_source_map():
"""
Returns a dict mapping "MeowURIs" to provider classes.
Example return value: {
'extractor.filesystem.xplat': CrossPlatformFilesystemExtractor,
'extractor.metadata.exiftool': ExiftoolMetadataExtractor,
}
Returns: Dictionary keyed by instances of the 'MeowURI' class,
storing provider classes.
"""
import analyzers
import extractors
mapping = dict()
for module_name in (analyzers, extractors):
module_registry = getattr(module_name, 'registry')
klass_list = module_registry.all_providers
for klass in klass_list:
uri = klass.meowuri_prefix()
assert uri, 'Got empty "meowuri_prefix" from {!s}'.format(klass)
assert uri not in mapping, 'URI "{!s}" already mapped'.format(uri)
mapping[uri] = klass
return mapping
def _get_excluded_sources():
"""
Returns a set of provider classes excluded due to unmet dependencies.
"""
import extractors
import analyzers
all_excluded = set()
for module_name in (analyzers, extractors):
module_registry = getattr(module_name, 'registry')
all_excluded.update(module_registry.excluded_providers)
return all_excluded
class ProviderRegistry(object):
def __init__(self, meowuri_source_map, excluded_providers):
self.log = logging.getLogger(
'{!s}.{!s}'.format(__name__, self.__module__)
)
self.meowuri_sources = dict(meowuri_source_map)
self._debug_log_mapped_meowuri_sources()
self._excluded_providers = excluded_providers
# Set of all MeowURIs "registered" by extractors or analyzers.
self.mapped_meowuris = self.unique_map_meowuris(self.meowuri_sources)
# Providers declaring generic MeowURIs through 'metainfo()'.
self.generic_meowuri_sources = _map_generic_sources(self.meowuri_sources)
self._debug_log_mapped_generic_meowuri_sources()
@property
def excluded_providers(self):
# Sort here so that callers won't have to work around the possibility
# of excluded providers not having a common base class and thus being
# unorderable.
return sorted(self._excluded_providers, key=lambda x: x.__name__)
def _debug_log_mapped_meowuri_sources(self):
if not logs.DEBUG:
return
for uri, klass in sorted(self.meowuri_sources.items()):
self.log.debug('Mapped MeowURI "%s" to %s', uri, klass.name())
def _debug_log_mapped_generic_meowuri_sources(self):
if not logs.DEBUG:
return
for klass, uris in self.generic_meowuri_sources.items():
klass_name = klass.name()
for uri in sorted(uris):
self.log.debug('Mapped generic MeowURI "%s" to %s', uri, klass_name)
def might_be_resolvable(self, uri):
if not uri:
return False
sanity.check_isinstance_meowuri(uri)
resolvable = list(self.mapped_meowuris)
uri_without_leaf = uri.stripleaf()
return any(m.matches_start(uri_without_leaf) for m in resolvable)
def providers_for_meowuri(self, requested_meowuri):
"""
Returns a set of classes that might store data under a given "MeowURI".
Note that the provider "MeowURI" is matched as a substring of the
requested "MeowURI".
Args:
requested_meowuri: The "MeowURI" of interest.
Returns:
A set of classes that "could" produce and store data under a
"MeowURI" that is a substring of the given "MeowURI".
"""
found = set()
if not requested_meowuri:
self.log.error('"providers_for_meowuri()" got empty MeowURI!')
return found
if requested_meowuri.is_generic:
found = self._providers_for_generic_meowuri(requested_meowuri)
else:
found = self._source_providers_for_meowuri(requested_meowuri)
self.log.debug('%s returning %d providers for MeowURI %s',
self.__class__.__name__, len(found), requested_meowuri)
return found
def _providers_for_generic_meowuri(self, requested_meowuri):
found = set()
for klass, meowuris in self.generic_meowuri_sources.items():
if requested_meowuri in meowuris:
found.add(klass)
return found
def _source_providers_for_meowuri(self, requested_meowuri):
# Argument 'requested_meowuri' is a full "source-specific" MeowURI,
# like 'extractor.metadata.exiftool.EXIF:CreateDate'
requested_meowuri_without_leaf = requested_meowuri.stripleaf()
found = set()
for uri in self.meowuri_sources.keys():
# 'uri' is a "MeowURI root" ('extractor.metadata.epub')
if uri.matches_start(requested_meowuri_without_leaf):
found.add(self.meowuri_sources[uri])
return found
@staticmethod
def unique_map_meowuris(meowuri_class_map):
unique_meowuris = set()
for uri in meowuri_class_map.keys():
unique_meowuris.add(uri)
return unique_meowuris
class ProviderRunner(object):
def __init__(self, config, extractor_runner, run_analysis_func):
self.config = config
self._extractor_runner = extractor_runner
assert callable(run_analysis_func), (
'Expected dependency-injected "run_analysis" to be callable'
)
self._run_analysis = run_analysis_func
self._provider_delegation_history = defaultdict(set)
self._delegate_every_possible_meowuri_history = set()
def delegate_to_providers(self, fileobject, uri):
possible_providers = set(Registry.providers_for_meowuri(uri))
if not possible_providers:
log.debug('Got no possible providers for delegation %s', uri)
return
# TODO: [TD0161] Translate from specific to "generic" MeowURI?
# Might be useful to be able to translate a specific MeowURI like
# 'analyzer.ebook.title' to a "generic" like 'generic.metadata.title'.
# Otherwise, user is almost never prompted with any possible candidates.
prepared_analyzers = set()
prepared_extractors = set()
num_possible_providers = len(possible_providers)
for n, provider in enumerate(possible_providers, start=1):
log.debug('Looking at possible provider (%d/%d): %s',
n, num_possible_providers, provider)
if self._previously_delegated_provider(fileobject, provider):
log.debug('Skipping previously delegated provider %s', provider)
continue
self._remember_provider_delegation(fileobject, provider)
if _provider_is_extractor(provider):
prepared_extractors.add(provider)
elif _provider_is_analyzer(provider):
prepared_analyzers.add(provider)
if prepared_extractors:
log.debug('Delegating %s to extractors: %s', uri, prepared_extractors)
self._delegate_to_extractors(fileobject, prepared_extractors)
if prepared_analyzers:
log.debug('Delegating %s to analyzers: %s', uri, prepared_analyzers)
self._delegate_to_analyzers(fileobject, prepared_analyzers)
def _previously_delegated_provider(self, fileobject, provider):
if fileobject in self._delegate_every_possible_meowuri_history:
return True
return bool(
fileobject in self._provider_delegation_history
and provider in self._provider_delegation_history[fileobject]
)
def _remember_provider_delegation(self, fileobject, provider):
self._provider_delegation_history[fileobject].add(provider)
def _delegate_to_extractors(self, fileobject, extractors_to_run):
try:
self._extractor_runner.start(fileobject, extractors_to_run)
except AutonameowException as e:
# TODO: [TD0164] Tidy up throwing/catching of exceptions.
log.critical('Extraction FAILED: %s', e)
raise
def _delegate_to_analyzers(self, fileobject, analyzers_to_run):
self._run_analysis(
fileobject,
self.config,
analyzers_to_run=analyzers_to_run
)
def delegate_every_possible_meowuri(self, fileobject):
self._delegate_every_possible_meowuri_history.add(fileobject)
# Run all extractors
try:
self._extractor_runner.start(fileobject, request_all=True)
except AutonameowException as e:
# TODO: [TD0164] Tidy up throwing/catching of exceptions.
log.critical('Extraction FAILED: %s', e)
raise
# Run all analyzers
self._run_analysis(fileobject, self.config)
def _provider_is_extractor(provider):
# TODO: [hack] Fix circular import problems when running new unit test runner.
# $ PYTHONPATH=autonameow:tests python3 -m unit --skip-slow
from extractors.metadata.base import BaseMetadataExtractor
return issubclass(provider, BaseMetadataExtractor)
def _provider_is_analyzer(provider):
# TODO: [hack] Fix circular import problems when running new unit test runner.
# $ PYTHONPATH=autonameow:tests python3 -m unit --skip-slow
from analyzers import BaseAnalyzer
return issubclass(provider, BaseAnalyzer)
class MasterDataProvider(object):
"""
Handles top-level _DYNAMIC_ data retrieval and data extraction delegation.
This is one of two main means of querying for data related to a file.
Compared to the repository, which is a static storage that either contain
the requested data or not, this is a "reactive" interface to the repository.
If the requested data is in the repository, is it retrieved and returned.
Otherwise, data providers (extractors/analyzers) that might be able
to provide the requested data is executed. If the execution turns up the
requested data, it is returned.
This is intended to be a "dynamic" or "reactive" data retrieval interface
for use by any part of the application.
"""
def __init__(self, config, run_analysis_func):
self.config = config
assert repository.SessionRepository is not None, (
'Expected Repository to be initialized at this point'
)
from core.extraction import ExtractorRunner
extractor_runner = ExtractorRunner(
add_results_callback=repository.SessionRepository.store
)
assert hasattr(extractor_runner, 'start'), (
'Expected "ExtractorRunner" to have an attribute "start"'
)
self.provider_runner = ProviderRunner(
self.config,
extractor_runner,
run_analysis_func
)
def delegate_every_possible_meowuri(self, fileobject):
log.debug('Running all available providers for %r', fileobject)
self.provider_runner.delegate_every_possible_meowuri(fileobject)
def request(self, fileobject, uri):
"""
Highest-level retrieval mechanism for data related to a file.
First the repository is queried with the MeowURI and if the query
returns data, it is returned. If the data is not in the repository,
the task of gathering the data is delegated to the "relevant" providers.
Then the repository is queried again.
If the delegation "succeeded" and the sought after data could be
gathered, it would now be stored in the repository and passed back
as the return value.
None is returned if nothing turns up.
"""
log.debug('Got request %r->[%s]', fileobject, uri)
# First try the repository for previously gathered data
response = self._query_repository(fileobject, uri)
if response:
return response
# Have relevant providers gather the data
self._delegate_to_providers(fileobject, uri)
# Try the repository again
response = self._query_repository(fileobject, uri)
if response:
return response
log.debug('Failed query, then delegation, then another query and returning None')
return QueryResponseFailure(
fileobject=fileobject, uri=uri,
msg='Repository query -> Delegation -> Repository query'
)
def request_one(self, fileobject, uri):
# TODO: [TD0175] Handle requesting exactly one or multiple alternatives.
response = self.request(fileobject, uri)
if isinstance(response, list):
if len(response) == 1:
return response[0]
return QueryResponseFailure(
fileobject=fileobject, uri=uri,
msg='Requested one but response contains {}'.format(len(response))
)
return response
def _delegate_to_providers(self, fileobject, uri):
log.debug('Delegating request to providers: %r->[%s]', fileobject, uri)
self.provider_runner.delegate_to_providers(fileobject, uri)
def _query_repository(self, fileobject, uri):
return repository.SessionRepository.query(fileobject, uri)
_MASTER_DATA_PROVIDER = None
def _initialize_master_data_provider(*_, **kwargs):
active_config = kwargs.get('config')
from core import analysis
run_analysis_func = analysis.run_analysis
# Keep one global 'MasterDataProvider' singleton per 'Autonameow' instance.
global _MASTER_DATA_PROVIDER
_MASTER_DATA_PROVIDER = MasterDataProvider(active_config, run_analysis_func)
def _shutdown_master_data_provider(*_, **__):
# TODO: [TD0202] Handle signals and graceful shutdown properly!
global _MASTER_DATA_PROVIDER
_MASTER_DATA_PROVIDER = None
Registry = None
def _initialize_provider_registry(*_, **__):
# Keep one global 'ProviderRegistry' singleton per 'Autonameow' instance.
global Registry
if not Registry:
Registry = ProviderRegistry(
meowuri_source_map=_get_meowuri_source_map(),
excluded_providers=_get_excluded_sources()
)
def _shutdown_provider_registry(*_, **__):
# TODO: [TD0202] Handle signals and graceful shutdown properly!
global Registry
Registry = None
event.dispatcher.on_config_changed.add(_initialize_master_data_provider)
event.dispatcher.on_startup.add(_initialize_provider_registry)
event.dispatcher.on_shutdown.add(_shutdown_provider_registry)
event.dispatcher.on_shutdown.add(_shutdown_master_data_provider)
def request(fileobject, uri):
sanity.check_isinstance_meowuri(uri)
return _MASTER_DATA_PROVIDER.request(fileobject, uri)
def request_one(fileobject, uri):
sanity.check_isinstance_meowuri(uri)
return _MASTER_DATA_PROVIDER.request_one(fileobject, uri)
def delegate_every_possible_meowuri(fileobject):
_MASTER_DATA_PROVIDER.delegate_every_possible_meowuri(fileobject)
| jonasjberg/autonameow | autonameow/core/master_provider.py | Python | gpl-2.0 | 17,265 |
#include <2geom/sbasis-geometric.h>
#include <2geom/sbasis.h>
#include <2geom/sbasis-math.h>
//#include <2geom/solver.h>
#include <2geom/sbasis-geometric.h>
/** Geometric operators on D2<SBasis> (1D->2D).
* Copyright 2007 JF Barraud
* Copyright 2007 N Hurst
*
* The functions defined in this header related to 2d geometric operations such as arc length,
* unit_vector, curvature, and centroid. Most are built on top of unit_vector, which takes an
* arbitrary D2 and returns a D2 with unit length with the same direction.
*
* Todo/think about:
* arclength D2 -> sbasis (giving arclength function)
* does uniform_speed return natural parameterisation?
* integrate sb2d code from normal-bundle
* angle(md<2>) -> sbasis (gives angle from vector - discontinuous?)
* osculating circle center?
*
**/
//namespace Geom{
using namespace Geom;
using namespace std;
//Some utils first.
//TODO: remove this!!
/**
* Return a list of doubles that appear in both a and b to within error tol
* a, b, vector of double
* tol tolerance
*/
static vector<double>
vect_intersect(vector<double> const &a, vector<double> const &b, double tol=0.){
vector<double> inter;
unsigned i=0,j=0;
while ( i<a.size() && j<b.size() ){
if (fabs(a[i]-b[j])<tol){
inter.push_back(a[i]);
i+=1;
j+=1;
}else if (a[i]<b[j]){
i+=1;
}else if (a[i]>b[j]){
j+=1;
}
}
return inter;
}
//------------------------------------------------------------------------------
static SBasis divide_by_sk(SBasis const &a, int k) {
if ( k>=(int)a.size()){
//make sure a is 0?
return SBasis();
}
if(k < 0) return shift(a,-k);
SBasis c;
c.insert(c.begin(), a.begin()+k, a.end());
return c;
}
static SBasis divide_by_t0k(SBasis const &a, int k) {
if(k < 0) {
SBasis c = Linear(0,1);
for (int i=2; i<=-k; i++){
c*=c;
}
c*=a;
return(c);
}else{
SBasis c = Linear(1,0);
for (int i=2; i<=k; i++){
c*=c;
}
c*=a;
return(divide_by_sk(c,k));
}
}
static SBasis divide_by_t1k(SBasis const &a, int k) {
if(k < 0) {
SBasis c = Linear(1,0);
for (int i=2; i<=-k; i++){
c*=c;
}
c*=a;
return(c);
}else{
SBasis c = Linear(0,1);
for (int i=2; i<=k; i++){
c*=c;
}
c*=a;
return(divide_by_sk(c,k));
}
}
static D2<SBasis> RescaleForNonVanishingEnds(D2<SBasis> const &MM, double ZERO=1.e-4){
D2<SBasis> M = MM;
//TODO: divide by all the s at once!!!
while ((M[0].size()>0||M[1].size()>0) &&
fabs(M[0].at0())<ZERO &&
fabs(M[1].at0())<ZERO &&
fabs(M[0].at1())<ZERO &&
fabs(M[1].at1())<ZERO){
M[0] = divide_by_sk(M[0],1);
M[1] = divide_by_sk(M[1],1);
}
while ((M[0].size()>0||M[1].size()>0) &&
fabs(M[0].at0())<ZERO && fabs(M[1].at0())<ZERO){
M[0] = divide_by_t0k(M[0],1);
M[1] = divide_by_t0k(M[1],1);
}
while ((M[0].size()>0||M[1].size()>0) &&
fabs(M[0].at1())<ZERO && fabs(M[1].at1())<ZERO){
M[0] = divide_by_t1k(M[0],1);
M[1] = divide_by_t1k(M[1],1);
}
return M;
}
/*static D2<SBasis> RescaleForNonVanishing(D2<SBasis> const &MM, double ZERO=1.e-4){
std::vector<double> levels;
levels.push_back(-ZERO);
levels.push_back(ZERO);
//std::vector<std::vector<double> > mr = multi_roots(MM, levels);
}*/
//=================================================================
//TODO: what's this for?!?!
Piecewise<D2<SBasis> >
Geom::cutAtRoots(Piecewise<D2<SBasis> > const &M, double ZERO){
vector<double> rts;
for (unsigned i=0; i<M.size(); i++){
vector<double> seg_rts = roots((M.segs[i])[0]);
seg_rts = vect_intersect(seg_rts, roots((M.segs[i])[1]), ZERO);
Linear mapToDom = Linear(M.cuts[i],M.cuts[i+1]);
for (unsigned r=0; r<seg_rts.size(); r++){
seg_rts[r]= mapToDom(seg_rts[r]);
}
rts.insert(rts.end(),seg_rts.begin(),seg_rts.end());
}
return partition(M,rts);
}
/** Return a function which gives the angle of vect at each point.
\param vect a piecewise parameteric curve.
\param tol the maximum error allowed.
\param order the maximum degree to use for approximation
*/
Piecewise<SBasis>
Geom::atan2(Piecewise<D2<SBasis> > const &vect, double tol, unsigned order){
Piecewise<SBasis> result;
Piecewise<D2<SBasis> > v = cutAtRoots(vect,tol);
result.cuts.push_back(v.cuts.front());
for (unsigned i=0; i<v.size(); i++){
D2<SBasis> vi = RescaleForNonVanishingEnds(v.segs[i]);
SBasis x=vi[0], y=vi[1];
Piecewise<SBasis> angle;
angle = divide (x*derivative(y)-y*derivative(x), x*x+y*y, tol, order);
//TODO: I don't understand this - sign.
angle = integral(-angle);
Point vi0 = vi.at0();
angle += -std::atan2(vi0[1],vi0[0]) - angle[0].at0();
//TODO: deal with 2*pi jumps form one seg to the other...
//TODO: not exact at t=1 because of the integral.
//TODO: force continuity?
angle.setDomain(Interval(v.cuts[i],v.cuts[i+1]));
result.concat(angle);
}
return result;
}
/** Return a function which gives the angle of vect at each point.
\param vect a piecewise parameteric curve.
\param tol the maximum error allowed.
\param order the maximum degree to use for approximation
*/
Piecewise<SBasis>
Geom::atan2(D2<SBasis> const &vect, double tol, unsigned order){
return atan2(Piecewise<D2<SBasis> >(vect),tol,order);
}
/** tan2 is the pseudo-inverse of atan2. It takes an angle and returns a unit_vector that points in the direction of angle.
\param angle a piecewise function of angle wrt t.
\param tol the maximum error allowed.
\param order the maximum degree to use for approximation
*/
D2<Piecewise<SBasis> >
Geom::tan2(SBasis const &angle, double tol, unsigned order){
return tan2(Piecewise<SBasis>(angle), tol, order);
}
/** tan2 is the pseudo-inverse of atan2. It takes an angle and returns a unit_vector that points in the direction of angle.
\param angle a piecewise function of angle wrt t.
\param tol the maximum error allowed.
\param order the maximum degree to use for approximation
*/
D2<Piecewise<SBasis> >
Geom::tan2(Piecewise<SBasis> const &angle, double tol, unsigned order){
return D2<Piecewise<SBasis> >(cos(angle, tol, order), sin(angle, tol, order));
}
/** Return a Piecewise<D2<SBasis> > which points in the same direction as V_in, but has unit_length.
\param V_in the original path.
\param tol the maximum error allowed.
\param order the maximum degree to use for approximation
unitVector(x,y) is computed as (b,-a) where a and b are solutions of:
ax+by=0 (eqn1) and a^2+b^2=1 (eqn2)
*/
Piecewise<D2<SBasis> >
Geom::unitVector(D2<SBasis> const &V_in, double tol, unsigned order){
//TODO: Handle vanishing vectors...
// -This approach is numerically bad. Find a stable way to rescale V_in to have non vanishing ends.
// -This done, unitVector will have jumps at zeros: fill the gaps with arcs of circles.
D2<SBasis> V = RescaleForNonVanishingEnds(V_in);
if (V[0].empty() && V[1].empty())
return Piecewise<D2<SBasis> >(D2<SBasis>(Linear(1),SBasis()));
SBasis x = V[0], y = V[1];
SBasis r_eqn1, r_eqn2;
Point v0 = unit_vector(V.at0());
Point v1 = unit_vector(V.at1());
SBasis a = SBasis(order+1, Linear(0.));
a[0] = Linear(-v0[1],-v1[1]);
SBasis b = SBasis(order+1, Linear(0.));
b[0] = Linear( v0[0], v1[0]);
r_eqn1 = -(a*x+b*y);
r_eqn2 = Linear(1.)-(a*a+b*b);
for (unsigned k=1; k<=order; k++){
double r0 = (k<r_eqn1.size())? r_eqn1.at(k).at0() : 0;
double r1 = (k<r_eqn1.size())? r_eqn1.at(k).at1() : 0;
double rr0 = (k<r_eqn2.size())? r_eqn2.at(k).at0() : 0;
double rr1 = (k<r_eqn2.size())? r_eqn2.at(k).at1() : 0;
double a0,a1,b0,b1;// coeffs in a[k] and b[k]
//the equations to solve at this point are:
// a0*x(0)+b0*y(0)=r0 & 2*a0*a(0)+2*b0*b(0)=rr0
//and
// a1*x(1)+b1*y(1)=r1 & 2*a1*a(1)+2*b1*b(1)=rr1
a0 = r0/dot(v0,V.at0())*v0[0]-rr0/2*v0[1];
b0 = r0/dot(v0,V.at0())*v0[1]+rr0/2*v0[0];
a1 = r1/dot(v1,V.at1())*v1[0]-rr1/2*v1[1];
b1 = r1/dot(v1,V.at1())*v1[1]+rr1/2*v1[0];
a[k] = Linear(a0,a1);
b[k] = Linear(b0,b1);
//TODO: use "incremental" rather than explicit formulas.
r_eqn1 = -(a*x+b*y);
r_eqn2 = Linear(1)-(a*a+b*b);
}
//our candidate is:
D2<SBasis> unitV;
unitV[0] = b;
unitV[1] = -a;
//is it good?
double rel_tol = std::max(1.,std::max(V_in[0].tailError(0),V_in[1].tailError(0)))*tol;
if (r_eqn1.tailError(order)>rel_tol || r_eqn2.tailError(order)>tol){
//if not: subdivide and concat results.
Piecewise<D2<SBasis> > unitV0, unitV1;
unitV0 = unitVector(compose(V,Linear(0,.5)),tol,order);
unitV1 = unitVector(compose(V,Linear(.5,1)),tol,order);
unitV0.setDomain(Interval(0.,.5));
unitV1.setDomain(Interval(.5,1.));
unitV0.concat(unitV1);
return(unitV0);
}else{
//if yes: return it as pw.
Piecewise<D2<SBasis> > result;
result=(Piecewise<D2<SBasis> >)unitV;
return result;
}
}
/** Return a Piecewise<D2<SBasis> > which points in the same direction as V_in, but has unit_length.
\param V_in the original path.
\param tol the maximum error allowed.
\param order the maximum degree to use for approximation
unitVector(x,y) is computed as (b,-a) where a and b are solutions of:
ax+by=0 (eqn1) and a^2+b^2=1 (eqn2)
*/
Piecewise<D2<SBasis> >
Geom::unitVector(Piecewise<D2<SBasis> > const &V, double tol, unsigned order){
Piecewise<D2<SBasis> > result;
Piecewise<D2<SBasis> > VV = cutAtRoots(V);
result.cuts.push_back(VV.cuts.front());
for (unsigned i=0; i<VV.size(); i++){
Piecewise<D2<SBasis> > unit_seg;
unit_seg = unitVector(VV.segs[i],tol, order);
unit_seg.setDomain(Interval(VV.cuts[i],VV.cuts[i+1]));
result.concat(unit_seg);
}
return result;
}
/** returns a function giving the arclength at each point in M.
\param M the Element.
\param tol the maximum error allowed.
*/
Piecewise<SBasis>
Geom::arcLengthSb(Piecewise<D2<SBasis> > const &M, double tol){
Piecewise<D2<SBasis> > dM = derivative(M);
Piecewise<SBasis> dMlength = sqrt(dot(dM,dM),tol,3);
Piecewise<SBasis> length = integral(dMlength);
length-=length.segs.front().at0();
return length;
}
/** returns a function giving the arclength at each point in M.
\param M the Element.
\param tol the maximum error allowed.
*/
Piecewise<SBasis>
Geom::arcLengthSb(D2<SBasis> const &M, double tol){
return arcLengthSb(Piecewise<D2<SBasis> >(M), tol);
}
#if 0
double
Geom::length(D2<SBasis> const &M,
double tol){
Piecewise<SBasis> length = arcLengthSb(M, tol);
return length.segs.back().at1();
}
double
Geom::length(Piecewise<D2<SBasis> > const &M,
double tol){
Piecewise<SBasis> length = arcLengthSb(M, tol);
return length.segs.back().at1();
}
#endif
/** returns a function giving the curvature at each point in M.
\param M the Element.
\param tol the maximum error allowed.
Todo:
* claimed incomplete. Check.
*/
Piecewise<SBasis>
Geom::curvature(D2<SBasis> const &M, double tol) {
D2<SBasis> dM=derivative(M);
Piecewise<SBasis> result;
Piecewise<D2<SBasis> > unitv = unitVector(dM,tol);
Piecewise<SBasis> dMlength = dot(Piecewise<D2<SBasis> >(dM),unitv);
Piecewise<SBasis> k = cross(derivative(unitv),unitv);
k = divide(k,dMlength,tol,3);
return(k);
}
/** returns a function giving the curvature at each point in M.
\param M the Element.
\param tol the maximum error allowed.
Todo:
* claimed incomplete. Check.
*/
Piecewise<SBasis>
Geom::curvature(Piecewise<D2<SBasis> > const &V, double tol){
Piecewise<SBasis> result;
Piecewise<D2<SBasis> > VV = cutAtRoots(V);
result.cuts.push_back(VV.cuts.front());
for (unsigned i=0; i<VV.size(); i++){
Piecewise<SBasis> curv_seg;
curv_seg = curvature(VV.segs[i],tol);
curv_seg.setDomain(Interval(VV.cuts[i],VV.cuts[i+1]));
result.concat(curv_seg);
}
return result;
}
//=================================================================
/** Reparameterise M to have unit speed.
\param M the Element.
\param tol the maximum error allowed.
\param order the maximum degree to use for approximation
*/
Piecewise<D2<SBasis> >
Geom::arc_length_parametrization(D2<SBasis> const &M,
unsigned order,
double tol){
Piecewise<D2<SBasis> > u;
u.push_cut(0);
Piecewise<SBasis> s = arcLengthSb(Piecewise<D2<SBasis> >(M),tol);
for (unsigned i=0; i < s.size();i++){
double t0=s.cuts[i],t1=s.cuts[i+1];
D2<SBasis> sub_M = compose(M,Linear(t0,t1));
D2<SBasis> sub_u;
for (unsigned dim=0;dim<2;dim++){
SBasis sub_s = s.segs[i];
sub_s-=sub_s.at0();
sub_s/=sub_s.at1();
sub_u[dim]=compose_inverse(sub_M[dim],sub_s, order, tol);
}
u.push(sub_u,s(t1));
}
return u;
}
/** Reparameterise M to have unit speed.
\param M the Element.
\param tol the maximum error allowed.
\param order the maximum degree to use for approximation
*/
Piecewise<D2<SBasis> >
Geom::arc_length_parametrization(Piecewise<D2<SBasis> > const &M,
unsigned order,
double tol){
Piecewise<D2<SBasis> > result;
for (unsigned i=0; i<M.size(); i++ ){
Piecewise<D2<SBasis> > uniform_seg=arc_length_parametrization(M[i],order,tol);
result.concat(uniform_seg);
}
return(result);
}
#include <gsl/gsl_integration.h>
static double sb_length_integrating(double t, void* param) {
SBasis* pc = (SBasis*)param;
return sqrt((*pc)(t));
}
/** Calculates the length of a D2<SBasis> through gsl integration.
\param B the Element.
\param tol the maximum error allowed.
\param result variable to be incremented with the length of the path
\param abs_error variable to be incremented with the estimated error
If you only want the length, this routine may be faster/more accurate.
*/
void Geom::length_integrating(D2<SBasis> const &B, double &result, double &abs_error, double tol) {
D2<SBasis> dB = derivative(B);
SBasis dB2 = dot(dB, dB);
gsl_function F;
gsl_integration_workspace * w
= gsl_integration_workspace_alloc (20);
F.function = &sb_length_integrating;
F.params = (void*)&dB2;
double quad_result, err;
/* We could probably use the non adaptive code here if we removed any cusps first. */
gsl_integration_qag (&F, 0, 1, 0, tol, 20,
GSL_INTEG_GAUSS21, w, &quad_result, &err);
abs_error += err;
result += quad_result;
}
/** Calculates the length of a D2<SBasis> through gsl integration.
\param s the Element.
\param tol the maximum error allowed.
If you only want the total length, this routine faster and more accurate than constructing an arcLengthSb.
*/
double
Geom::length(D2<SBasis> const &s,
double tol){
double result = 0;
double abs_error = 0;
length_integrating(s, result, abs_error, tol);
return result;
}
/** Calculates the length of a Piecewise<D2<SBasis> > through gsl integration.
\param s the Element.
\param tol the maximum error allowed.
If you only want the total length, this routine faster and more accurate than constructing an arcLengthSb.
*/
double
Geom::length(Piecewise<D2<SBasis> > const &s,
double tol){
double result = 0;
double abs_error = 0;
for (unsigned i=0; i < s.size();i++){
length_integrating(s[i], result, abs_error, tol);
}
return result;
}
/**
* Centroid using sbasis integration.
\param p the Element.
\param centroid on return contains the centroid of the shape
\param area on return contains the signed area of the shape.
This approach uses green's theorem to compute the area and centroid using integrals. For curved shapes this is much faster than converting to polyline. Note that without an uncross operation the output is not the absolute area.
* Returned values:
0 for normal execution;
2 if area is zero, meaning centroid is meaningless.
*/
unsigned Geom::centroid(Piecewise<D2<SBasis> > const &p, Point& centroid, double &area) {
Point centroid_tmp(0,0);
double atmp = 0;
for(unsigned i = 0; i < p.size(); i++) {
SBasis curl = dot(p[i], rot90(derivative(p[i])));
SBasis A = integral(curl);
D2<SBasis> C = integral(multiply(curl, p[i]));
atmp += A.at1() - A.at0();
centroid_tmp += C.at1()- C.at0(); // first moment.
}
// join ends
centroid_tmp *= 2;
Point final = p[p.size()-1].at1(), initial = p[0].at0();
const double ai = cross(final, initial);
atmp += ai;
centroid_tmp += (final + initial)*ai; // first moment.
area = atmp / 2;
if (atmp != 0) {
centroid = centroid_tmp / (3 * atmp);
return 0;
}
return 2;
}
/**
* Find cubics with prescribed curvatures at both ends.
*
* this requires to solve a system of the form
*
* \f[
* \lambda_1 = a_0 \lambda_0^2 + c_0
* \lambda_0 = a_1 \lambda_1^2 + c_1
* \f]
*
* which is a deg 4 equation in lambda 0.
* Below are basic functions dedicated to solving this assuming a0 and a1 !=0.
*/
static OptInterval
find_bounds_for_lambda0(double aa0,double aa1,double cc0,double cc1,
int insist_on_speeds_signs){
double a0=aa0,a1=aa1,c0=cc0,c1=cc1;
Interval result;
bool flip = a1<0;
if (a1<0){a1=-a1; c1=-c1;}
if (a0<0){a0=-a0; c0=-c0;}
double a = (a0<a1 ? a0 : a1);
double c = (c0<c1 ? c0 : c1);
double delta = 1-4*a*c;
if ( delta < 0 )
return OptInterval();//return empty interval
double lambda_max = (1+std::sqrt(delta))/2/a;
result = Interval(c,lambda_max);
if (flip)
result *= -1;
if (insist_on_speeds_signs == 1){
if (result.max() < 0)//Caution: setMin with max<new min...
return OptInterval();//return empty interval
result.setMin(0);
}
result = Interval(result.min()-.1,result.max()+.1);//just in case all our approx. were exact...
return result;
}
static
std::vector<double>
solve_lambda0(double a0,double a1,double c0,double c1,
int insist_on_speeds_signs){
SBasis p(3, Linear());
p[0] = Linear( a1*c0*c0+c1, a1*a0*(a0+ 2*c0) +a1*c0*c0 +c1 -1 );
p[1] = Linear( -a1*a0*(a0+2*c0), -a1*a0*(3*a0+2*c0) );
p[2] = Linear( a1*a0*a0 );
OptInterval domain = find_bounds_for_lambda0(a0,a1,c0,c1,insist_on_speeds_signs);
if ( !domain )
return std::vector<double>();
p = compose(p,Linear(domain->min(),domain->max()));
std::vector<double>rts = roots(p);
for (unsigned i=0; i<rts.size(); i++){
rts[i] = domain->min() + rts[i] * domain->extent();
}
return rts;
}
/**
* \brief returns the cubics fitting direction and curvature of a given
* input curve at two points.
*
* The input can be the
* value, speed, and acceleration
* or
* value, speed, and cross(acceleration,speed)
* of the original curve at the both ends.
* (the second is often technically usefull, as it avoids unnecessary division by |v|^2)
* Recall that K=1/R=cross(acceleration,speed)/|speed|^3.
*
* Moreover, a 7-th argument 'insist_on_speed_signs' can be supplied to select solutions:
* If insist_on_speed_signs == 1, only consider solutions where speeds at both ends are positively
* proportional to the given ones.
* If insist_on_speed_signs == 0, allow speeds to point in the opposite direction (both at the same time)
* If insist_on_speed_signs == -1, allow speeds to point in both direction independantly.
*/
std::vector<D2<SBasis> >
Geom::cubics_fitting_curvature(Point const &M0, Point const &M1,
Point const &dM0, Point const &dM1,
double d2M0xdM0, double d2M1xdM1,
int insist_on_speed_signs,
double epsilon){
std::vector<D2<SBasis> > result;
//speed of cubic bezier will be lambda0*dM0 and lambda1*dM1,
//with lambda0 and lambda1 s.t. curvature at both ends is the same
//as the curvature of the given curve.
std::vector<double> lambda0,lambda1;
double dM1xdM0=cross(dM1,dM0);
if (fabs(dM1xdM0)<epsilon){
if (fabs(d2M0xdM0)<epsilon || fabs(d2M1xdM1)<epsilon){
return result;
}
double lbda02 = 6.*cross(M1-M0,dM0)/d2M0xdM0;
double lbda12 =-6.*cross(M1-M0,dM1)/d2M1xdM1;
if (lbda02<0 || lbda12<0){
return result;
}
lambda0.push_back(std::sqrt(lbda02) );
lambda1.push_back(std::sqrt(lbda12) );
}else{
//solve: lambda1 = a0 lambda0^2 + c0
// lambda0 = a1 lambda1^2 + c1
double a0,c0,a1,c1;
a0 = -d2M0xdM0/2/dM1xdM0;
c0 = 3*cross(M1-M0,dM0)/dM1xdM0;
a1 = -d2M1xdM1/2/dM1xdM0;
c1 = -3*cross(M1-M0,dM1)/dM1xdM0;
if (fabs(a0)<epsilon){
lambda1.push_back( c0 );
lambda0.push_back( a1*c0*c0 + c1 );
}else if (fabs(a1)<epsilon){
lambda0.push_back( c1 );
lambda1.push_back( a0*c1*c1 + c0 );
}else{
//find lamda0 by solving a deg 4 equation d0+d1*X+...+d4*X^4=0
double a[5];
a[0] = c1+a1*c0*c0;
a[1] = -1;
a[2] = 2*a1*a0*c0;
a[3] = 0;
a[4] = a1*a0*a0;
//vector<double> solns=solve_poly(a,4);
vector<double> solns=solve_lambda0(a0,a1,c0,c1,insist_on_speed_signs);
for (unsigned i=0;i<solns.size();i++){
double lbda0=solns[i];
double lbda1=c0+a0*lbda0*lbda0;
//is this solution pointing in the + direction at both ends?
if (lbda0>=0. && lbda1>=0.){
lambda0.push_back( lbda0);
lambda1.push_back( lbda1);
}
//is this solution pointing in the - direction at both ends?
else if (lbda0<=0. && lbda1<=0. && insist_on_speed_signs<=0){
lambda0.push_back( lbda0);
lambda1.push_back( lbda1);
}
//ok,this solution is pointing in the + and - directions.
else if (insist_on_speed_signs<0){
lambda0.push_back( lbda0);
lambda1.push_back( lbda1);
}
}
}
}
for (unsigned i=0; i<lambda0.size(); i++){
Point V0 = lambda0[i]*dM0;
Point V1 = lambda1[i]*dM1;
D2<SBasis> cubic;
for(unsigned dim=0;dim<2;dim++){
SBasis c(2, Linear());
c[0] = Linear(M0[dim],M1[dim]);
c[1] = Linear( M0[dim]-M1[dim]+V0[dim],
-M0[dim]+M1[dim]-V1[dim]);
cubic[dim] = c;
}
#if 0
Piecewise<SBasis> k = curvature(result);
double dM0_l = dM0.length();
double dM1_l = dM1.length();
g_warning("Target radii: %f, %f", dM0_l*dM0_l*dM0_l/d2M0xdM0,dM1_l*dM1_l*dM1_l/d2M1xdM1);
g_warning("Obtained radii: %f, %f",1/k.valueAt(0),1/k.valueAt(1));
#endif
result.push_back(cubic);
}
return(result);
}
std::vector<D2<SBasis> >
Geom::cubics_fitting_curvature(Point const &M0, Point const &M1,
Point const &dM0, Point const &dM1,
Point const &d2M0, Point const &d2M1,
int insist_on_speed_signs,
double epsilon){
double d2M0xdM0 = cross(d2M0,dM0);
double d2M1xdM1 = cross(d2M1,dM1);
return cubics_fitting_curvature(M0,M1,dM0,dM1,d2M0xdM0,d2M1xdM1,insist_on_speed_signs,epsilon);
}
std::vector<D2<SBasis> >
Geom::cubics_with_prescribed_curvature(Point const &M0, Point const &M1,
Point const &dM0, Point const &dM1,
double k0, double k1,
int insist_on_speed_signs,
double epsilon){
double length;
length = dM0.length();
double d2M0xdM0 = k0*length*length*length;
length = dM1.length();
double d2M1xdM1 = k1*length*length*length;
return cubics_fitting_curvature(M0,M1,dM0,dM1,d2M0xdM0,d2M1xdM1,insist_on_speed_signs,epsilon);
}
/**
* \brief returns all the parameter values of A whose tangent passes through P.
*/
std::vector<double> find_tangents(Point P, D2<SBasis> const &A) {
SBasis crs (cross(A - P, derivative(A)));
crs = shift(crs*Linear(-1, 0)*Linear(-1, 0), -2); // We know that there is a double root at t=0 so we divide out t^2
// JFB points out that this is equivalent to (t-1)^2 followed by a divide by s^2 (shift)
return roots(crs);
}
//}; // namespace
/*
Local Variables:
mode:c++
c-file-style:"stroustrup"
c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
indent-tabs-mode:nil
fill-column:99
End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :
| Huluzai/DoonSketch | inkscape-0.48.5/src/2geom/sbasis-geometric.cpp | C++ | gpl-2.0 | 25,700 |
<?php
/**
* The template for displaying Comments.
*
* The area of the page that contains both current comments
* and the comment form. The actual display of comments is
* handled by a callback to skt_photo_session_comment() which is
* located in the inc/template-tags.php file.
*
* @package SKT Photo Session
*/
/*
* If the current post is protected by a password and
* the visitor has not yet entered the password we will
* return early without loading the comments.
*/
if ( post_password_required() )
return;
?>
<div id="comments" class="comments-area">
<?php // You can start editing here -- including this comment! ?>
<?php if ( have_comments() ) : ?>
<h2 class="comments-title">
<?php
printf( _nx( 'One thought on “%2$s”', '%1$s thoughts on “%2$s”', get_comments_number(), 'comments title', 'skt-photo-session' ),
number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' );
?>
</h2>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-above" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'skt-photo-session' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'skt-photo-session' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'skt-photo-session' ) ); ?></div>
</nav><!-- #comment-nav-above -->
<?php endif; // check for comment navigation ?>
<ol class="comment-list">
<?php
/* Loop through and list the comments. Tell wp_list_comments()
* to use skt_photo_session_comment() to format the comments.
* If you want to override this in a child theme, then you can
* define skt_photo_session_comment() and that will be used instead.
* See skt_photo_session_comment() in inc/template-tags.php for more.
*/
wp_list_comments( array( 'callback' => 'skt_photo_session_comment' ) );
?>
</ol><!-- .comment-list -->
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-below" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'skt-photo-session' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'skt-photo-session' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'skt-photo-session' ) ); ?></div>
</nav><!-- #comment-nav-below -->
<?php endif; // check for comment navigation ?>
<?php endif; // have_comments() ?>
<?php
// If comments are closed and there are comments, let's leave a little note, shall we?
if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) :
?>
<p class="no-comments"><?php _e( 'Comments are closed.', 'skt-photo-session' ); ?></p>
<?php endif; ?>
<?php comment_form(); ?>
</div><!-- #comments -->
| selinaross/JessesWebsite | wp-content/themes/skt-photo-session/comments.php | PHP | gpl-2.0 | 3,137 |
<?php
/**
* Googleapps helper functions
*
* @package Googleapps
* @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2
* @author Jeff Tilson
* @copyright THINK Global School 2010 - 2015
* @link http://www.thinkglobalschool.org/
*
*/
/**
* Get account settings content
*/
function googleapps_get_page_content_settings_account() {
$params['title'] = elgg_echo('googleapps:menu:google_sync_settings');
$user = elgg_get_logged_in_user_entity();
if ($user->google_connected == TRUE) {
$vars = array(
'id' => 'google-auth-settings-form',
'forms' => 'google_auth_settings_form',
);
$params['content'] = elgg_view_form('google/auth/settings', $vars, array('user' => $user));
$params['content'] .= elgg_view_form('google/auth/disconnect', array('class' => 'elgg-form-alt'));
} else {
$params['content'] = elgg_view_form('google/auth/connect');
}
$params['layout'] = 'one_sidebar';
return $params;
}
/**
* Get google docs listing content
*/
function googleapps_get_page_content_docs_list($container_guid = NULL) {
elgg_load_js('elgg.googlefilepicker');
elgg_load_js('google-js-api');
elgg_load_js('google-doc-picker-client');
$params['filter_context'] = $container_guid ? 'mine' : 'all';
if ($container_guid) {
$container = get_entity($container_guid);
// Make sure container is a user or group, otherwise things will look weird
if (!elgg_instanceof($container, 'user') && !elgg_instanceof($container, 'group')) {
// Scram..
forward('googleapps/docs/all');
}
if ($container != elgg_get_logged_in_user_entity() || elgg_instanceof($container, 'group')) {
$params['filter_context'] = FALSE;
}
elgg_push_breadcrumb(elgg_echo('googleapps:googleshareddoc'), elgg_get_site_url() . 'googleapps/docs/all');
elgg_push_breadcrumb($container->name);
$content = elgg_list_entities(array(
'type' => 'object',
'subtype' => 'shared_doc',
'container_guid' => $container_guid,
'full_view' => FALSE
));
$params['title'] = elgg_echo('googleapps:label:user_docs', array($container->name));
} else {
elgg_push_breadcrumb(elgg_echo('googleapps:googleshareddoc'), elgg_get_site_url() . 'googleapps/docs/all');
$content = elgg_list_entities(array(
'type' => 'object',
'subtype' => 'shared_doc',
'full_view' => FALSE
));
$params['title'] = elgg_echo('googleapps:menu:allshareddocs');
}
$owner = elgg_get_page_owner_entity();
if (!$owner) {
$owner = elgg_get_logged_in_user_entity();
}
// Only allow creating google docs if google connected and allowed to write to container
if ($owner && $owner->canWriteToContainer() && elgg_get_logged_in_user_entity()->google_connected) {
$guid = $owner->getGUID();
elgg_register_menu_item('title', array(
'name' => 'googleapps_docs_add',
'href' => "googleapps/docs/add/{$guid}",
'text' => elgg_echo("googleapps/docs:add"),
'link_class' => 'elgg-button elgg-button-action google-doc-picker',
));
}
// If theres no content, display a nice message
if (!$content) {
$content = elgg_view('googleapps/noresults');
}
$params['context'] = 'googleapps/docs';
$params['content'] = $content;
return $params;
}
/**
* Get friends docs
*/
function googleapps_get_page_content_docs_friends($user_guid) {
$user = get_entity($user_guid);
elgg_push_breadcrumb(elgg_echo('googleapps:googleshareddoc'), elgg_get_site_url() . 'googleapps/docs/all');
elgg_push_breadcrumb($user->name, elgg_get_site_url() . 'googleapps/docs/owner/' . $user->username);
elgg_push_breadcrumb(elgg_echo('friends'));
if (!$friends = get_user_friends($user_guid, ELGG_ENTITIES_ANY_VALUE, 0)) {
$content .= elgg_echo('friends:none:you');
} else {
$options = array(
'type' => 'object',
'subtype' => 'shared_doc',
'full_view' => FALSE,
);
foreach ($friends as $friend) {
$options['container_guids'][] = $friend->getGUID();
}
$params['title'] = elgg_echo('googleapps:menu:friendsshareddocs');
$list = elgg_list_entities($options);
if (!$list) {
$content .= elgg_view('googleapps/noresults');
} else {
$content .= $list;
}
}
$params['filter_context'] = 'friends';
$params['context'] = 'googleapps/docs';
$params['content'] = $content;
return $params;
}
/**
* Get google docs share/edit content
*
* @param int $guid Document guid (for editing)
* @return array
*/
function googleapps_get_page_content_docs_share($guid = null) {
$google_doc = get_entity($guid);
elgg_push_breadcrumb(elgg_echo('googleapps:googleshareddoc'), elgg_get_site_url() . 'googleapps/docs/all');
if (elgg_instanceof($google_doc, 'object', 'shared_doc')) {
elgg_push_breadcrumb($google_doc->title);
elgg_push_breadcrumb(elgg_echo('googleapps:docs:edit'));
$body_vars = google_doc_prepare_form_vars($google_doc);
$title = elgg_echo('googleapps:label:editdoc', array($google_doc->title));
} else {
elgg_push_breadcrumb(elgg_echo('googleapps/docs:add'));
$body_vars = array();
$title = elgg_echo('googleapps:label:google_docs');
}
$params = array(
'filter' => '',
);
$params['title'] = $title;
// Form vars
$vars = array();
$vars['id'] = 'google-docs-share-form';
$vars['name'] = 'google_docs_share_form';
// View share form
$params['content'] = elgg_view_form('google/docs/share', $vars, $body_vars);
return $params;
}
/**
* Get google sites/wiki content
*/
function googleapps_get_page_content_wikis_list($container_guid = NULL) {
elgg_push_breadcrumb(elgg_echo('googleapps:menu:wikis'), elgg_get_site_url() . 'googleapps/wikis/all');
$params['context'] = 'googleapps/wikis';
$params['title'] = elgg_echo('googleapps:menu:wikis');
$params['filter_context'] = $container_guid ? 'mine' : 'all';
$db_prefix = elgg_get_config('dbprefix');
$order = sanitize_string(get_input('order', 'ASC'));
$order_by = sanitize_string(get_input('by', 'alpha'));
// Default options (for 'ALL')
$options = array(
'type' => 'object',
'subtype' => 'site',
'full_view' => FALSE,
'limit' => 10,
);
if ($order_by == 'updated') {
$options['order_by_metadata'] = array('name' => 'modified', 'as' => 'int', 'direction' => $order);
$options['reverse_order_by'] = TRUE;
$list = elgg_list_entities_from_metadata($options);
} else {
$options['joins'] = array("JOIN {$db_prefix}objects_entity oe on e.guid = oe.guid");
$options['order_by'] = "oe.title {$order}";
$list = elgg_list_entities($options);
}
$content = elgg_view('googleapps/wiki_sort');
if (!$list) {
$content .= elgg_view('googleapps/noresults');
} else {
$content .= $list;
}
$params['content'] = $content;
$params['sidebar'] = elgg_view('googleapps/featured_site_sidebar');
$domain = elgg_get_plugin_setting('google_api_domain', 'googleapps');
$new_url = 'https://sites.google.com/a/' . $domain . '/sites/system/app/pages/meta/dashboard/create-new-site';
// Show create wiki button
if (elgg_is_logged_in()) {
elgg_register_menu_item('title', array(
'name' => 'add',
'href' => $new_url,
'text' => elgg_echo('googleapps:menu:create_new_wiki'),
'link_class' => 'elgg-button elgg-button-action',
));
}
$params['filter'] = ' ';
return $params;
}
/**
* Pull together google doc variables for the edit form
*
* @param ElggObject $google_doc
* @return array
*/
function google_doc_prepare_form_vars($google_doc = NULL) {
// input names => defaults
$values = array(
'title' => NULL,
'description' => NULL,
'tags' => NULL,
'container_guid' => NULL,
'guid' => NULL,
);
if ($google_doc) {
foreach (array_keys($values) as $field) {
if (isset($google_doc->$field)) {
$values[$field] = $google_doc->$field;
}
}
}
if (elgg_is_sticky_form('google-docs-edit-form')) {
$sticky_values = elgg_get_sticky_values('google-docs-edit-form');
foreach ($sticky_values as $key => $value) {
$values[$key] = $value;
}
}
elgg_clear_sticky_form('google-docs-edit-form');
return $values;
}
/**
* Prepare form vars for google calendars
*
* @param mixed $entity
* @return arary
*/
function google_calendars_prepare_form_vars($calendar = null) {
// input names => defaults
$values = array(
'title' => '',
'google_cal_feed' => '',
'text_color' => '',
'background_color' => '',
'access_id' => ACCESS_DEFAULT,
'guid' => ''
);
if (elgg_is_sticky_form('google-calendar-save')) {
foreach (array_keys($values) as $field) {
$values[$field] = elgg_get_sticky_value('google-calendar-save', $field);
}
}
elgg_clear_sticky_form('google-calendar-save');
if (!$calendar) {
return $values;
}
foreach (array_keys($values) as $field) {
if (isset($calendar->$field)) {
$values[$field] = $calendar->$field;
}
}
$values['entity'] = $calendar;
return $values;
}
/**
* Retrieve and parse allowed subdomains from plugin settings
*
* @return array | bool
*/
function googleapps_get_allowed_subdomains() {
$subdomain_setting = elgg_get_plugin_setting('googleapps_subdomains', 'googleapps');
$subdomains = preg_split('/[\.,\s]/', $subdomain_setting, -1, PREG_SPLIT_NO_EMPTY);
if (empty($subdomains)) {
return FALSE;
} else {
return $subdomains;
}
}
/**
* Generate google client
*
* @return Google_Client
*/
function googleapps_get_client() {
elgg_load_library('gapc:Client'); // Main client
elgg_load_library('gapc:Plus'); // Plus
// Get client id/secret from plugin settings
$client_id = elgg_get_plugin_setting('google_api_client_id', 'googleapps');
$client_secret = elgg_get_plugin_setting('google_api_client_secret', 'googleapps');
$redirect_uri = elgg_get_site_url() . "googleapps/auth/callback";
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes(array(
'email',
'profile',
'https://sites.google.com/feeds/',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/calendar.readonly',
'https://www.googleapis.com/auth/calendar'
));
$client->setAccessType('offline');
$client->setApplicationName(elgg_get_plugin_setting('google_domain_label', 'googleapps'));
return $client;
}
/**
* Generate a google service account client
*/
function googleapps_get_service_client($scopes = array()) {
elgg_load_library('gapc:Client');
$plugin = elgg_get_plugin_from_id('googleapps');
$client = new Google_Client();
$client->setApplicationName(elgg_get_plugin_setting('google_domain_label', 'googleapps'));
// Get auth/key info from plugin settings
$key_location = elgg_get_plugin_setting('google_service_client_key', 'googleapps');
$key_password = elgg_get_plugin_setting('google_service_client_key_password', 'googleapps');
$service_account = elgg_get_plugin_setting('google_service_client_address', 'googleapps');
$impersonate = elgg_get_plugin_setting('google_service_client_key_impersonate', 'googleapps');
$key = file_get_contents($key_location);
// Get credentials
$credentials = new Google_Auth_AssertionCredentials(
$service_account,
$scopes,
$key,
$key_password,
'http://oauth.net/grant_type/jwt/1.0/bearer',
$impersonate
);
$client->setAssertionCredentials($credentials);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($credentials);
}
return $client;
}
/**
* Delete all site entities (debug)
*/
function googleapps_delete_all_site_entities() {
$site_entities = elgg_get_entities(array(
'type' => 'object',
'subtype' => 'site',
'limit' => 0
));
foreach($site_entities as $site_entity) {
$site_entity->delete();
}
return;
}
/**
* Change the google drive file permissions based on chosen elgg permissions
*
* @param object $client
* @param string $doc_id Document id
* @param string $access public | domain
* @param array $optParams optional params to send along with insert
* @return bool
*/
function googleapps_update_file_permissions($client, $doc_id, $access, $optParams = array()) {
if (empty($doc_id) || !$doc_id) {
return FALSE;
}
elgg_load_library('gapc:Drive'); // Load drive lib
$service = new Google_Service_Drive($client);
// May insert multiple permissions
$permissions = array();
// Set new permission based on access requested
if ($access == "domain") {
$permission = new Google_Service_Drive_Permission();
$permission->setRole('reader');
$domain = elgg_get_plugin_setting('google_api_domain', 'googleapps');
$permission->setType('domain');
$permission->setDomain($domain);
$permission->setValue($domain);
$permissions[] = $permission;
} else if ($access == 'public') {
$permission = new Google_Service_Drive_Permission();
$permission->setRole('reader');
$permission->setType('anyone');
$permission->setValue('anyone');
$permissions[] = $permission;
} else if (is_array($access)) {
// Array of ElggUsers
foreach ($access as $user) {
$permission = new Google_Service_Drive_Permission();
$permission->setRole('reader');
$permission->setAdditionalRoles(["commenter"]);
$permission->setType('user');
$permission->setValue($user->email);
$permissions[] = $permission;
}
}
try {
$success = TRUE;
// Handle multiple permissions
foreach ($permissions as $permission) {
$success &= $service->permissions->insert($doc_id, $permission, $optParams);
}
return $success;
} catch (Exception $e) {
//var_dump($e);
return FALSE;
}
}
/**
* Get a single google drive file from supplied ID
*
* @param object $client
* @param string $id
* @return Google_Service_Drive_DriveFile
*/
function googleapps_get_file_from_id($client, $id) {
if (empty($id) || !$id) {
return FALSE;
}
elgg_load_library('gapc:Drive'); // Load drive lib
$service = new Google_Service_Drive($client);
$file = $service->files->get($id);
return $file;
}
/**
* Get permissions for a single google drive file from supplied ID
*
* @param object $client
* @param string $id
* @return array Google_Service_Drive_Permission
*/
function googleapps_get_file_permissions_from_id($client, $id) {
if (empty($id) || !$id) {
return FALSE;
}
elgg_load_library('gapc:Drive'); // Load drive lib
$service = new Google_Service_Drive($client);
$permissions = $service->permissions->listPermissions($id)->getItems();
return $permissions;
}
/**
* Create/save a shared google document
*
* @param Google_Service_Drive_DriveFile $document The google drive document
* @param array $params Elgg object params array:
*
* description => null|string Document description
*
* tags => null|array Document tags
*
* access_id => null|INT Document access level
*
* container_guid => null|INT Container guid for the document
*
* entity_guid => null|INT Supply this to update an existing entity
*
* @return bool
*/
function googleapps_save_shared_document($document, $params = array()) {
// Check for valid drive file
if (!($document instanceof Google_Service_Drive_DriveFile)) {
register_error(elgg_echo('googleapps:error:invaliddoc'));
return FALSE;
}
// Supply some defaults
$defaults = array(
'access_id' => ACCESS_LOGGED_IN,
'container_guid' => elgg_get_logged_in_user_guid(),
'entity_guid' => FALSE
);
$params = array_merge($defaults, $params);
// Check if we were supplied with an entity_guid
if ($params['entity_guid']) {
// Got one, check if it's a valid entity
$shared_doc = get_entity($params['entity_guid']);
if (!elgg_instanceof($shared_doc, 'object', 'shared_doc')) {
register_error(elgg_echo('googleapps:error:invaliddoc'));
return FALSE;
}
} else {
// New object
$shared_doc = new ElggObject();
$shared_doc->subtype = 'shared_doc';
}
// Set document metadata from drive object
$shared_doc->title = $document->getTitle();
$shared_doc->res_id = $document->getId();
$shared_doc->updated = strtotime($document->getModifiedDate()); // CHECK ME
$shared_doc->href = $document->getAlternateLink();
$shared_doc->icon = $document->getIconLink();
$shared_doc->description = $params['description'];
$shared_doc->access_id = $params['access_id'];
$shared_doc->container_guid = $params['container_guid'];
$shared_doc->tags = string_to_tag_array($params['tags']);
if (!$shared_doc->save()) {
register_error(elgg_echo('googleapps:error:share_doc'));
exit;
}
if (!$params['entity_guid']) {
// Add to river
elgg_create_river_item(array(
'view' => 'river/object/shared_doc/create',
'action_type' => 'create',
'subject_guid' => elgg_get_logged_in_user_guid(),
'object_guid' => $shared_doc->guid
));
}
return TRUE;
}
/**
* Return given user's access tokens (default is logged in user)
*
* @param ElggUser $user
* @return string json_encode'd array of user access tokens
*/
function googleapps_get_user_access_tokens($user = FALSE) {
if (!elgg_instanceof($user, 'user')) {
$user = elgg_get_logged_in_user_entity();
}
return json_encode(array(
'access_token' => $user->google_access_token,
'refresh_token' => $user->google_refresh_token
));
}
/**
* Process Google Sites
* - Creates new local entities
* - Deletes local entities not found/deleted remotley
*
* @return array|false
*/
function googleapps_process_sites() {
// Don't do anything if sites are disabled
if (elgg_get_plugin_setting('enable_google_sites', 'googleapps') == 'no') {
return FALSE;
}
set_time_limit(0); // Long timeout, just in case
$log .= "Processing Google Sites\n";
$log .= "-----------------------\n";
// Get service client
$client = googleapps_get_service_client(array(
'https://sites.google.com/feeds/'
));
if ($client) {
$domain = elgg_get_plugin_setting('google_api_domain', 'googleapps');
$base_feed = "https://sites.google.com/feeds/site/{$domain}";
$feed_params = array(
'alt' => 'json',
'include-all-sites' => 'true',
'max-results' => 500,
);
$feed_url = $base_feed . '?' . implode_assoc('=', '&', $feed_params);
$log .= "Request: {$feed_url}\n";
// Get sites feed
$request = new Google_Http_Request($feed_url, 'GET');
$response = $client->getAuth()->authenticatedRequest($request);
$response = json_decode($response->getResponseBody(), TRUE);
if ($response && is_array($response) && count($response) > 0) {
$log .= "\nSuccess..\n\n";
// Get exising elgg site entities
$site_entities = elgg_get_entities(array(
'type' => 'object',
'subtype' => 'site',
'limit' => 0
));
// Elgg site guid, for owner/container guid's
$site_guid = elgg_get_site_entity()->guid;
if (!$site_entities) {
$site_count = 0;
} else {
$site_count = count($site_entities);
}
$log .= "Found {$site_count} local site(s)\n";
// Array to compare local site id's
$local_site_ids = array();
// Array to compate remote site id's
$remote_site_ids = array();
// Build an array of remote site id's
foreach ($response['feed']['entry'] as $site) {
$site_id = $site['id']['$t'];
$remote_site_ids[] = $site_id;
}
// Deleted count
$sites_deleted = 0;
// Process local sites
foreach ($site_entities as $site) {
$log .= "\n[{$site->title}]\n";
$log .= "ID: {$site->site_id}\n";
$log .= "URL: {$site->url}\n";
$local_site_ids[] = $site->site_id;
// Make sure site entity is owned by the elgg site, not a specific user
if ($site->container_guid != $site_guid) {
$site->container_guid = $site_guid;
$site->owner_guid = $site_guid;
$site->save();
$log .= "Updated owner/container guid: {$site_guid}\n";
}
// Remove deleted/unavailable local sites
if (!in_array($site->site_id, $remote_site_ids)) {
$log .= "Site not found remotely, will be deleted.\n";
$site->delete();
$sites_deleted++;
}
}
// Process all remote sites
$log .= "\nFound " . count($response['feed']['entry']) . " remote site(s)\n";
$log .= "\nRemote list:\n------------\n";
// Array to hold new site
$new_sites = array();
// Process new sites
foreach ($response['feed']['entry'] as $site) {
$site_title = $site['title']['$t'];
$site_id = $site['id']['$t'];
$log .= "\n[{$site_title}]\n";
$log .= "ID: {$site_id}\n";
// Locate site URL and ACL feed url
foreach($site['link'] as $link) {
if ($link['rel'] == 'alternate') {
$site_url = $link['href'];
} else if ($link['rel'] == 'http://schemas.google.com/acl/2007#accessControlList') {
$acl_url = $link['href'];
}
}
// Build ACL feed request
$acl_feed_params = array(
'alt' => 'json'
);
$acl_feed_url = $acl_url . '?' . implode_assoc('=', '&', $acl_feed_params);
// Get ACL feed
$request = new Google_Http_Request($acl_feed_url, 'GET');
$response = $client->getAuth()->authenticatedRequest($request);
$response = json_decode($response->getResponseBody(), TRUE);
// Build an array of owner emails
$site_owners = array();
foreach ($response['feed']['entry'] as $entry) {
if ($entry['gAcl$role']['value'] == 'owner' && $entry['gAcl$scope']['type'] == 'user') {
$site_owners[] = $entry['gAcl$scope']['value'];
}
}
// Get activity feed (just replace feed location from the acl feed url)
$activity_url = preg_replace('!(.*)feeds/acl/site/(.*)!', '$1feeds/activity/$2', $acl_feed_url);
// Get activity feed
$request = new Google_Http_Request($activity_url, 'GET');
$response = $client->getAuth()->authenticatedRequest($request);
$response = json_decode($response->getResponseBody(), TRUE);
// See if there is any site activity, if so grab the latest timestamp
$site_updated = FALSE;
foreach ($response['feed']['entry'] as $entry) {
$site_updated = strtotime($entry['updated']['$t']);
break;
}
// If there was no site activity, use the main site feed updated timestamp
if (!$site_updated) {
$site_updated = strtotime($site['updated']['$t']);
}
$log .= "URL: {$site_url}\n";
if (!in_array($site_id, $local_site_ids)) {
$new_sites[$site_title] = $site_id;
// Create new site
$new_site = new ElggObject();
$new_site->owner_guid = $site_guid;
$new_site->container_guid = $site_guid;
$new_site->site_id = $site_id;
$new_site->title = $site_title;
$new_site->subtype = "site";
$new_site->url = $site_url;
$new_site->modified = $site_updated;
$new_site->remote_owners = $site_owners;
$new_site->access_id = ACCESS_LOGGED_IN; // Default access, admin controlled
//$new_site->site_access_id = ACCESS_PRIVATE ; // for site
$new_site->save();
$log .= "New site! ({$new_site->guid})\n";
} else {
$log .= "Local site exists!\n";
// Update local site info
$remote_site = array(
'modified' => $site_updated,
'owners' => $site_owners,
'url' => $site_url,
'title' => $site_title,
'site_id' => $site_id
);
googleapps_update_local_site_info($remote_site);
}
}
// New count
$sites_created = count($new_sites);
$log .= "\n\nCreated {$sites_created} local site(s)\n";
$log .= "Deleted {$sites_deleted} local site(s)\n";
// Get exising elgg site entities again
$site_entities = elgg_get_entities(array(
'type' => 'object',
'subtype' => 'site',
'limit' => 0
));
} else {
$log .= "\n" . $result;
$log .= "\nNo sites found\n";
}
} else {
$log .= "Error creating client!\n";
return FALSE;
}
if (elgg_in_context('googleapps_sites_log')) {
echo "<pre>";
echo $log;
echo "</pre>";
}
return array(
'response_list'=>$response,
'site_entities'=>$site_entities,
'all_site_entities'=>$site_entities // @TODO phase this out
);
}
/**
* Process Google Sites Activity
* - Creates new activity items for sites (group connected)
*
* @return array|false
*/
function googleapps_process_sites_activity() {
// Don't do anything if sites are disabled
if (elgg_get_plugin_setting('enable_google_sites', 'googleapps') == 'no') {
return FALSE;
}
set_time_limit(0); // Long timeout, just in case
$log .= "Processing Google Sites Activity\n";
$log .= "--------------------------------\n";
/** GET LOCAL WIKIS THAT ARE CONNECTED TO A GROUP **/
$options = array(
'type' => 'object',
'subtype' => 'site',
'limit' => 0,
);
$relationship = GOOGLEAPPS_GROUP_WIKI_RELATIONSHIP;
$dbprefix = elgg_get_config('dbprefix');
// Where clause to ignore wikis that already have a relationship with another group
$options['wheres'] = "EXISTS (
SELECT 1 FROM {$dbprefix}entity_relationships r2
WHERE r2.guid_one = e.guid
AND r2.relationship = '{$relationship}')";
// Get a count
$options['count'] = TRUE;
$count = elgg_get_entities($options);
if ($count >= 1) {
$log .= "Found {$count} connected site(s).\n";
// Grab sites as a batch
unset($options['count']);
$sites = new ElggBatch('elgg_get_entities', $options);
// Array to contain site->group relationship
$sites_groups = array();
foreach ($sites as $site) {
$log .= "\n[{$site->title}]\n";
$log .= "ID: {$site->site_id}\n";
$log .= "URL: {$site->url}\n";
// Get the connected group
$options = array(
'type' => 'group',
'limit' => 1, // Should only be connected to one group
'full_view' => FALSE,
'relationship' => GOOGLEAPPS_GROUP_WIKI_RELATIONSHIP,
'relationship_guid' => $site->guid,
'inverse_relationship' => FALSE,
);
$connected_groups = elgg_get_entities_from_relationship($options);
$log .= "GROUP: ";
if (count($connected_groups)) {
// Store site/group
$sites_groups[] = array('site' => $site, 'group' => $connected_groups[0]);
$log .= $connected_groups[0]->name . " (" . $connected_groups[0]->guid . ")\n";
$log .= "Last Activity: {$site->last_activity_time}\n";
} else {
$log .= "Couldn't find group! Not processing!\n";
}
}
// Get service client
$client = googleapps_get_service_client(array(
'https://sites.google.com/feeds/'
));
if ($client) {
$domain = elgg_get_plugin_setting('google_api_domain', 'googleapps');
// Elgg site guid, for owner/container guid's
$site_guid = elgg_get_site_entity()->guid;
// Loop over our connected sites
foreach ($sites_groups as $site_group) {
$site = $site_group['site']; // Site entity
$group = $site_group['group']; // Group entity
// Create feed url
$activity_feed = preg_replace('!(.*)feeds/site/(.*)!', '$1feeds/activity/$2', $site->site_id);
$activity_feed_params = array(
'alt' => 'json',
'max-results' => 500,
);
$activity_feed_url = $activity_feed . '?' . implode_assoc('=', '&', $activity_feed_params);
$log .= "\nProcessing [{$site->title}]...\n\n Request: {$activity_feed_url}\n\n";
// Skip sites that have been set back to private
if ($site->access_id == ACCESS_PRIVATE) {
$log .= " Site's access is PRIVATE, skipping.\n";
continue;
}
// Get activity feed
$request = new Google_Http_Request($activity_feed_url, 'GET');
$response = $client->getAuth()->authenticatedRequest($request);
$response = json_decode($response->getResponseBody(), TRUE);
$last_activity_time = $site->last_activity_time;
$site_new_activity_count = 0;
// Hold each activity items updated timestamp (to store later)
$activity_times = array();
// Title for activity
$title = "Changes on {$site->title} site";
// Loop over activity entries
foreach ($response['feed']['entry'] as $entry) {
$activity_time = strtotime($entry['updated']['$t']);
if ($last_activity_time < $activity_time) {
// Get activity info
$summary = $entry['summary']['$t'];
// Parse out summary link
preg_match_all('~<a\s+.*?</a>~is',$summary,$anchors);
$summary_link = $anchors[0][0];
$author_email = $entry['author'][0]['email']['$t'];
$author_name = $entry['author'][0]['name']['$t'];
// Store activity timestamps
$activity_times[] = $activity_time;
if (empty($author_email)) {
$author_email = NULL;
$author_output = "(unknown)";
} else {
// Try to find elgg user
$users = get_user_by_email($author_email);
if (count($users) >= 1 && elgg_instanceof($users[0], 'user')) {
$local_user = $users[0];
$author_output = $local_user->username;
} else {
$author_output = $author_email;
}
}
// Use the api provided category terms to identify action type
$category_term = $entry['category'][0]['term'];
$category_label = $entry['category'][0]['label'];
$log .= " Found new activity! $author_output $category_label @ $activity_time\n";
// Create new site activity object
$site_activity = new ElggObject();
$site_activity->subtype = 'site_activity';
// If we have a local user for this entry, make them owner
if ($local_user) {
$site_activity->owner_guid = $local_user->guid;
} else { // Site otherwise
$site_activity->owner_guid = $group->guid;
}
// Set container guid & access to that of the group
$site_activity->container_guid = $group->guid;
$site_activity->access_id = $group->group_acl;
// Set other data/metadata
$site_activity->title = $title;
$site_activity->site_name = $site->title;
$site_activity->site_url = $site->url;
$site_activity->author_name = $author_name;
$site_activity->summary = $summary; // Full 'summary' element
$site_activity->summary_link = $summary_link;
// Category term/label
$site_activity->category_term = $category_term;
$site_activity->category_label = $category_label;
$site_activity->updated = $activity_time;
// Save the site activity item
if ($site_activity->save()) {
$log .= " Created new activity entity: {$site_activity->guid}\n\n";
$site_new_activity_count++;
$river_id = elgg_create_river_item(array(
'view' => 'river/object/site_activity/create',
'action_type' => 'create',
'subject_guid' => $site_activity->owner_guid,
'object_guid' => $site_activity->guid,
'posted' => $activity_time
));
if ($river_id) {
$log .= " River entry created!\n\n";
} else {
$log .= " River activity creation failed!!\n\n";
}
} else {
$log .= " Site activity creation failed!!\n\n";
}
}
}
if ($site_new_activity_count) {
$log .= " Created $site_new_activity_count new site_activity object(s)\n";
// Update the site's last activity time
$site->last_activity_time = max($activity_times);
} else {
$log .= " No new activity.\n";
}
}
} else {
$log .= "Error creating client!\n";
}
} else {
$log .= "ABORTING: No connected sites found.\n";
}
if (elgg_in_context('googleapps_sites_log')) {
echo "<pre>";
echo $log;
echo "</pre>";
}
return TRUE;
}
/**
* Reset (delete) all site activity and revert site last updated times
* back to connection time
*/
function googleapps_reset_sites_activity() {
$log = "Reset Site Activity\n------------------\n";
$sites_options = array(
'type' => 'object',
'subtype' => 'site',
'limit' => 0,
);
$sites = elgg_get_entities($sites_options);
$sites_count = count($sites);
foreach ($sites as $site) {
$site->last_activity_time = $site->connected_time;
$site->save();
}
$log .= "\nReset update time for {$sites_count} site(s)\n";
$activity_options = array(
'type' => 'object',
'subtype' => 'site_activity',
'limit' => 0,
'count' => TRUE,
);
$activity_count = elgg_get_entities($activity_options);
unset($activity_options['count']);
$activity_items = elgg_get_entities($activity_options);
foreach ($activity_items as $activity) {
elgg_delete_river(array(
'object_guid' => $activity->guid,
));
$activity->delete();
}
$log .= "\nDeleted {$activity_count} site_activity items(s)\n";
if (elgg_in_context('googleapps_sites_log')) {
echo "<pre>";
echo $log;
echo "</pre>";
}
}
/**
* Helper function to update a local site entities information
*
* @param array $remote_site site info
* @return mixed
*/
function googleapps_update_local_site_info($remote_site) {
// Grab sites
$site = elgg_get_entities_from_metadata(array(
'type' => 'object',
'subtype' => 'site',
'metadata_name' => 'site_id',
'metadata_value' => $remote_site['site_id'],
'limit' => 1,
));
// If we've got a proper site
if (count($site) >= 1 && elgg_instanceof($site[0], 'object', 'site')) {
$site = $site[0];
$site->remote_owners = $remote_site['owners'];
$site->modified = $remote_site['modified'];
$site->url = $remote_site['url'];
$site->title = $remote_site['title'];
$site->save();
}
return FALSE;
}
/**
* Get events from calendar api
*
* @param string $calendar_id Calendar ID
* @param string $class_name Class name for display in fullcalendar
* @param string $start_date Event upper limit
* @param string $end_date Event lower limit
* @return array
*/
function googleapps_get_calendar_events($calendar_id, $class_name = FALSE, $start_date = FALSE, $end_date = FALSE) {
if (!$calendar_id) {
return FALSE;
}
// Get google client and load calendar API
elgg_load_library('gapc:Client');
elgg_load_library('gapc:Calendar');
$client = googleapps_get_service_client(array(
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly'
));
$service = new Google_Service_Calendar($client);
$optParams = array(
'showDeleted' => 0,
'maxResults' => '2500',
'singleEvents' => 1
);
// Attempt to create DateTime objects with given date strings
$start_date = $start_date ? new DateTime($start_date) : FALSE;
$end_date = $end_date ? new DateTime($end_date) : FALSE;
// If we've got dates, format then ISO-8602 (2014-12-07T00:00:00Z)
if ($start_date) {
$optParams['timeMin'] = $start_date->format('c');
}
if ($end_date) {
$optParams['timeMax'] = $end_date->format('c');
}
$events = $service->events->listEvents($calendar_id, $optParams);
$event_array = array();
foreach ($events->getItems() as $item) {
// Determine if this is an all day event
$allDay = FALSE;
if (!$item->getStart()->getDateTime()) {
$allDay = true;
}
// Figure out start date
$start_string = $item->getStart()->getDateTime() ? $item->getStart()->getDateTime() : $item->getStart()->getDate();
// Figure out end date
$end_string = $item->getEnd()->getDateTime() ? $item->getEnd()->getDateTime() : $item->getEnd()->getDate();
// Format dates
$start = new DateTime($start_string);
$end = new DateTime($end_string);
// Add event to event array
$event_array[] = array(
'id' => $item->getId(),
'title' => $item->getSummary(),
'url' => $item->getHtmlLink(),
'start' => $start->format('c'),
'end' => $end->format('c'),
'allDay' => $allDay,
'location' => $item->getLocation(),
'description' => $item->getDescription(),
'className' => $class_name,
'editable' => false,
);
}
return $event_array;
}
/**
* Helper function to map a google site activity 'label' to a
* friendly river verb
*
* @param $label Human readable label from sites api, ie: deletion, move, etc
* @return string
*/
function googleapps_get_river_verb_from_category_label($label) {
$api_labels = array(
'creation' => 'created',
'deletion' => 'deleted',
'edit' => 'edited',
'move' => 'moved',
'recovery' => 'recovered',
);
return $api_labels[$label] ? $api_labels[$label] : 'updated';
}
/**
* Joins key:value pairs by inner_glue and each pair together by outer_glue
* @param string $inner_glue The HTTP method (GET, POST, PUT, DELETE)
* @param string $outer_glue Full URL of the resource to access
* @param array $array Associative array of query parameters
* @return string Urlencoded string of query parameters
*/
function implode_assoc($inner_glue, $outer_glue, $array) {
$output = array();
foreach($array as $key => $item) {
$output[] = $key . $inner_glue . urlencode($item);
}
return implode($outer_glue, $output);
} | THINKGlobalSchool/googleapps | lib/googleapps.php | PHP | gpl-2.0 | 36,538 |
#include "Kernel.h"
#include "Hardware.h"
#include "Process9.h"
#include "Bootloader.h"
#define LOGPM
P9PM::P9PM(Process9* owner) :m_open(), m_owner(owner), handlecount(0x100000001)
{
}
P9PM::~P9PM()
{
}
extern FILE* openapp(u32 titlehigh, u32 titlelow); //this is from Bootloader.cpp
void P9PM::Command(u32 data[],u32 numb)
{
u32 resdata[0x200];
memset(resdata, 0, sizeof(resdata));
u16 cmd = (data[0] >> 16);
switch (cmd)
{
case 1:
{
u64 handle = (data[2] >> 0) | ((u64)(data[1]) << 32);
resdata[0] = 0x00020040;
auto a = m_open.list;
while (a)
{
if (a->data->handle == handle)
break;
a = a->next;
}
if (a)
{
LOG("pm getexheader handle=%" PRIx64 ", titleid=%" PRIx64, handle, a->data->title);
KMemoryMap* map = m_owner->m_kernel->m_IPCFIFOAdresses[(data[3] >> 4) &0xF];
resdata[1] = 0xE0000000;
FILE * fd = openapp(a->data->title >> 32, (u32)a->data->title);
if (fd)
{
//open the container
char ex[0x400];
ctr_ncchheader loader_h;
u32 ncch_off = 0;
// Read header.
if (fread(&loader_h, sizeof(loader_h), 1, fd) != 1) {
XDSERROR("failed to read header.");
break;
}
// Load NCCH
if (memcmp(&loader_h.magic, "NCCH", 4) != 0) {
XDSERROR("invalid magic.. wrong file?");
break;
}
// Read Exheader.
if (fread(&ex, 0x400, 1, fd) != 1) { //this is fixed
XDSERROR("failed to read exheader.");
break;
}
for (int i = 0; i < sizeof(ex); i++)
{
if (map->Write8(data[4] + i, ex[i]) != Success)
{
break;
}
}
resdata[1] = 0;
}
}
else
{
#ifdef LOGPM
LOG("pm getexheader handle=%" PRIx64, handle);
#endif
resdata[1] = 0xE0000000; //todo correct error
}
}
break;
case 2:
{
u64 title = (data[1] >> 0) | ((u64)(data[2]) << 32);
#ifdef LOGPM
LOG("pm register %08x %08x", data[1], data[2]);
#endif
if ((data[3] >> 24) != 0)
LOG("register flags %02x %02x", (data[3] >> 24), (data[3 + 4] >> 24));
if (data[1] != data[1 + 4] && data[2] != data[2 + 4])
LOG("register secound %08x %08x", data[1 + 4], data[2 + 4]);
struct PMOpenprocess * neone = (PMOpenprocess*)malloc(sizeof(struct PMOpenprocess));
neone->handle = handlecount++;
neone->title = title;
m_open.AddItem(neone);
resdata[0] = 0x000200C0;
resdata[1] = 0x0;
resdata[2] = neone->handle >> 32;
resdata[3] = (u32)neone->handle;
}
break;
default:
LOG("unknown PM cmd %08x", data[0]);
break;
}
m_owner->Sendresponds(numb, resdata);
}
u64 P9PM::GetTitle(u64 handle)
{
auto a = m_open.list;
while(a)
{
if(a->data->handle == handle)
break;
a = a->next;
}
if(a)
{
return a->data->title;
}
return -1;
}
| ichfly/XDS | source/process9/pm.cpp | C++ | gpl-2.0 | 3,443 |
#include "VCTAmbientOcclusionRenderPass.h"
#include "Debug/Statistics/StatisticsManager.h"
#include "VCTStatisticsObject.h"
bool VCTAmbientOcclusionRenderPass::IsAvailable (const RenderScene* renderScene, const Camera* camera,
const RenderSettings& settings, const RenderVolumeCollection* rvc) const
{
/*
* Always execure reflective shadow mapping indirect light render pass
*/
return settings.vct_ao_enabled;
}
std::string VCTAmbientOcclusionRenderPass::GetPostProcessFragmentShaderPath () const
{
return "Assets/Shaders/VoxelConeTracing/voxelConeTracingAmbientOcclusionFragment.glsl";
}
std::string VCTAmbientOcclusionRenderPass::GetPostProcessVolumeName () const
{
return "VCTAOMap";
}
glm::ivec2 VCTAmbientOcclusionRenderPass::GetPostProcessVolumeResolution (const RenderSettings& settings) const
{
return glm::ivec2 (glm::vec2 (settings.resolution.width, settings.resolution.height) * settings.rsm_scale);
}
FramebufferRenderVolume* VCTAmbientOcclusionRenderPass::CreatePostProcessVolume (const RenderSettings& settings) const
{
/*
* Create ambient occlusion framebuffer
*/
Resource<Texture> texture = Resource<Texture> (new Texture ("ambientOcclusionMap"));
glm::ivec2 size = GetPostProcessVolumeResolution (settings);
texture->SetSize (Size (size.x, size.y));
texture->SetMipmapGeneration (false);
texture->SetSizedInternalFormat (TEXTURE_SIZED_INTERNAL_FORMAT::FORMAT_R8);
texture->SetInternalFormat (TEXTURE_INTERNAL_FORMAT::FORMAT_RED);
texture->SetChannelType (TEXTURE_CHANNEL_TYPE::CHANNEL_UNSIGNED_BYTE);
texture->SetWrapMode (TEXTURE_WRAP_MODE::WRAP_CLAMP_EDGE);
texture->SetMinFilter (TEXTURE_FILTER_MODE::FILTER_NEAREST);
texture->SetMagFilter (TEXTURE_FILTER_MODE::FILTER_NEAREST);
texture->SetAnisotropicFiltering (false);
Resource<Framebuffer> framebuffer = Resource<Framebuffer> (new Framebuffer (texture));
FramebufferRenderVolume* renderVolume = new FramebufferRenderVolume (framebuffer);
/*
* Update statistics object
*/
auto vctStatisticsObject = StatisticsManager::Instance ()->GetStatisticsObject <VCTStatisticsObject> ();
vctStatisticsObject->vctAmbientOcclusionMapVolume = renderVolume;
return renderVolume;
}
std::vector<PipelineAttribute> VCTAmbientOcclusionRenderPass::GetCustomAttributes (const Camera* camera,
const RenderSettings& settings, RenderVolumeCollection* rvc)
{
/*
* Attach post process volume attributes to pipeline
*/
std::vector<PipelineAttribute> attributes = PostProcessRenderPass::GetCustomAttributes (camera, settings, rvc);
/*
* Attach screen space ambient occlusion attributes to pipeline
*/
PipelineAttribute originBias;
PipelineAttribute aoConeRatio;
PipelineAttribute aoConeDistance;
PipelineAttribute temporalFilterEnabled;
originBias.type = PipelineAttribute::AttrType::ATTR_1F;
aoConeRatio.type = PipelineAttribute::AttrType::ATTR_1F;
aoConeDistance.type = PipelineAttribute::AttrType::ATTR_1F;
temporalFilterEnabled.type = PipelineAttribute::AttrType::ATTR_1I;
originBias.name = "originBias";
aoConeRatio.name = "aoConeRatio";
aoConeDistance.name = "aoConeDistance";
temporalFilterEnabled.name = "temporalFilterEnabled";
originBias.value.x = settings.vct_origin_bias;
aoConeRatio.value.x = settings.vct_ao_cone_ratio;
aoConeDistance.value.x = settings.vct_ao_cone_distance;
temporalFilterEnabled.value.x = settings.vct_temporal_filter_enabled;
attributes.push_back (originBias);
attributes.push_back (aoConeRatio);
attributes.push_back (aoConeDistance);
attributes.push_back (temporalFilterEnabled);
return attributes;
}
| maritim/LiteEngine | Engine/RenderPasses/VoxelConeTracing/VCTAmbientOcclusionRenderPass.cpp | C++ | gpl-2.0 | 3,570 |
module AjaxUiHelper
# Unobtrusive version of link_to_remote
def link_to_remote( name, options, html_options={} )
html_options[:class] = "remote #{html_options.delete(:class)}".strip
link_to(name, options, html_options)
end
def jquery_library
return '' if @jquery_library_loaded
@jquery_library_loaded = true
javascript_include_tag( 'jquery/jquery-1.2.6.min.js' ) +
javascript_tag( 'var jQ$ = jQuery.noConflict();' )
end
def prototype_library
return '' if @prototype_library_loaded
@prototype_library_loaded = true
javascript_include_tag 'prototype'
end
def jquery_effects
return '' if @jquery_effects_loaded
@jquery_effects_loaded = true
jquery_library +
javascript_include_tag( 'jquery/ui/minified/effects.core.min.js' ) +
javascript_include_tag( 'jquery/ui/minified/effects.slide.min.js' ) +
javascript_include_tag( 'jquery/ui/minified/effects.drop.min.js' )
end
# load the javascript tabs. redefine the method when you're done so it can't be called again
def load_javascript_tabs
return if @javascript_tabs_loaded
content_for :javascript,
jquery_effects +
javascript_include_tag('tabs')
content_for :javascript_onload, "Crabgrass.Tabs.initialize_tab_blocks();"
@javascript_tabs_loaded = true
end
def load_ajax_form_behaviors
return if @ajax_form_behavior_loaded
content_for :javascript, javascript_include_tag( 'forms' )
content_for :javascript_onload,
'Crabgrass.Forms.initialize_radio_behavior(); Crabgrass.Forms.initialize_remote_actions();'
@ajax_form_behavior_loaded = true
end
def load_ajax_list_behaviors
return if @ajax_list_behavior_loaded
content_for( :javascript, jquery_library +
javascript_tag( <<-SCRIPT
jQ$('ul.list .toolbar .delete.confirm').click( function( ev ) {
return confirm( 'You are about to delete this item. You will not be able to undo this.' );
});
SCRIPT
))
@ajax_list_behavior_loaded = true
end
def load_markitup_library
content_for( :stylesheet,
stylesheet_link_tag( '../javascripts/markitup/skins/greenchange/style-full' ) +
stylesheet_link_tag( '../javascripts/markitup/sets/textile/style' ))
content_for( :javascript,
jquery_library +
javascript_include_tag( 'markitup/jquery.markitup.preview.min.js' ) +
javascript_include_tag( 'markitup/sets/textile/parser' ) +
javascript_include_tag( 'markitup/sets/textile/set' ) )
end
end
| mikeymicrophone/greenchange | app/helpers/ajax_ui_helper.rb | Ruby | gpl-2.0 | 2,523 |
<html> <pre> <?php
print_r($_REQUEST);
if( isset( $_REQUEST['ip'] ) && isset ( $_REQUEST['mac'] ) ) {
$ip = $_REQUEST['ip'];
$mac = $_REQUEST['mac'];
exec("sudo iptables -I internet 1 -t mangle -m mac --mac-source $mac -j RETURN");
exec("sudo rmtrack " . $ip);
echo "User logged in.";
exit;
} else {
echo "Access Denied";
exit;
}
?>
| thgh/pilon | www/process.php | PHP | gpl-2.0 | 363 |
package com.example.shokedbrain.usus;
/**
* Created by shokedbrain on 05.06.17.
*/
public class Room {
private String roomName;
public Room() {
}
public Room(String roomName) {
this.roomName = roomName;
}
public String getRoomName() {
return roomName;
}
public void setRoomName(String roomName) {
this.roomName = roomName;
}
}
| Macleopard/Usus | app/src/main/java/com/example/shokedbrain/usus/Room.java | Java | gpl-2.0 | 395 |
package com.xiner.game.util;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.xiner.game.ball.LotteryBox;
import com.xiner.game.ball.LotteryStage;
import com.xiner.game.ball.LotteryStatistic;
import com.xiner.game.ball.LotteryContain;
import com.xiner.game.data.CommonData;
/**
* https://dl-ssl.google.com/android/eclipse/
* @author xiner
*
*/
public class LotteryManager
{
static LotteryManager m_LotteryManager = null;
/**
* key: lottery flag name
* value: lottery content
*/
private Map<String, LotteryContain> m_Lottery = null;
/**
* key: statistic flag name
* value: lottery statistic
*/
private Map<String, LotteryStatistic> m_Statistic = null;
private String m_KEY_Lottery;
private String m_KEY_Statistic;
public LotteryManager()
{
m_LotteryManager = this;
m_Lottery = new HashMap<String, LotteryContain>();
m_Statistic = new HashMap<String, LotteryStatistic>();
}
public static void create()
{
if (m_LotteryManager == null)
{
m_LotteryManager = new LotteryManager();
}
}
/**
*
* @return
*/
public static LotteryManager getInstance()
{
if (m_LotteryManager == null)
{
m_LotteryManager = new LotteryManager();
}
return m_LotteryManager;
}
public String getKEY_Lottery()
{
if (m_KEY_Lottery == null || "".equals(m_KEY_Lottery))
{
m_KEY_Lottery = CommonData.KEY_Lottery_AnalysisHTML;
}
return m_KEY_Lottery;
}
public void setKEY_Lottery(String KEY_Lottery)
{
this.m_KEY_Lottery = KEY_Lottery;
}
public String getKEY_Statistic()
{
if (m_KEY_Statistic == null || "".equals(m_KEY_Statistic))
{
m_KEY_Statistic = CommonData.KEY_Statistic_TEMP;
}
return m_KEY_Statistic;
}
public void setKEY_Statistic(String KEY_Statistic)
{
this.m_KEY_Statistic = KEY_Statistic;
}
/**
* add lottery stage
* @param lotteryKey: lottery flag key
* @param lotteryStage: lottery stage
*/
public void addLotteryStage(String lotteryKey, LotteryStage lotteryStage)
{
LotteryContain lotteryContain = getLotteryContain(lotteryKey);
lotteryContain.addLotteryStage(lotteryStage);
}
/**
* get lotteryContain by lottery flag key
* @param lotteryKey: lottery flag key
* @return
*/
public LotteryContain getLotteryContain(String lotteryKey)
{
LotteryContain lotteryContain = null;
lotteryContain = m_Lottery.get(lotteryKey);
if (lotteryContain == null)
{
lotteryContain = new LotteryContain();
m_Lottery.put(lotteryKey, lotteryContain);
}
return lotteryContain;
}
public LotteryStage getLastLotteryStage(String lotteryKey)
{
LotteryStage lotteryStage = null;
LotteryContain lotteryContain = getLotteryContain(lotteryKey);
if (lotteryContain != null)
{
Map<Integer, LotteryBox> boxmap = lotteryContain.getLotteryContain();
int year = 0;
for (LotteryBox box : boxmap.values())
{
int y = Integer.parseInt(box.getYear());
if (y > year)
{
year = y;
}
}
LotteryBox box = boxmap.get(new Integer(year));
List<Entry<String, LotteryStage>> list = box.getLotteryBoxByOrder();
lotteryStage = list.get(list.size()-1).getValue();
}
return lotteryStage;
}
/**
* source lottery add to traget lottery
* @param skey: source flag key
* @param tKey: traget flag key
*/
public void addSource2Target(String skey, String tKey)
{
LotteryContain sContain = getLotteryContain(skey);
LotteryContain tContain = getLotteryContain(tKey);
tContain.addLotteryContain(sContain);
}
/**
* clear lotterContain by key
* @param key: lotteryContain flag name
*/
public void clearContain(String key)
{
LotteryContain lotteryContain = getLotteryContain(key);
lotteryContain.getLotteryContain().clear();
}
/**
* add lottery statistic
* @param key: statistic flag name
* @param lotteryStatistic: lotteryStatistic
*/
public void putLotteryStatistic(String key, LotteryStatistic lotteryStatistic)
{
LotteryStatistic lStatistic = getLotteryStatistic(key, false);
if (lStatistic != null)
{
m_Statistic.remove(key);
}
m_Statistic.put(key, lotteryStatistic);
}
/**
* get lotteryStatistic
* @param key: statistic flag name
* @param isAdd: ture -if null and add one
* @return: lotteryStatistic
*/
public LotteryStatistic getLotteryStatistic(String key, boolean isAdd)
{
LotteryStatistic lotteryStatistic = null;
lotteryStatistic = m_Statistic.get(key);
if (isAdd && lotteryStatistic == null)
{
lotteryStatistic = new LotteryStatistic();
m_Statistic.put(key, lotteryStatistic);
}
return lotteryStatistic;
}
/**
* clear lotteryStatistic by key
* @param key: lotteryStatistic flag name
*/
public void clearStatistic(String key)
{
LotteryStatistic lotteryStatistic = getLotteryStatistic(key, false);
if (lotteryStatistic != null)
{
lotteryStatistic.clear();
}
}
/**
* lotteryCotain change to lotteryStatistic
* @param lotteryContain: lotteryContain
* @param lotteryStatistic: lotteryStatistic
*/
public void lotteryContain2Statistic(LotteryContain lotteryContain, LotteryStatistic lotteryStatistic)
{
List<Entry<Integer, LotteryBox>> boxList = lotteryContain.getLotteryContainByOrder();
for (Entry<Integer, LotteryBox> entryBox : boxList)
{
LotteryBox lotteryBox = entryBox.getValue();
lotteryBox2Statistic(lotteryBox, lotteryStatistic);
}
}
/**
* lotteryBox change to lotteryStatistic
* @param lotteryBox: lotteryBox
* @param lotteryStatistic: lotteryStatistic
*/
public void lotteryBox2Statistic(LotteryBox lotteryBox, LotteryStatistic lotteryStatistic)
{
List<Entry<String, LotteryStage>> stageList = lotteryBox.getLotteryBoxByOrder();
for (Entry<String, LotteryStage> entryStage : stageList)
{
LotteryStage lotteryStage = entryStage.getValue();
lotteryStage2Statistic(lotteryStage, lotteryStatistic);
}
}
/**
* lotteryStage change to lotteryStatistic
* @param lotteryStage: lotteryStage
* @param lotteryStatistic: lotteryStatistic
*/
public void lotteryStage2Statistic(LotteryStage lotteryStage, LotteryStatistic lotteryStatistic)
{
lotteryStatistic.updateByLotteryStage(lotteryStage);
}
}
| xinerworld/ProbabilityGame | src/com/xiner/game/util/LotteryManager.java | Java | gpl-2.0 | 6,443 |
using System.Collections.Generic;
using System.IO;
using Transformer.Core.Logging;
using Transformer.Core.Model;
namespace Transformer.Core.Template
{
public class TemplateEngine
{
private static readonly ILog Log = LogManager.GetLogger(typeof(VariableResolver));
public VariableResolver VariableResolver { get; set; }
public int TransformDirectory(string path, Environment targetEnvironment, string subEnvironment = null, bool deleteTemplate = true)
{
if (subEnvironment == null)
subEnvironment = string.Empty;
Log.InfoFormat("Transform templates for environment {1} in {0} {2} deleting templates", path, targetEnvironment.Name, deleteTemplate ? "with" : "without");
targetEnvironment.Variables.Add(new Variable() { Name = "subenv", Value = subEnvironment });
VariableResolver = new VariableResolver(targetEnvironment.Variables);
int templateCounter = 0;
foreach (var templateFile in Directory.EnumerateFiles(path, "*.template.*", SearchOption.AllDirectories))
{
++templateCounter;
Log.Info(string.Format(" Transform template {0}", templateFile));
var templateText = File.ReadAllText(templateFile);
var transformed = VariableResolver.TransformVariables(templateText);
ConvertTemplateNameToTargetName(templateFile).OverwriteContent(transformed);
if (deleteTemplate)
{
File.Delete(templateFile);
}
}
Log.InfoFormat("Transformed {0} template(s) in {1}.", templateCounter, path);
return templateCounter;
}
private string ConvertTemplateNameToTargetName(string templateName)
{
return templateName.Replace(".template.", ".").Replace(".Template.", ".");
}
}
public class TransformResult
{
public int TransformedVariables { get; set; }
public List<string> MissingVariables { get; set; }
}
}
| tobiaszuercher/transformer | src/Transformer.Core/Template/TemplateEngine.cs | C# | gpl-2.0 | 2,109 |
/*
* Common DPS routines
* dps.h
* Provides common structure definitions and routines for all applications
*
* Copyright (c) 2005-2006 Chris Cantwell
*
* 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 "dps.h"
#include "Logger.h"
#include <iostream>
#include <sstream>
#include <cstdlib>
using std::endl;
#include <pqxx/pqxx>
track dps_getTrack(std::string md5) {
const char *routine = "dps::dps_getTrack";
DataAccess DB;
track t;
t.isNull = true;
PqxxResult R;
std::string SQL, type;
try {
SQL = "SELECT audiotypes.name AS type "
"FROM audio,audiotypes "
"WHERE audiotypes.id = audio.type "
"AND md5='" + md5 + "'";
type = DB.exec("DpsGetTrack",SQL)[0]["type"].c_str();
}
catch (...) {
L_ERROR(LOG_DB, "Cannot get track " + md5);
return t;
}
if (type == "music") {
try {
SQL = "SELECT audio.md5 AS md5, audio.title AS title, "
"artists.name AS artist, albums.name AS album, "
"archives.name AS archive, audio.music_track AS track, "
"audio.music_released AS released, "
"audio.length_smpl AS length, audio.start_smpl AS start, "
"audio.end_smpl AS end, audio.intro_smpl AS fade_in, "
"audio.extro_smpl AS fade_out, audio.censor AS censor "
"FROM audio, audioartists, artists, albums, archives "
"WHERE audioartists.audio = audio.id "
"AND audioartists.artist = artists.id "
"AND audio.archive = archives.id "
"AND audio.music_album = albums.id "
"AND audio.md5 = '" + md5 + "' "
"ORDER BY audio.md5";
R = DB.exec("DpsGetTrack",SQL);
}
catch (...) {
L_ERROR(LOG_DB, "SQL failed on getTrack.");
L_ERROR(LOG_DB, " -> SQL: " + SQL );
}
if (R.size() > 0) {
t.md5 = R[0]["md5"].c_str();
t.title = R[0]["title"].c_str();
t.artists.push_back(R[0]["artist"].c_str());
t.album = R[0]["album"].c_str();
t.release_date = R[0]["released"].c_str();
t.tracknum = atoi(R[0]["track"].c_str());
if (std::string(R[0]["censor"].c_str()) == "t")
t.censor = true;
else
t.censor = false;
t.length_smpl = atoi(R[0]["length"].c_str());
t.trim_start_smpl = atoi(R[0]["start"].c_str());
t.trim_end_smpl = atoi(R[0]["end"].c_str());
t.fade_in_smpl = atoi(R[0]["fade_in"].c_str());
t.fade_out_smpl = atoi(R[0]["fade_out"].c_str());
t.isNull = false;
}
}
if (type == "jingle") {
try {
SQL = "SELECT audio.md5 AS md5, audio.title AS title, "
"albums.name AS album, "
"archives.name AS archive, audio.music_track AS track, "
"audio.length_smpl AS length, audio.start_smpl AS start, "
"audio.end_smpl AS end, audio.intro_smpl AS fade_in, "
"audio.extro_smpl AS fade_out, audio.censor AS censor "
"FROM audio, archives, albums "
"WHERE audio.archive = archives.id "
"AND audio.music_album = albums.id "
"AND audio.md5 = '" + md5 + "' "
"ORDER BY audio.md5";
R = DB.exec("DpsGetTrack", SQL);
}
catch (...) {
L_ERROR(LOG_DB, "SQL failed on getTrack.");
L_ERROR(LOG_DB, " -> SQL: " + SQL);
}
if (R.size() > 0) {
t.md5 = R[0]["md5"].c_str();
t.title = R[0]["title"].c_str();
t.album = R[0]["album"].c_str();
t.length_smpl = atoi(R[0]["length"].c_str());
t.trim_start_smpl = atoi(R[0]["start"].c_str());
t.trim_end_smpl = atoi(R[0]["end"].c_str());
t.fade_in_smpl = atoi(R[0]["fade_in"].c_str());
t.fade_out_smpl = atoi(R[0]["fade_out"].c_str());
t.isNull = false;
}
}
DB.abort("DpsGetTrack");
return t;
}
std::string dps_itoa(long num) {
std::stringstream S (std::stringstream::in | std::stringstream::out);
S << num;
return S.str();
}
std::string& dps_strTrim(std::string& s) {
std::string::size_type pos = s.find_last_not_of(' ');
if (pos != std::string::npos) {
s.erase(pos + 1);
pos = s.find_first_not_of(' ');
if (pos != std::string::npos) s.erase(0,pos);
}
else {
s.erase(s.begin(), s.end());
}
return s;
}
// TODO: replace users of this function with stdlib version
std::string& dps_strLcase(std::string& s) {
for (unsigned int i = 0; i < s.length(); i++) {
if (s[i] >= 'A' && s[i] <= 'Z') s[i] = s[i] + 32;
}
return s;
}
std::string dps_strPcase(std::string *Str) {
bool upper = true;
bool punctuate = false;
if (Str->length() < 1) return *Str;
for (unsigned int i = 0; i < Str->length() - 1; i++) {
char now = (*Str)[i];
char next = (*Str)[i];
if ((now == '.' || now == ',' || now == '?') && next == ' ') {
punctuate = true;
upper = true;
continue;
}
if ((now == '(' || now == '\'' || now == '\"')
&& (i == 0 || (*Str)[i-1] == ' ')) {
upper = true;
continue;
}
if ((punctuate) && now != ' ') {
Str->insert(i+1,1,' ');
punctuate = false;
continue;
}
if (now == ' ') {
upper = true;
continue;
}
if (upper) {
if (now >= 'a' && now <= 'z')
(*Str)[i] = (*Str)[i] - 32;
upper = false;
}
else {
if (now >= 'A' && now <= 'Z')
(*Str)[i] = (*Str)[i] + 32;
}
}
if ((*Str)[Str->length() - 1] >= 'A' && (*Str)[Str->length() - 1] <= 'Z')
(*Str)[Str->length() - 1] = (*Str)[Str->length() - 1] + 32;
return *Str;
}
std::string dps_strNum(long num, unsigned int digits) {
std::string result = dps_itoa(num);
for (unsigned int i = 1; i < digits; i++) {
if (result.length() < digits) {
result = "0" + result;
}
}
return result;
}
std::string dps_prettyTime(long samples) {
std::string result = "";
int hours = (int)(samples / 158760000);
if (hours > 0) {
result += dps_itoa(hours) + "h ";
}
samples -= hours*158760000;
int mins = (int)(samples / 2646000);
if (mins > 0) {
if (mins < 10) {
result += "0";
}
result += dps_itoa(mins) + "m ";
}
samples -= mins*2646000;
int secs = (int)(samples / 44100);
if (secs < 10) {
result += "0";
}
result += dps_itoa(secs) + ".";
samples -= secs*44100;
int ms = (int)(samples / 441);
if (ms < 10) {
result += "0";
}
result += dps_itoa(ms) + "s";
return result;
}
long dps_current_time() {
return (long)time(NULL);
}
| radiowarwick/digiplay_legacy | src/dps.cpp | C++ | gpl-2.0 | 7,399 |
"""grace
Revision ID: 2bce3f42832
Revises: 100d29f9f7e
Create Date: 2015-08-19 13:48:08.511040
"""
# revision identifiers, used by Alembic.
revision = '2bce3f42832'
down_revision = '100d29f9f7e'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('cs_jiao_yi_ma', sa.Column('xzbz', sa.CHAR(length=12), nullable=False))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('cs_jiao_yi_ma', 'xzbz')
### end Alembic commands ###
| huangtao-sh/grace | grace/alembic/versions/2bce3f42832_grace.py | Python | gpl-2.0 | 649 |
/*
* Copyright (C) 2005-2008 Team XBMC
* http://www.xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "stdafx.h"
#include "RGBRendererV2.h"
#define SURFTOTEX(a) ((a)->Parent ? (a)->Parent : (D3DBaseTexture*)(a))
//#define DBGBOB
CRGBRendererV2::CRGBRendererV2(LPDIRECT3DDEVICE8 pDevice)
: CXBoxRenderer(pDevice)
{
m_444PTextureFull = NULL;
m_444PTextureField = NULL;
m_hInterleavingShader = 0;
m_hInterleavingShaderAlpha = 0;
m_hYUVtoRGBLookup = 0;
m_UVLookup = NULL;
m_UVErrorLookup = NULL;
m_motionpass = 5;
memset(&m_yuvcoef_last, 0, sizeof(YUVCOEF));
memset(&m_yuvrange_last, 0, sizeof(YUVRANGE));
}
void CRGBRendererV2::FlipPage(int source)
{
m_444GeneratedFull = false;
CXBoxRenderer::FlipPage(source);
}
void CRGBRendererV2::Delete444PTexture()
{
CSingleLock lock(g_graphicsContext);
SAFE_RELEASE(m_444PTextureFull)
SAFE_RELEASE(m_444PTextureField)
CLog::Log(LOGDEBUG, "Deleted 444P video textures");
}
void CRGBRendererV2::Clear444PTexture(bool full, bool field)
{
CSingleLock lock(g_graphicsContext);
if(m_444PTextureFull && full)
{
D3DLOCKED_RECT lr;
m_444PTextureFull->LockRect(0, &lr, NULL, 0);
memset(lr.pBits, 0x00, lr.Pitch*m_iSourceHeight);
m_444PTextureFull->UnlockRect(0);
}
if(m_444PTextureField && field)
{
D3DLOCKED_RECT lr;
m_444PTextureField->LockRect(0, &lr, NULL, 0);
#ifdef DBGBOB
memset(lr.pBits, 0xFF, lr.Pitch*m_iSourceHeight>>1);
#else
memset(lr.pBits, 0x00, lr.Pitch*m_iSourceHeight>>1);
#endif
m_444PTextureField->UnlockRect(0);
}
m_444GeneratedFull = false;
}
bool CRGBRendererV2::Create444PTexture(bool full, bool field)
{
CSingleLock lock(g_graphicsContext);
if (!m_444PTextureFull && full)
{
if(D3D_OK != m_pD3DDevice->CreateTexture(m_iSourceWidth, m_iSourceHeight, 1, 0, D3DFMT_LIN_A8R8G8B8, 0, &m_444PTextureFull))
return false;
CLog::Log(LOGINFO, "Created 444P full texture");
}
if (!m_444PTextureField && field)
{
if(D3D_OK != m_pD3DDevice->CreateTexture(m_iSourceWidth, m_iSourceHeight>>1, 1, 0, D3DFMT_LIN_A8R8G8B8, 0, &m_444PTextureField))
return false;
CLog::Log(LOGINFO, "Created 444P field texture");
}
return true;
}
void CRGBRendererV2::ManageTextures()
{
//use 1 buffer in fullscreen mode and 0 buffers in windowed mode
if (!g_graphicsContext.IsFullScreenVideo())
{
if (m_444PTextureFull || m_444PTextureField)
Delete444PTexture();
}
CXBoxRenderer::ManageTextures();
if (g_graphicsContext.IsFullScreenVideo())
{
if (!m_444PTextureFull)
{
Create444PTexture(true, false);
Clear444PTexture(true, false);
}
}
}
bool CRGBRendererV2::Configure(unsigned int width, unsigned int height, unsigned int d_width, unsigned int d_height, float fps, unsigned flags)
{
if(!CXBoxRenderer::Configure(width, height, d_width, d_height, fps, flags))
return false;
// create our lookup textures for yv12->rgb translation,
if(!CreateLookupTextures(m_yuvcoef, m_yuvrange) )
return false;
m_bConfigured = true;
return true;
}
void CRGBRendererV2::Render(DWORD flags)
{
CSingleLock lock(g_graphicsContext);
if ( !g_graphicsContext.IsFullScreenVideo() )
{
RenderLowMem(flags);
}
else
{
int index = m_iYV12RenderBuffer;
if( !(flags & RENDER_FLAG_NOLOCK) )
if( WaitForSingleObject(m_eventTexturesDone[index], 500) == WAIT_TIMEOUT )
CLog::Log(LOGWARNING, __FUNCTION__" - Timeout waiting for texture %d", index);
D3DSurface* p444PSourceFull = NULL;
D3DSurface* p444PSourceField = NULL;
if( flags & (RENDER_FLAG_TOP|RENDER_FLAG_BOT) )
{
if(!m_444PTextureField)
{
Create444PTexture(false, true);
Clear444PTexture(false, true);
}
if(!m_444PTextureField)
{
CLog::Log(LOGERROR, __FUNCTION__" - Couldn't create field texture");
return;
}
m_444PTextureField->GetSurfaceLevel(0, &p444PSourceField);
}
if(!m_444PTextureFull)
{
CLog::Log(LOGERROR, __FUNCTION__" - Couldn't create full texture");
return;
}
m_444PTextureFull->GetSurfaceLevel(0, &p444PSourceFull);
//UV in interlaced video is seen as being closer to first line in first field and closer to second line in second field
//we shift it with an offset of 1/4th pixel (1/8 in UV planes)
//This need only be done when field scaling
#define CHROMAOFFSET_VERT 0.125f
//Each chroma sample is not said to be between the first and second sample as in the vertical case
//first Y(1) <=> UV(1), Y(2) <=> ( UV(1)+UV(2) ) / 2, Y(3) <=> UV(2)
//we wish to offset this by 1/2 pxiel to le left, which in the half rez of UV planes means 1/4th
#define CHROMAOFFSET_HORIZ 0.25f
//Example of how YUV has it's Luma and Chroma data stored
//for progressive video
//L L L L L L L L L L
//C C C C C
//L L L L L L L L L L
//Example of how YUV has Chroma subsampled in interlaced displays
//FIELD 1 FIELD 2
//L L L L L L L L L L
//C C C C C
// L L L L L L L L L L
//
//L L L L L L L L L L
// C C C C C
// L L L L L L L L L L
//
//L L L L L L L L L L
//C C C C C
// L L L L L L L L L L
//
//.........................................
//.........................................
m_pD3DDevice->SetRenderState( D3DRS_SWATHWIDTH, 15 );
m_pD3DDevice->SetRenderState( D3DRS_ZENABLE, FALSE );
m_pD3DDevice->SetRenderState( D3DRS_FOGENABLE, FALSE );
m_pD3DDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );
m_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );
m_pD3DDevice->SetRenderState( D3DRS_YUVENABLE, FALSE );
DWORD alphaenabled;
m_pD3DDevice->GetRenderState( D3DRS_ALPHABLENDENABLE, &alphaenabled );
m_pD3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
m_pD3DDevice->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE );
RECT rsf = { rs.left, rs.top>>1, rs.right, rs.bottom>>1 };
if( !m_444GeneratedFull )
{
m_444GeneratedFull = true;
InterleaveYUVto444P(
m_YUVTexture[index][FIELD_FULL],
NULL, // use motion from last frame as motion value
p444PSourceFull,
rs, rs, rs,
1, 1,
0.0f, 0.0f,
CHROMAOFFSET_HORIZ, 0.0f);
}
#ifdef DBGBOB
m_pD3DDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA);
#endif
if( flags & RENDER_FLAG_TOP )
{
InterleaveYUVto444P(
m_YUVTexture[index][FIELD_TOP],
m_444PTextureFull, // use a downscaled motion value from the full frame,
p444PSourceField,
rsf, rs, rsf,
1, 1,
0.0f, 0.0f,
CHROMAOFFSET_HORIZ, +CHROMAOFFSET_VERT);
}
else if( flags & RENDER_FLAG_BOT )
{
InterleaveYUVto444P(
m_YUVTexture[index][FIELD_BOT],
m_444PTextureFull, // use a downscaled motion value from the full frame,
p444PSourceField,
rsf, rs, rsf,
1, 1,
0.0f, 0.0f,
CHROMAOFFSET_HORIZ, -CHROMAOFFSET_VERT);
}
#ifdef DBGBOB
m_pD3DDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALL);
#endif
//Okey, when the gpu is done with the textures here, they are free to be modified again
if( !(flags & RENDER_FLAG_NOUNLOCK) )
m_pD3DDevice->InsertCallback(D3DCALLBACK_WRITE,&TextureCallback, (DWORD)m_eventTexturesDone[index]);
// Now perform the YUV->RGB conversion in a single pass, and render directly to the screen
m_pD3DDevice->SetScreenSpaceOffset( -0.5f, -0.5f );
if(true)
{
// NOTICE, field motion can have been replaced by downscaled frame motion
// this method uses the difference between fields to estimate motion
// it work sorta, but it can't for example handle horizontal
// hairlines wich only exist in one field, they will flicker
// as they get considered motion
// render the full frame
m_pD3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
RenderYUVtoRGB(m_444PTextureFull, rs, rd, 0.0f, 0.0f);
// render the field texture ontop
if(m_444PTextureField && p444PSourceField)
{
m_pD3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
m_pD3DDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
m_pD3DDevice->SetRenderState(D3DRS_ALPHAREF, m_motionpass);
if(flags & RENDER_FLAG_TOP)
RenderYUVtoRGB(m_444PTextureField, rsf, rd, 0.0f, 0.25);
else
RenderYUVtoRGB(m_444PTextureField, rsf, rd, 0.0f, -0.25);
}
}
else
{
// this method will use the difference between this and previous
// frame as an estimate for motion. this will currently fail
// on the first field that has motion. as then only that line
// has motion. if the alpha channel where first downscaled
// to the field texture lineary we should get away from that
// render the field texture first
if(m_444PTextureField && p444PSourceField)
{
m_pD3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
if(flags & RENDER_FLAG_TOP)
RenderYUVtoRGB(m_444PTextureField, rsf, rd, 0.0f, 0.25);
else
RenderYUVtoRGB(m_444PTextureField, rsf, rd, 0.0f, -0.25);
}
// fill in any place we have no motion with full texture
m_pD3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
m_pD3DDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_LESS);
m_pD3DDevice->SetRenderState(D3DRS_ALPHAREF, m_motionpass);
RenderYUVtoRGB(m_444PTextureFull, rs, rd, 0.0f, 0.0f);
}
m_pD3DDevice->SetScreenSpaceOffset(0.0f, 0.0f);
m_pD3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, alphaenabled );
m_pD3DDevice->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE );
m_pD3DDevice->SetTexture(0, NULL);
m_pD3DDevice->SetTexture(1, NULL);
m_pD3DDevice->SetTexture(2, NULL);
m_pD3DDevice->SetTexture(3, NULL);
m_pD3DDevice->SetPixelShader( NULL );
SAFE_RELEASE(p444PSourceFull);
SAFE_RELEASE(p444PSourceField);
}
CXBoxRenderer::Render(flags);
}
unsigned int CRGBRendererV2::PreInit()
{
CXBoxRenderer::PreInit();
// Create the pixel shader
if (!m_hInterleavingShader)
{
CSingleLock lock(g_graphicsContext);
// shader to interleave separate Y U and V planes into a single YUV output
const char* interleave =
"xps.1.1\n"
"def c0,1,0,0,0\n"
"def c1,0,1,0,0\n"
"def c2,0,0,1,0\n"
"tex t0\n"
"tex t1\n"
"tex t2\n"
"tex t3\n"
// interleave our data
"xmma discard,discard,r0, t0,c0, t1,c1\n"
"mad r0, t2,c2,r0\n"
"sub_x4 r1, r0,t3\n" // calculate the differens in this pixel values
"dp3 r1.rgba, r1,r1\n" // take the absolute of the "yuv" difference vector
// "add_d2 r1.a, r1, t3\n" // average with previouse value to avoid minor changes
"mov r0.a, r1";
const char* interleavealpha =
"xps.1.1\n"
"def c0,1,0,0,0\n"
"def c1,0,1,0,0\n"
"def c2,0,0,1,0\n"
"tex t0\n"
"tex t1\n"
"tex t2\n"
"tex t3\n"
// interleave our data
"xmma discard,discard,r0, t0,c0, t1,c1\n"
"mad r0, t2,c2,r0\n"
// use alpha from t3
"mov r0.a, t3";
// shader for 14bit accurate YUV to RGB (single pass :)
const char* yuv2rgb =
"xps.1.1\n"
"def c0,0.0117647,0.0117647,0.0117647,0\n"
"tex t0\n"
"texreg2ar t1, t0\n"
"texreg2gb t2, t0\n"
"texreg2gb t3, t0\n"
"add r0, t1, t2_bx2\n"
"add r1, t1.a, t3\n"
"mad r0, r1, c0, r0\n"
"mov r0.a, t0";
XGBuffer* pShader;
XGAssembleShader("InterleaveShader", interleave, strlen(interleave), 0, NULL, &pShader, NULL, NULL, NULL, NULL, NULL);
m_pD3DDevice->CreatePixelShader((D3DPIXELSHADERDEF*)pShader->GetBufferPointer(), &m_hInterleavingShader);
pShader->Release();
XGAssembleShader("InterleaveShaderAlpha", interleavealpha, strlen(interleavealpha), 0, NULL, &pShader, NULL, NULL, NULL, NULL, NULL);
m_pD3DDevice->CreatePixelShader((D3DPIXELSHADERDEF*)pShader->GetBufferPointer(), &m_hInterleavingShaderAlpha);
pShader->Release();
XGAssembleShader("YUV2RGBShader", yuv2rgb, strlen(yuv2rgb), 0, NULL, &pShader, NULL, NULL, NULL, NULL, NULL);
m_pD3DDevice->CreatePixelShader((D3DPIXELSHADERDEF*)pShader->GetBufferPointer(), &m_hYUVtoRGBLookup);
pShader->Release();
}
return 0;
}
void CRGBRendererV2::UnInit()
{
CSingleLock lock(g_graphicsContext);
Delete444PTexture();
DeleteLookupTextures();
if (m_hInterleavingShader)
{
m_pD3DDevice->DeletePixelShader(m_hInterleavingShader);
m_hInterleavingShader = 0;
}
if (m_hInterleavingShaderAlpha)
{
m_pD3DDevice->DeletePixelShader(m_hInterleavingShaderAlpha);
m_hInterleavingShaderAlpha = 0;
}
if (m_hYUVtoRGBLookup)
{
m_pD3DDevice->DeletePixelShader(m_hYUVtoRGBLookup);
m_hYUVtoRGBLookup = 0;
}
CXBoxRenderer::UnInit();
}
void CRGBRendererV2::DeleteLookupTextures()
{
if (m_UVLookup)
{
m_UVLookup->Release();
m_UVLookup = NULL;
}
if (m_UVErrorLookup)
{
m_UVErrorLookup->Release();
m_UVErrorLookup = NULL;
}
}
bool CRGBRendererV2::CreateLookupTextures(const YUVCOEF &coef, const YUVRANGE &range)
{
if(memcmp(&m_yuvcoef_last, &coef, sizeof(YUVCOEF)) == 0
&& memcmp(&m_yuvrange_last, &range, sizeof(YUVRANGE)) == 0)
return true;
DeleteLookupTextures();
if (
D3D_OK != m_pD3DDevice->CreateTexture(1 , 256, 1, 0, D3DFMT_A8L8 , 0, &m_YLookup) ||
D3D_OK != m_pD3DDevice->CreateTexture(256, 256, 1, 0, D3DFMT_A8R8G8B8, 0, &m_UVLookup) ||
D3D_OK != m_pD3DDevice->CreateTexture(256, 256, 1, 0, D3DFMT_A8R8G8B8, 0, &m_UVErrorLookup)
)
{
DeleteLookupTextures();
CLog::Log(LOGERROR, "Could not create RGB lookup textures");
return false;
}
// fill in the lookup texture
// create a temporary buffer as we need to swizzle the result
D3DLOCKED_RECT lr;
BYTE *pBuffY = new BYTE[1 * 256 * 2];
BYTE *pBuff = new BYTE[256 * 256 * 4];
BYTE *pErrorBuff = new BYTE[256 * 256 * 4];
if(pBuffY)
{
// first column is our luminance data
for (int y = 0; y < 256; y++)
{
float fY = (y - range.y_min) * 255.0f / (range.y_max - range.y_min);
fY = CLAMP(fY, 0.0f, 255.0f);
float fWhole = floor(fY);
float fFrac = floor((fY - fWhole) * 85.0f + 0.5f); // 0 .. 1.0
pBuffY[2*y] = (BYTE)fWhole;
pBuffY[2*y+1] = (BYTE)fFrac;
}
}
if (pBuff && pErrorBuff)
{
for (int u = 1; u < 256; u++)
{
for (int v = 0; v < 256; v++)
{
// convert to -0.5 .. 0.5 ( -127.5 .. 127.5 )
float fV = (v - range.v_min) * 255.f / (range.v_max - range.v_min) - 127.5f;
float fU = (u - range.u_min) * 255.f / (range.u_max - range.u_min) - 127.5f;
fU = CLAMP(fU, -127.5f, 127.5f);
fV = CLAMP(fV, -127.5f, 127.5f);
// have U and V, calculate R, G and B contributions (lie between 0 and 255)
// -1 is mapped to 0, 1 is mapped to 255
float r = coef.r_up * fU + coef.r_vp * fV;
float g = coef.g_up * fU + coef.g_vp * fV;
float b = coef.b_up * fU + coef.b_vp * fV;
float r_rnd = floor(r * 0.5f - 0.5f) * 2 + 1;
float g_rnd = floor(g * 0.5f - 0.5f) * 2 + 1;
float b_rnd = floor(b * 0.5f - 0.5f) * 2 + 1;
float ps_r = (r_rnd - 1) * 0.5f + 128.0f;
float ps_g = (g_rnd - 1) * 0.5f + 128.0f;
float ps_b = (b_rnd - 1) * 0.5f + 128.0f;
ps_r = CLAMP(ps_r, 0.0f, 255.0f);
ps_g = CLAMP(ps_g, 0.0f, 255.0f);
ps_b = CLAMP(ps_b, 0.0f, 255.0f);
float r_frac = floor((r - r_rnd) * 85.0f + 0.5f);
float b_frac = floor((b - b_rnd) * 85.0f + 0.5f);
float g_frac = floor((g - g_rnd) * 85.0f + 0.5f);
pBuff[4*u + 1024*v + 0] = (BYTE)ps_b;
pBuff[4*u + 1024*v + 1] = (BYTE)ps_g;
pBuff[4*u + 1024*v + 2] = (BYTE)ps_r;
pBuff[4*u + 1024*v + 3] = 0;
pErrorBuff[4*u + 1024*v + 0] = (BYTE)b_frac;
pErrorBuff[4*u + 1024*v + 1] = (BYTE)g_frac;
pErrorBuff[4*u + 1024*v + 2] = (BYTE)r_frac;
pErrorBuff[4*u + 1024*v + 3] = 0;
}
}
m_YLookup->LockRect(0, &lr, NULL, 0);
XGSwizzleRect(pBuffY, 0, NULL, lr.pBits, 1, 256, NULL, 2);
m_YLookup->UnlockRect(0);
m_UVLookup->LockRect(0, &lr, NULL, 0);
XGSwizzleRect(pBuff, 0, NULL, lr.pBits, 256, 256, NULL, 4);
m_UVLookup->UnlockRect(0);
m_UVErrorLookup->LockRect(0, &lr, NULL, 0);
XGSwizzleRect(pErrorBuff, 0, NULL, lr.pBits, 256, 256, NULL, 4);
m_UVErrorLookup->UnlockRect(0);
m_yuvcoef_last = coef;
m_yuvrange_last = range;
}
delete[] pBuff;
delete[] pErrorBuff;
delete[] pBuffY;
return true;
}
void CRGBRendererV2::InterleaveYUVto444P(
YUVPLANES pSources,
LPDIRECT3DTEXTURE8 pAlpha,
LPDIRECT3DSURFACE8 pTarget,
RECT &source, RECT &sourcealpha, RECT &target,
unsigned cshift_x, unsigned cshift_y,
float offset_x, float offset_y,
float coffset_x, float coffset_y)
{
coffset_x += offset_x / (1<<cshift_x);
coffset_y += offset_y / (1<<cshift_y);
for (int i = 0; i < 3; ++i)
{
m_pD3DDevice->SetTexture( i, pSources[i]);
m_pD3DDevice->SetTextureStageState( i, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP );
m_pD3DDevice->SetTextureStageState( i, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP );
m_pD3DDevice->SetTextureStageState( i, D3DTSS_MAGFILTER, D3DTEXF_LINEAR );
m_pD3DDevice->SetTextureStageState( i, D3DTSS_MINFILTER, D3DTEXF_LINEAR );
}
m_pD3DDevice->SetVertexShader( FVF_YV12VERTEX );
if(pAlpha)
{
m_pD3DDevice->SetTexture(3, pAlpha);
m_pD3DDevice->SetPixelShader( m_hInterleavingShaderAlpha );
}
else
{
m_pD3DDevice->SetTexture(3, SURFTOTEX(pTarget));
m_pD3DDevice->SetPixelShader( m_hInterleavingShader );
}
m_pD3DDevice->SetTextureStageState( 3, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP );
m_pD3DDevice->SetTextureStageState( 3, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP );
m_pD3DDevice->SetTextureStageState( 3, D3DTSS_MAGFILTER, D3DTEXF_LINEAR );
m_pD3DDevice->SetTextureStageState( 3, D3DTSS_MINFILTER, D3DTEXF_LINEAR );
LPDIRECT3DSURFACE8 pOldRT = NULL;
if( pTarget )
{
m_pD3DDevice->GetRenderTarget(&pOldRT);
m_pD3DDevice->SetRenderTarget(pTarget, NULL);
}
m_pD3DDevice->SetScreenSpaceOffset(-0.5f, -0.5f);
m_pD3DDevice->Begin(D3DPT_QUADLIST);
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD0, (float)source.left + offset_x, (float)source.top + offset_y);
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD1, (float)(source.left>>cshift_x) + coffset_x, (float)(source.top>>cshift_y) + coffset_y );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD2, (float)(source.left>>cshift_x) + coffset_x, (float)(source.top>>cshift_y) + coffset_y );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD3, (float)sourcealpha.left, (float)sourcealpha.top);
m_pD3DDevice->SetVertexData4f( D3DVSDE_VERTEX, (float)target.left, (float)target.top, 0, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD0, (float)source.right + offset_x, (float)source.top + offset_y);
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD1, (float)(source.right>>cshift_x) + coffset_x, (float)(source.top>>cshift_y) + coffset_y );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD2, (float)(source.right>>cshift_x) + coffset_x, (float)(source.top>>cshift_y) + coffset_y );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD3, (float)sourcealpha.right, (float)sourcealpha.top);
m_pD3DDevice->SetVertexData4f( D3DVSDE_VERTEX, (float)target.right, (float)target.top, 0, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD0, (float)source.right + offset_x, (float)source.bottom + offset_y);
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD1, (float)(source.right>>cshift_x) + coffset_x, (float)(source.bottom>>cshift_y) + coffset_y );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD2, (float)(source.right>>cshift_x) + coffset_x, (float)(source.bottom>>cshift_y) + coffset_y );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD3, (float)sourcealpha.right, (float)sourcealpha.bottom);
m_pD3DDevice->SetVertexData4f( D3DVSDE_VERTEX, (float)target.right, (float)target.bottom, 0, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD0, (float)source.left + offset_x, (float)source.bottom + offset_y);
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD1, (float)(source.left>>cshift_x) + coffset_x, (float)(source.bottom>>cshift_y) + coffset_y );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD2, (float)(source.left>>cshift_x) + coffset_x, (float)(source.bottom>>cshift_y) + coffset_y );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD3, (float)sourcealpha.left, (float)sourcealpha.bottom);
m_pD3DDevice->SetVertexData4f( D3DVSDE_VERTEX, (float)target.left, (float)target.bottom, 0, 1.0f );
m_pD3DDevice->End();
m_pD3DDevice->SetScreenSpaceOffset(0.0f, 0.0f);
m_pD3DDevice->SetTexture(0, NULL);
m_pD3DDevice->SetTexture(1, NULL);
m_pD3DDevice->SetTexture(2, NULL);
m_pD3DDevice->SetTexture(3, NULL);
if( pOldRT )
{
m_pD3DDevice->SetRenderTarget( pOldRT, NULL);
pOldRT->Release();
}
}
void CRGBRendererV2::RenderYUVtoRGB(
D3DBaseTexture* pSource,
RECT &source, RECT &target,
float offset_x, float offset_y)
{
m_pD3DDevice->SetTexture( 0, pSource);
m_pD3DDevice->SetTexture( 1, m_YLookup);
m_pD3DDevice->SetTexture( 2, m_UVLookup);
m_pD3DDevice->SetTexture( 3, m_UVErrorLookup);
for (int i = 0; i < 4; ++i)
{
m_pD3DDevice->SetTextureStageState( i, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP );
m_pD3DDevice->SetTextureStageState( i, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP );
m_pD3DDevice->SetTextureStageState( i, D3DTSS_MAGFILTER, D3DTEXF_LINEAR );
m_pD3DDevice->SetTextureStageState( i, D3DTSS_MINFILTER, D3DTEXF_LINEAR );
}
m_pD3DDevice->SetVertexShader( FVF_YUVRGBVERTEX );
m_pD3DDevice->SetPixelShader( m_hYUVtoRGBLookup );
// render the full frame
m_pD3DDevice->Begin(D3DPT_QUADLIST);
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD1, 0.0f, 0.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD2, 0.0f, 0.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD3, 0.0f, 0.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD1, 1.0f, 0.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD2, 1.0f, 0.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD3, 1.0f, 0.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD1, 1.0f, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD2, 1.0f, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD3, 1.0f, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD1, 0.0f, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD2, 0.0f, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD3, 0.0f, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD0, (float)source.left + offset_x, (float)source.top + offset_y);
m_pD3DDevice->SetVertexData4f( D3DVSDE_VERTEX, (float)target.left, (float)target.top, 0, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD0, (float)source.right + offset_x, (float)source.top + offset_y);
m_pD3DDevice->SetVertexData4f( D3DVSDE_VERTEX, (float)target.right, (float)target.top, 0, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD0, (float)source.right + offset_x, (float)source.bottom + offset_y);
m_pD3DDevice->SetVertexData4f( D3DVSDE_VERTEX, (float)target.right, (float)target.bottom, 0, 1.0f );
m_pD3DDevice->SetVertexData2f( D3DVSDE_TEXCOORD0, (float)source.left + offset_x, (float)source.bottom + offset_y);
m_pD3DDevice->SetVertexData4f( D3DVSDE_VERTEX, (float)target.left, (float)target.bottom, 0, 1.0f );
m_pD3DDevice->End();
}
| xbmc/xbmc-antiquated | xbmc/cores/VideoRenderers/legacy/RGBRendererV2.cpp | C++ | gpl-2.0 | 24,853 |
package com.anju.android.carpoolexpensecalculator;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class FeedReaderDbHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "carpool.db";
private static final int DATABASE_VERSION = 2;
public FeedReaderDbHelper (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(FeedReaderContract.SQL_CREATE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(FeedReaderContract.SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
| anjusuryawanshi/carpool-calculator | src/com/anju/android/carpoolexpensecalculator/FeedReaderDbHelper.java | Java | gpl-2.0 | 1,090 |
<?php
namespace Wizard\Build;
/*
* Main User class
*/
class User {
public function access($access_level) {
// if user isn't logged in, fail access
if (!$this->isLoggedIn()) return false;
// get all accesses of current logged in user
$ret = DB()->query("SELECT al.label
FROM users u
LEFT JOIN access_groups ag
ON ag.uid = u.id
LEFT JOIN access_levels al
ON ag.aid = al.id
WHERE u.id = ? ;
", 'i', $_SESSION["login"]);
// if query fails, fail access
if ($ret == false) return false;
// loop through each access level
foreach ($ret as $access_label) {
// on access level match, give access
if ($access_level == $access_label[0]) return true;
}
// no match found, fail access
return false;
}
// returns count of all users in db
public function counted() {
$ret = DB()->query("SELECT COUNT(id) counted FROM users;");
if ($ret == false) {
return 0;
} else {
return $ret[0]['counted'];
}
}
// returns count of all users activated by email in db
public function counted_active() {
$ret = DB()->query("SELECT COUNT(id) counted FROM users WHERE active='Y';");
if ($ret == false) {
return 0;
} else {
return $ret[0]['counted'];
}
}
// get email of current user
public function getEmail() {
if ($this->isLoggedIn()) {
$ret = DB()->query("SELECT email FROM users WHERE active='Y' AND id=? LIMIT 1;", 's', $_SESSION['login']);
if ($ret != false) {
return $ret[0]['email'];
}
}
return false;
}
// returns true if admin is logged on, false otherwise
public function isAdmin() {
if (isset($_SESSION['login'])) {
$sql = "SELECT id
FROM users
WHERE active = 'Y'
AND admin = 'Y'
AND id = ?
LIMIT 1;";
$data = DB()->query($sql, 's', $_SESSION['login']);
if (($data != false) && ($data[0]['id'] == $_SESSION['login'])) {
return true;
}
}
return false;
}
// return true if a user is logged in, false otherwise
public function isLoggedIn() {
if (isset($_SESSION['login'])) {
return true;
}
return false;
}
// login with email and password, returns true on logon, false otherwise
public function login($email, $password) {
$data = DB()->query("SELECT id, email, passhash
FROM users
WHERE status = 0
AND email = ?
ORDER BY id ASC
LIMIT 1;", 's', $email);
if ($data != false) {
if (($password != '') && (password_verify($password, $data[0]['passhash']) != false)) {
$_SESSION['login'] = $data[0]['id'];
return true;
}
}
//$this->logout();
return false;
}
// Creates a user, first user created is admin
// returns string of error or exact===true for created
public function add($email, $password, $password_confirm) {
// verify if passwords match
if ($password != $password_confirm) {
// passwords mismatch
return 'Passwords mismatch';
}
$counted_users = $this->counted();
// db table doesn't exist
if ($counted_users == 0) {
$sql = "CREATE TABLE `users` (
`id` int(6) UNSIGNED NOT NULL,
`email` varchar(50) COLLATE latin1_general_ci NOT NULL,
`passhash` text COLLATE latin1_general_ci NOT NULL,
`keygen` varchar(32) COLLATE latin1_general_ci NOT NULL,
`active` varchar(1) COLLATE latin1_general_ci NOT NULL,
`admin` varchar(1) COLLATE latin1_general_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;";
$ret = DB()->query($sql);
$sql = "ALTER TABLE `users`
ADD PRIMARY KEY (`id`);";
$ret = DB()->query($sql);
$sql = "ALTER TABLE `users`
MODIFY `id` int(6) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;";
$ret = DB()->query($sql);
}
// verify if email exists
$email_exists = DB()->query("SELECT id, email
FROM users
WHERE email=?
ORDER BY id DESC
LIMIT 1;", 's', $email);
if ($email_exists != false) {
// email already exists
return 'Email already exists';
}
// random string, ommitting confusing values like 0oO, l1i
$rnd = substr(str_shuffle('23456789abcdefghjklmnpqrstuvwxyz'), 0, 8);
$isAdmin = 'N'; // default: not admin
if ($counted_users <= 0) { // when no users in active db
$isAdmin = 'Y'; // first user is admin
}
$sql = "INSERT INTO users (email, passhash, keygen, active, admin)
VALUES (?, ?, ?, 'N', ?);";
$data = DB()->query($sql, 'sssss', $email, password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]), $rnd, $isAdmin);
email($email, 'Account Confirmation', 'Please <a href="http://'.$_SERVER['SERVER_NAME'].'/confirm/admin/'.$rnd.'/'.$email.'">click here</a> to activate your account at '.$_SERVER['SERVER_NAME']);
return true;
}
// confirm email account link to user
public function confirm ($email, $key) {
// verify if user exists
$data = DB()->query("SELECT id, email
FROM users
WHERE active='N'
AND keygen=?
AND email=?
ORDER BY id DESC
LIMIT 1;", 'ss', $key, $email);
if ($data != false) {
// on found user, update to active user (user must still login)
DB()->query("UPDATE users
SET active='Y'
WHERE
keygen=?
AND email=?
ORDER BY id DESC
LIMIT 1;", 'ss', $key, $email);
return true;
}
return false;
}
// remove admin session
public function logout() {
if (isset($_SESSION['login'])) {
unset($_SESSION['login']);
}
return true;
}
}
| LucLaverdure/DreamForgery | core/user/user.php | PHP | gpl-2.0 | 5,680 |
<?php
//clear all div on the page
function ShowGallery()
{$objResponse = new xajaxResponse();
//$objResponse->addAssign("UserAccountDiv","className","hidemsg");//clear useraccount
$objResponse->addAssign("HomeTable","className","hidemsg");//clear home page
$objResponse->addAssign("option","className","slidetext");
$objResponse->addAssign("registerdiv","className","hidemsg");
$objResponse->addAssign("mysearch","className","hidemsg");
$objResponse->addAssign("orderby","className","hidemsg");
return $objResponse->getXML();
}//end of function
function showRegister()
{
$objResponse = new xajaxResponse();
$objResponse->addAssign("HomeTable","className","hidemsg");//clear home page
//$objResponse->addAssign("UserAccountDiv","className","hidemsg");//clear useraccount
$objResponse->addAssign("option","className","hidemsg");
$objResponse->addAssign("formcomments","className","hidemsg");
$objResponse->addAssign("mysearch","className","hidemsg");
$objResponse->addClear("table","innerHTML");
$objResponse->addClear("comments","innerHTML");
$objResponse->addAssign("orderby","className","hidemsg");
return $objResponse->getXML();
}//end of function
function showAlbums()
{
$objResponse = new xajaxResponse();
$objResponse->addAssign("HomeTable","className","hidemsg");//clear home page
//$objResponse->addAssign("UserAccountDiv","className","hidemsg");//clear useraccount
$objResponse->addAssign("registerdiv","className","hidemsg");
$objResponse->addAssign("option","className","hidemsg");
$objResponse->addAssign("formcomments","className","hidemsg");
$objResponse->addAssign("mysearch","className","hidemsg");
$objResponse->addClear("table","innerHTML");
$objResponse->addClear("comments","innerHTML");
return $objResponse->getXML();
}//end of function
function showsearch()
{$objResponse = new xajaxResponse();
$objResponse->addAssign("HomeTable","className","hidemsg");//clear home page
$objResponse->addAssign("option","className","hidemsg");
$objResponse->addAssign("orderby","className","hidemsg");
$objResponse->addAssign("loginform","className","hidemsg");
return $objResponse->getXML();
}
function hideRegisterForm()
{$objResponse = new xajaxResponse();
$objResponse->addAssign("registerdiv","className","hidemsg");
return $objResponse->getXML();
}
function hidehomepage()
{$objResponse = new xajaxResponse();
$objResponse->addAssign("HomeTable","className","hidemsg");//clear home page
return $objResponse->getXML();
}
function showHome()
{
//show div homepage
$objResponse = new xajaxResponse();
$objResponse->addAssign("HomeTable","className","showmsg2");//clear home page
return $objResponse->getXML();
}
function HideImageDetailDiv()
{
//show div homepage
$objResponse = new xajaxResponse();
$objResponse->addAssign("imageDetails","innerHTML","");//clear imagesdetails
$objResponse->addAssign("imagecomments","innerHTML","");//clear imagesdetails
return $objResponse->getXML();
}
function showImageDetailDiv()
{
//show div homepage
$objResponse = new xajaxResponse();
$objResponse->addAssign("imageDetails","className","");//clear imagesdetails
$objResponse->addAssign("imagecomments","className","");//clear imagesdetails
return $objResponse->getXML();
}
?>
<script type="text/javascript">
//keep around the old call function
xajax.realCall = xajax.call;
//override the call function to bend to our wicked ways
xajax.call = function(sFunction, aArgs, sRequestType)
{
//show the spinner
this.$('spinner').style.display = 'inline';
//call the old call function
return this.realCall(sFunction, aArgs, sRequestType);
}
//save the old processResponse function for later
xajax.realProcessResponse = xajax.processResponse;
//override the processResponse function
xajax.processResponse = function(xml)
{
//hide the spinner
//this.$('spinner').style.display = 'none';
//call the real processResponse function
return this.realProcessResponse(xml);
}
</script>
<META NAME="Generator" CONTENT="TextPad 4.6">
<META NAME="Author" CONTENT="?">
<META NAME="Keywords" CONTENT="?">
<META NAME="Description" CONTENT="?">
<script src="history.js">
</script> | avinash/nuzimazz | clear.php | PHP | gpl-2.0 | 4,354 |
<?php
/**
* @copyright Copyright (c) 2014 Orange Applications for Business
* @link http://github.com/kambalabs for the sources repositories
*
* This file is part of Kamba.
*
* Kamba 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.
*
* Kamba 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 Kamba. If not, see <http://www.gnu.org/licenses/>.
*/
namespace KmbPermission\Listener;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZfcRbac\Service\AuthorizationService;
use ZfcRbac\Service\RoleService;
class NavigationRbacListenerFactory implements FactoryInterface
{
/**
* Create service
*
* @param ServiceLocatorInterface $serviceLocator
* @return mixed
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
/** @var AuthorizationService $authorizationService */
$authorizationService = $serviceLocator->get('ZfcRbac\Service\AuthorizationService');
/** @var RoleService $roleService */
$roleService = $serviceLocator->get('ZfcRbac\Service\RoleService');
return new NavigationRbacListener($authorizationService, $roleService);
}
}
| kambalabs/KmbPermission | src/KmbPermission/Listener/NavigationRbacListenerFactory.php | PHP | gpl-2.0 | 1,650 |
package net.sf.jabref.logic.importer.fileformat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import net.sf.jabref.JabRefGUI;
import net.sf.jabref.logic.bibtexkeypattern.BibtexKeyPatternUtil;
import net.sf.jabref.logic.importer.ImportFormatPreferences;
import net.sf.jabref.logic.importer.ParserResult;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.util.FileExtensions;
import net.sf.jabref.logic.util.OS;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.BibtexEntryTypes;
import net.sf.jabref.model.entry.EntryType;
import net.sf.jabref.model.entry.FieldName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This importer parses text format citations using the online API of FreeCite -
* Open Source Citation Parser http://freecite.library.brown.edu/
*/
public class FreeCiteImporter extends ImportFormat {
private static final Log LOGGER = LogFactory.getLog(FreeCiteImporter.class);
private final ImportFormatPreferences importFormatPreferences;
public FreeCiteImporter(ImportFormatPreferences importFormatPreferences) {
this.importFormatPreferences = importFormatPreferences;
}
@Override
public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
Objects.requireNonNull(reader);
// TODO: We don't know how to recognize text files, therefore we return "false"
return false;
}
@Override
public ParserResult importDatabase(BufferedReader reader) throws IOException {
try (Scanner scan = new Scanner(reader)) {
String text = scan.useDelimiter("\\A").next();
return importEntries(text);
}
}
public ParserResult importEntries(String text) {
// URLencode the string for transmission
String urlencodedCitation = null;
try {
urlencodedCitation = URLEncoder.encode(text, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
LOGGER.warn("Unsupported encoding", e);
}
// Send the request
URL url;
URLConnection conn;
try {
url = new URL("http://freecite.library.brown.edu/citations/create");
conn = url.openConnection();
} catch (MalformedURLException e) {
LOGGER.warn("Bad URL", e);
return new ParserResult();
} catch (IOException e) {
LOGGER.warn("Could not download", e);
return new ParserResult();
}
try {
conn.setRequestProperty("accept", "text/xml");
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
String data = "citation=" + urlencodedCitation;
// write parameters
writer.write(data);
writer.flush();
} catch (IllegalStateException e) {
LOGGER.warn("Already connected.", e);
} catch (IOException e) {
LOGGER.warn("Unable to connect to FreeCite online service.", e);
return ParserResult.fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service."));
}
// output is in conn.getInputStream();
// new InputStreamReader(conn.getInputStream())
List<BibEntry> res = new ArrayList<>();
XMLInputFactory factory = XMLInputFactory.newInstance();
try {
XMLStreamReader parser = factory.createXMLStreamReader(conn.getInputStream());
while (parser.hasNext()) {
if ((parser.getEventType() == XMLStreamConstants.START_ELEMENT)
&& "citation".equals(parser.getLocalName())) {
parser.nextTag();
StringBuilder noteSB = new StringBuilder();
BibEntry e = new BibEntry();
// fallback type
EntryType type = BibtexEntryTypes.INPROCEEDINGS;
while (!((parser.getEventType() == XMLStreamConstants.END_ELEMENT)
&& "citation".equals(parser.getLocalName()))) {
if (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
String ln = parser.getLocalName();
if ("authors".equals(ln)) {
StringBuilder sb = new StringBuilder();
parser.nextTag();
while (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
// author is directly nested below authors
assert "author".equals(parser.getLocalName());
String author = parser.getElementText();
if (sb.length() == 0) {
// first author
sb.append(author);
} else {
sb.append(" and ");
sb.append(author);
}
assert parser.getEventType() == XMLStreamConstants.END_ELEMENT;
assert "author".equals(parser.getLocalName());
parser.nextTag();
// current tag is either begin:author or
// end:authors
}
e.setField(FieldName.AUTHOR, sb.toString());
} else if (FieldName.JOURNAL.equals(ln)) {
// we guess that the entry is a journal
// the alternative way is to parse
// ctx:context-objects / ctx:context-object / ctx:referent / ctx:metadata-by-val / ctx:metadata / journal / rft:genre
// the drawback is that ctx:context-objects is NOT nested in citation, but a separate element
// we would have to change the whole parser to parse that format.
type = BibtexEntryTypes.ARTICLE;
e.setField(ln, parser.getElementText());
} else if ("tech".equals(ln)) {
type = BibtexEntryTypes.TECHREPORT;
// the content of the "tech" field seems to contain the number of the technical report
e.setField(FieldName.NUMBER, parser.getElementText());
} else if (FieldName.DOI.equals(ln) || FieldName.INSTITUTION.equals(ln)
|| FieldName.LOCATION.equals(ln) || FieldName.NUMBER.equals(ln)
|| FieldName.NOTE.equals(ln) || FieldName.TITLE.equals(ln)
|| FieldName.PAGES.equals(ln) || FieldName.PUBLISHER.equals(ln)
|| FieldName.VOLUME.equals(ln) || FieldName.YEAR.equals(ln)) {
e.setField(ln, parser.getElementText());
} else if (FieldName.BOOKTITLE.equals(ln)) {
String booktitle = parser.getElementText();
if (booktitle.startsWith("In ")) {
// special treatment for parsing of
// "In proceedings of..." references
booktitle = booktitle.substring(3);
}
e.setField(FieldName.BOOKTITLE, booktitle);
} else if ("raw_string".equals(ln)) {
// raw input string is ignored
} else {
// all other tags are stored as note
noteSB.append(ln);
noteSB.append(':');
noteSB.append(parser.getElementText());
noteSB.append(OS.NEWLINE);
}
}
parser.next();
}
if (noteSB.length() > 0) {
String note;
if (e.hasField(FieldName.NOTE)) {
// "note" could have been set during the parsing as FreeCite also returns "note"
note = e.getFieldOptional(FieldName.NOTE).get().concat(OS.NEWLINE)
.concat(noteSB.toString());
} else {
note = noteSB.toString();
}
e.setField(FieldName.NOTE, note);
}
// type has been derived from "genre"
// has to be done before label generation as label generation is dependent on entry type
e.setType(type);
// autogenerate label (BibTeX key)
BibtexKeyPatternUtil.makeLabel(
JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getMetaData(),
JabRefGUI.getMainFrame().getCurrentBasePanel().getDatabase(), e,
importFormatPreferences.getBibtexKeyPatternPreferences());
res.add(e);
}
parser.next();
}
parser.close();
} catch (IOException | XMLStreamException ex) {
LOGGER.warn("Could not parse", ex);
return new ParserResult();
}
return new ParserResult(res);
}
@Override
public String getFormatName() {
return "text citations";
}
@Override
public FileExtensions getExtensions() {
return FileExtensions.FREECITE;
}
@Override
public String getDescription() {
return "This importer parses text format citations using the online API of FreeCite.";
}
}
| ambro2/jabref | src/main/java/net/sf/jabref/logic/importer/fileformat/FreeCiteImporter.java | Java | gpl-2.0 | 10,863 |
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include "Event.hpp"
#include "Events.hpp"
#include "stats.hpp"
int main() {
std::string line;
Events events;
while (std::getline(std::cin, line)) {
std::vector<std::string> elements;
boost::split(elements, line, boost::is_any_of("/"));
if (elements.size() != 4) {
std::cerr << "Warning: elements.size() != 4" << std::endl;
continue;
}
Event e;
e.player = elements[0];
e.map = elements[1];
e.lapTime = parseLapTime(elements[2]);
e.date = parseDate(elements[3]);
events.push_back(e);
}
std::cout << "Number of events: " << events.size() << std::endl;
std::sort(events.begin(), events.end());
std::cout << "Last event: " << events.back() << std::endl;
Ranking ranking = getRankings(events, boost::posix_time::time_from_string("2014-01-03 22:00:00.000"));
for ( unsigned i = 0; i < 20 && i < ranking.size(); ++i ) {
std::cout << i+1 << ".: " << ranking[i].getPlayer() << ", Time: " << ranking[i].getTotalLapTime() << std::endl;
}
std::cout << "Current leader = " << ranking[0].getTotalLapTime() << std::endl;
}
| r0mai/jtt-competition-rank-visualiser | src/main.cpp | C++ | gpl-2.0 | 1,173 |
/***************************************************************************
* Copyright (C) 2008 Philipp Nordhus *
* pnordhus@users.sourceforge.net *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "circle.h"
#include "rect.h"
#include "world.h"
World::World()
{
}
World::~World()
{
Q_ASSERT(m_objects.isEmpty());
}
void World::setGravity(const Vector& gravity)
{
m_gravity = gravity;
}
void World::process(float time)
{
const uint iterations = time / 0.001;
const float stepSize = time / iterations;
for (uint i = 0; i < iterations; i++) {
foreach (Object* obj, m_objects) {
if (obj->isStatic())
continue;
if (obj->isLinked()) {
obj->accelerate(0.5f * stepSize);
} else {
// gravity only applies to non-linked objects
obj->accelerate(m_gravity * stepSize);
}
obj->move(stepSize);
}
collide();
}
}
void World::collide()
{
for (int i = 0; i + 1 < m_objects.size(); i++) {
for (int j = i + 1; j < m_objects.size(); j++) {
collide(m_objects[i], m_objects[j]);
}
}
}
void World::collide(Object* obj1, Object* obj2)
{
if ((obj1->type() != Object::Circle) && (obj2->type() != Object::Circle))
return;
if ((obj1->type() == Object::Circle) && (obj2->type() == Object::Circle)) {
collide2(static_cast<Circle*>(obj1), static_cast<Circle*>(obj2));
return;
}
if ((obj1->type() == Object::Circle) && (obj2->type() == Object::Rect)) {
collide2(static_cast<Circle*>(obj1), static_cast<Rect*>(obj2));
return;
}
if ((obj1->type() == Object::Rect) && (obj2->type() == Object::Circle)) {
collide2(static_cast<Circle*>(obj2), static_cast<Rect*>(obj1));
return;
}
Q_ASSERT(false);
}
void World::collide2(Circle* circle, Rect* rect)
{
const float dist = (circle->position() - rect->position()).length();
if (dist >= circle->radius() + rect->radius())
return;
Vector toCirc = circle->position() - rect->position();
const float distToLine = toCirc * rect->dir().perpendicular();
if (qAbs(distToLine) > circle->radius() + rect->width())
return;
// test for collision with cap 1
if (collideCircleRectCap(circle, rect, rect->position1(), rect->dir()))
return;
// test for collision with cap 2
if (collideCircleRectCap(circle, rect, rect->position2(), -rect->dir()))
return;
if (circle->isLinked() && !rect->unlink()) {
collideCircleRectLinked(circle, rect);
return;
}
circle->unlink();
const float move = circle->radius() + rect->width() - qAbs(distToLine) + 0.001;
collideCircleRectUnlinked(circle, rect, rect->dir());
toCirc = rect->dir().perpendicular() * distToLine;
circle->move(toCirc.normalized() * move);
circle->collide(false);
}
bool World::collideCircleRectCap(Circle* circle, Rect* rect, const Vector& center, const Vector& dirLine)
{
Vector toCirc = circle->position() - center;
const float distToLine = toCirc * dirLine;
if (distToLine >= 0.0f)
return false;
// ok we are behind the line, return true from here on!
const float dist = toCirc.length();
if (dist >= circle->radius() + rect->width())
return true;
if (circle->isLinked() && !rect->unlink()) {
collideCircleRectLinked(circle, rect);
return true;
}
circle->unlink();
const Vector dir = toCirc.perpendicular().normalized();;
const float move = circle->radius() + rect->width() - toCirc.length() + 0.001;
collideCircleRectUnlinked(circle, rect, dir);
circle->move(toCirc.normalized() * move);
circle->collide(false);
return true;
}
void World::collideCircleRectLinked(Circle* circle, Rect* rect)
{
float speed = 2.0f * qAbs(circle->linkSpeed());
speed *= rect->boostScale();
speed += rect->boost();
circle->accelerate(-speed);
}
void World::collideCircleRectUnlinked(Circle* circle, Rect* rect, const Vector& tangent)
{
const float angle = tangent.angleTo(circle->speed());
const Vector accelDir(angle + tangent.angle());
float speed = circle->speed().length();
speed *= rect->boostScale();
speed += rect->boost();
circle->accelerate(-circle->speed() + accelDir * speed);
}
void World::collide2(Circle* obj1, Circle* obj2)
{
const float dist = (obj1->position() - obj2->position()).length();
if (dist >= obj1->radius() + obj2->radius())
return;
obj1->unlink();
obj2->unlink();
const Vector to1 = (obj1->position() - obj2->position()).normalized();
const Vector to2 = -to1;
const Vector speed1 = obj1->speed();
const Vector speed2 = obj2->speed();
const float mass1 = obj1->mass();
const float mass2 = obj2->mass();
const float massSum = mass1 + mass2;
float impulseTransferToFactor1 = ((mass1 - mass2) * speed1.length() + 2.0f * mass2 * speed2.length()) / massSum;
float impulseTransferToFactor2 = ((mass2 - mass1) * speed2.length() + 2.0f * mass1 * speed1.length()) / massSum;
const float angleAffectorTo1 = cos(to1.angleTo(speed2));
const float angleAffectorTo2 = cos(to2.angleTo(speed1));
impulseTransferToFactor1 = angleAffectorTo1 * impulseTransferToFactor1;
impulseTransferToFactor2 = angleAffectorTo2 * impulseTransferToFactor2;
const Vector impulseTransferTo1 = to1 * impulseTransferToFactor1;
const Vector impulseTransferTo2 = to2 * impulseTransferToFactor2;
obj1->accelerate(impulseTransferTo1 - impulseTransferTo2);
obj2->accelerate(impulseTransferTo2 - impulseTransferTo1);
const float move = (obj1->radius() + obj2->radius() - dist) / 2.0f;
obj1->move(to1 * move);
obj2->move(to2 * move);
obj1->collide(true);
obj2->collide(true);
}
void World::registerObject(Object* obj)
{
m_objects.append(obj);
}
void World::unregisterObject(Object* obj)
{
m_objects.removeAll(obj);
}
| pnordhus/openorbiter | src/physics/world.cpp | C++ | gpl-2.0 | 6,880 |
# -*- coding: UTF-8 -*-
import eqq
import argparse
from eqq import EqqClient
class EqqMachine(object):
def __init__(self,uin,pwd):
self.eqq=EqqClient()
self.eqq.set_output()
self.uin=uin
self.pwd=pwd
self.eqq.set_account(uin,pwd)
self.eqq.login()
self.eqq.get_friend_info2(uin)
self.eqq.get_user_friends2()
self.eqq.get_group_name_list_mask2()
self.eqq.get_online_buddies2()
self.eqq.get_recent_list2()
self.groups
def init(self):
self.set_message_process()
self.eqq.start()
def run(self):
while True:
cmd=raw_input("eqq#:")
self.pase_command(cmd)
def pase_command(self,command):
pass
def set_message_process(self):
self.eqq.set_poll_type_action('shake_message',self.process_shake_message)
self.eqq.set_poll_type_action('group_message',self.process_group_message)
def process_shake_message(self,message):
print '#shake_message:',message
pass
def process_group_message(self,message):
print '#group_message:',message
print 'content:',message['content']
for c in message['content']:
print 'c:',c
pass
| evilbinary/eqq-python | eqq_machine.py | Python | gpl-2.0 | 1,306 |
<?php
/*
* Copyright (c) 2006, Universal Diagnostic Solutions, Inc.
*
* This file is part of Tracmor.
*
* Tracmor 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.
*
* Tracmor 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 Tracmor; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
?>
<?php
class QAssetTransactComposite extends QControl {
public $blnEditMode;
public $objParentObject;
public $strTitleVerb;
public $objAssetArray;
public $dtgAssetTransact;
public $objAsset;
public $blnTransactionModified;
protected $lstLocation;
protected $txtNote;
protected $objAssetTransaction;
protected $btnSave;
protected $btnCancel;
protected $btnAdd;
protected $btnRemove;
protected $txtNewAssetCode;
protected $objTransaction;
protected $intTransactionTypeId;
public function __construct($objParentObject, $strControlId = null) {
// First, call the parent to do most of the basic setup
try {
parent::__construct($objParentObject, $strControlId);
} catch (QCallerException $objExc) {
$objExc->IncrementOffset();
throw $objExc;
}
// Assign the parent object (AssetEditForm from asset_edit.php)
$this->objParentObject = $objParentObject;
// Setup the Asset, which assigns objAsset and blnEditMode
$this->objParentObject->SetupAsset($this);
// Create an empty Asset Array
$this->objAssetArray = array();
$this->btnCancel_Create();
$this->lstLocation_Create();
$this->txtNote_Create();
$this->txtNewAssetCode_Create();
$this->btnAdd_Create();
$this->btnSave_Create();
$this->dtgAssetTransact_Create();
}
// This method must be declared in all composite controls
public function ParsePostData() {
}
public function GetJavaScriptAction() {
return "onchange";
}
public function Validate() {return true;}
protected function GetControlHtml() {
$strStyle = $this->GetStyleAttributes();
if ($strStyle) {
$strStyle = sprintf('style="%s"', $strStyle);
}
$strAttributes = $this->GetAttributes();
// Store the Output Buffer locally
$strAlreadyRendered = ob_get_contents();
ob_clean();
// Evaluate the template
require('asset_transact_control.inc.php');
$strTemplateEvaluated = ob_get_contents();
ob_clean();
// Restore the output buffer and return evaluated template
print($strAlreadyRendered);
$strToReturn = sprintf('<span id="%s" %s%s>%s</span>',
$this->strControlId,
$strStyle,
$strAttributes,
$strTemplateEvaluated);
return $strToReturn;
}
// I'm pretty sure that this is not necessary
// Create the Asset Code label
protected function lblAssetCode_Create() {
$this->lblAssetCode = new QLabel($this);
$this->lblAssetCode->Name = 'Asset Code';
$this->lblAssetCode->Text = $this->objAsset->AssetCode;
}
// Create the Note text field
protected function txtNote_Create() {
$this->txtNote = new QTextBox($this);
$this->txtNote->Name = 'Note';
$this->txtNote->TextMode = QTextMode::MultiLine;
$this->txtNote->Columns = 80;
$this->txtNote->Rows = 4;
$this->txtNote->CausesValidation = false;
}
// Create and Setup lstLocation
protected function lstLocation_Create() {
$this->lstLocation = new QListBox($this);
$this->lstLocation->Name = 'Location';
$this->lstLocation->AddItem('- Select One -', null);
$objLocationArray = Location::LoadAllLocations(false, false, 'short_description');
if ($objLocationArray) foreach ($objLocationArray as $objLocation) {
$objListItem = new QListItem($objLocation->__toString(), $objLocation->LocationId);
$this->lstLocation->AddItem($objListItem);
}
$this->lstLocation->CausesValidation = false;
}
// Create the text field to enter new asset codes to add to the transaction
// Eventually this field will receive information from the AML
protected function txtNewAssetCode_Create() {
$this->txtNewAssetCode = new QTextBox($this);
$this->txtNewAssetCode->Name = 'Asset Code';
$this->txtNewAssetCode->AddAction(new QEnterKeyEvent(), new QAjaxControlAction($this, 'btnAdd_Click'));
$this->txtNewAssetCode->AddAction(new QEnterKeyEvent(), new QTerminateAction());
$this->txtNewAssetCode->CausesValidation = false;
}
// Create the save button
protected function btnSave_Create() {
$this->btnSave = new QButton($this);
$this->btnSave->Text = 'Save';
$this->btnSave->AddAction(new QClickEvent(), new QAjaxControlAction($this, 'btnSave_Click'));
$this->btnSave->AddAction(new QEnterKeyEvent(), new QAjaxControlAction($this, 'btnSave_Click'));
$this->btnSave->AddAction(new QEnterKeyEvent(), new QTerminateAction());
$this->btnSave->CausesValidation = false;
}
// Setup Cancel Button
protected function btnCancel_Create() {
$this->btnCancel = new QButton($this);
$this->btnCancel->Text = 'Cancel';
$this->btnCancel->AddAction(new QClickEvent(), new QAjaxControlAction($this, 'btnCancel_Click'));
$this->btnCancel->AddAction(new QEnterKeyEvent(), new QAjaxControlAction($this, 'btnCancel_Click'));
$this->btnCancel->AddAction(new QEnterKeyEvent(), new QTerminateAction());
$this->btnCancel->CausesValidation = false;
}
// Setup Add Button
protected function btnAdd_Create() {
$this->btnAdd = new QButton($this);
$this->btnAdd->Text = 'Add';
$this->btnAdd->AddAction(new QClickEvent(), new QAjaxControlAction($this, 'btnAdd_Click'));
$this->btnAdd->AddAction(new QEnterKeyEvent(), new QAjaxControlAction($this, 'btnAdd_Click'));
$this->btnAdd->AddAction(new QEnterKeyEvent(), new QTerminateAction());
$this->btnAdd->CausesValidation = false;
}
// Setup the datagrid
protected function dtgAssetTransact_Create() {
$this->dtgAssetTransact = new QDataGrid($this);
$this->dtgAssetTransact->CellPadding = 5;
$this->dtgAssetTransact->CellSpacing = 0;
$this->dtgAssetTransact->CssClass = "datagrid";
// Enable AJAX - this won't work while using the DB profiler
$this->dtgAssetTransact->UseAjax = true;
// Enable Pagination, and set to 20 items per page
$objPaginator = new QPaginator($this->dtgAssetTransact);
$this->dtgAssetTransact->Paginator = $objPaginator;
$this->dtgAssetTransact->ItemsPerPage = 20;
$this->dtgAssetTransact->AddColumn(new QDataGridColumn('Asset Code', '<?= $_ITEM->__toStringWithLink("bluelink") ?>', array('OrderByClause' => QQ::OrderBy(QQN::Asset()->AssetCode), 'ReverseOrderByClause' => QQ::OrderBy(QQN::Asset()->AssetCode, false), 'CssClass' => "dtg_column", 'HtmlEntities' => false)));
$this->dtgAssetTransact->AddColumn(new QDataGridColumn('Model', '<?= $_ITEM->AssetModel->__toStringWithLink("bluelink") ?>', array('OrderByClause' => QQ::OrderBy(QQN::Asset()->AssetModel->ShortDescription), 'ReverseOrderByClause' => QQ::OrderBy(QQN::Asset()->AssetModel->ShortDescription, false), 'Width' => 200, 'CssClass' => "dtg_column", 'HtmlEntities' => false)));
$this->dtgAssetTransact->AddColumn(new QDataGridColumn('Current Location', '<?= $_ITEM->Location->__toString() ?>', array('OrderByClause' => QQ::OrderBy(QQN::Asset()->Location->ShortDescription), 'ReverseOrderByClause' => QQ::OrderBy(QQN::Asset()->Location->ShortDescription, false), 'CssClass' => "dtg_column", 'HtmlEntities' => false)));
$this->dtgAssetTransact->AddColumn(new QDataGridColumn('Action', '<?= $_FORM->RemoveColumn_Render($_ITEM) ?>', array('CssClass' => "dtg_column", 'HtmlEntities' => false)));
/* $this->dtgAssetTransact->AddColumn(new QDataGridColumn('Asset Code', '<?= $_ITEM->__toStringWithLink("bluelink") ?>', 'SortByCommand="asset_code ASC"', 'ReverseSortByCommand="asset_code DESC"', 'CssClass="dtg_column"', 'HtmlEntities=false"'));
$this->dtgAssetTransact->AddColumn(new QDataGridColumn('Model', '<?= $_ITEM->AssetModel->__toStringWithLink("bluelink") ?>', 'Width=200', 'SortByCommand="asset__asset_model_id__short_description ASC"', 'ReverseSortByCommand="asset__asset_model_id__short_description DESC"', 'CssClass="dtg_column"', 'HtmlEntities=false"'));
$this->dtgAssetTransact->AddColumn(new QDataGridColumn('Current Location', '<?= $_ITEM->Location->__toString() ?>', 'SortByCommand="asset__location_id__short_description ASC"', 'ReverseSortByCommand="asset__location_id__short_description DESC"', 'CssClass=dtg_column', 'HtmlEntities=false"'));
$this->dtgAssetTransact->AddColumn(new QDataGridColumn('Action', '<?= $_FORM->RemoveColumn_Render($_ITEM) ?>', 'CssClass=dtg_column', 'HtmlEntities=false"'));
*/
$objStyle = $this->dtgAssetTransact->RowStyle;
$objStyle->ForeColor = '#000000';
$objStyle->BackColor = '#FFFFFF';
$objStyle->FontSize = 12;
$objStyle = $this->dtgAssetTransact->AlternateRowStyle;
$objStyle->BackColor = '#EFEFEF';
$objStyle = $this->dtgAssetTransact->HeaderRowStyle;
$objStyle->ForeColor = '#000000';
$objStyle->BackColor = '#EFEFEF';
$objStyle->CssClass = 'dtg_header';
$this->blnTransactionModified = true;
}
// Add Button Click
public function btnAdd_Click($strFormId, $strControlId, $strParameter) {
$strAssetCode = $this->txtNewAssetCode->Text;
$blnDuplicate = false;
$blnError = false;
if ($strAssetCode) {
// Begin error checking
if ($this->objAssetArray) {
foreach ($this->objAssetArray as $asset) {
if ($asset && $asset->AssetCode == $strAssetCode) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset has already been added.";
}
}
}
if (!$blnError) {
$objNewAsset = Asset::LoadByAssetCode($this->txtNewAssetCode->Text);
if (!($objNewAsset instanceof Asset)) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset code does not exist.";
}
// Cannot move, check out/in, nor reserve/unreserve any assets that have been shipped
elseif ($objNewAsset->LocationId == 2) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset has already been shipped.";
}
// Cannot move, check out/in, nor reserve/unreserve any assets that are scheduled to be received
elseif ($objNewAsset->LocationId == 5) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is currently scheduled to be received.";
}
elseif ($objPendingShipment = AssetTransaction::PendingShipment($objNewAsset->AssetId)) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is already in a pending shipment.";
}
elseif (!QApplication::AuthorizeEntityBoolean($objNewAsset, 2)) {
$blnError = true;
$this->txtNewAssetCode->Warning = "You do not have authorization to perform a transaction on this asset.";
}
// Move
elseif ($this->intTransactionTypeId == 1) {
if ($objNewAsset->CheckedOutFlag) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is checked out.";
}
elseif ($objNewAsset->ReservedFlag) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is reserved.";
}
}
// Check in
elseif ($this->intTransactionTypeId == 2) {
if (!$objNewAsset->CheckedOutFlag) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is not checked out.";
}
elseif ($objNewAsset->ReservedFlag) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is reserved.";
}
elseif ($objNewAsset->CheckedOutFlag) {
$objUserAccount = $objNewAsset->GetLastTransactionUser();
if ($objUserAccount->UserAccountId != QApplication::$objUserAccount->UserAccountId) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset was not checked out by the current user.";
}
}
}
elseif ($this->intTransactionTypeId ==3) {
if ($objNewAsset->CheckedOutFlag) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is already checked out.";
}
elseif ($objNewAsset->ReservedFlag) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is reserved.";
}
}
elseif ($this->intTransactionTypeId == 8) {
if ($objNewAsset->ReservedFlag) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is already reserved.";
}
elseif ($objNewAsset->CheckedOutFlag) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is checked out.";
}
}
// Unreserver
elseif ($this->intTransactionTypeId == 9) {
if (!$objNewAsset->ReservedFlag) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is not reserved";
}
elseif ($objNewAsset->CheckedOutFlag) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset is checked out.";
}
elseif ($objNewAsset->ReservedFlag) {
$objUserAccount = $objNewAsset->GetLastTransactionUser();
if ($objUserAccount->UserAccountId != QApplication::$objUserAccount->UserAccountId) {
$blnError = true;
$this->txtNewAssetCode->Warning = "That asset was not reserved by the current user.";
}
}
}
if (!$blnError && $objNewAsset instanceof Asset) {
$this->objAssetArray[] = $objNewAsset;
$this->txtNewAssetCode->Text = null;
}
}
}
else {
$this->txtNewAssetCode->Warning = "Please enter an asset code.";
}
}
// Save Button Click
public function btnSave_Click($strFormId, $strControlId, $strParameter) {
if ($this->objAssetArray) {
$blnError = false;
foreach ($this->objAssetArray as $asset) {
// TransactionTypeId = 1 is for moves
if ($this->intTransactionTypeId == 1) {
if ($asset->LocationId == $this->lstLocation->SelectedValue) {
$this->dtgAssetTransact->Warning = 'Cannot move an asset from a location to the same location.';
$blnError = true;
}
}
// For all transactions except Unreserve, make sure the asset is not already reserved
if ($this->intTransactionTypeId != 9 && $asset->ReservedFlag) {
$this->btnCancel->Warning = sprintf('The Asset %s is reserved.',$asset->AssetCode);
$blnError = true;
}
}
if (!$blnError) {
if (($this->intTransactionTypeId == 1 || $this->intTransactionTypeId == 2) && is_null($this->lstLocation->SelectedValue)) {
$this->lstLocation->Warning = 'Location is required.';
$blnError = true;
}
elseif ($this->txtNote->Text == '') {
$this->txtNote->Warning = 'Note is required.';
$blnError = true;
}
}
if (!$blnError) {
try {
// Get an instance of the database
$objDatabase = QApplication::$Database[1];
// Begin a MySQL Transaction to be either committed or rolled back
$objDatabase->TransactionBegin();
// Create the new transaction object and save it
$this->objTransaction = new Transaction();
// Entity Qtype is Asset
$this->objTransaction->EntityQtypeId = EntityQtype::Asset;
$this->objTransaction->TransactionTypeId = $this->intTransactionTypeId;
$this->objTransaction->Note = $this->txtNote->Text;
$this->objTransaction->Save();
// Assign different source and destinations depending on transaction type
foreach ($this->objAssetArray as $asset) {
if ($asset instanceof Asset) {
$SourceLocationId = $asset->LocationId;
if ($this->intTransactionTypeId == 1) {
$DestinationLocationId = $this->lstLocation->SelectedValue;
}
elseif ($this->intTransactionTypeId == 2) {
$DestinationLocationId = $this->lstLocation->SelectedValue;
$asset->CheckedOutFlag = false;
}
elseif ($this->intTransactionTypeId == 3) {
$DestinationLocationId = 1;
$asset->CheckedOutFlag = true;
}
elseif ($this->intTransactionTypeId == 8) {
$DestinationLocationId = $asset->LocationId;
$asset->ReservedFlag = true;
}
elseif ($this->intTransactionTypeId == 9) {
$DestinationLocationId = $asset->LocationId;
$asset->ReservedFlag = false;
}
$asset->LocationId = $DestinationLocationId;
$asset->Save();
// Create the new assettransaction object and save it
$this->objAssetTransaction = new AssetTransaction();
$this->objAssetTransaction->AssetId = $asset->AssetId;
$this->objAssetTransaction->TransactionId = $this->objTransaction->TransactionId;
$this->objAssetTransaction->SourceLocationId = $SourceLocationId;
$this->objAssetTransaction->DestinationLocationId = $DestinationLocationId;
$this->objAssetTransaction->Save();
}
}
// Commit the above transactions to the database
$objDatabase->TransactionCommit();
QApplication::Redirect('../common/transaction_edit.php?intTransactionId='.$this->objTransaction->TransactionId);
}
catch (QOptimisticLockingException $objExc) {
// Rollback the database
$objDatabase->TransactionRollback();
$objAsset = Asset::Load($objExc->EntityId);
$this->objParentObject->btnRemove_Click($this->objParentObject->FormId, 'btnRemove' . $objExc->EntityId, $objExc->EntityId);
// Lock Exception Thrown, Report the Error
$this->btnCancel->Warning = sprintf('The Asset %s has been altered by another user and removed from the transaction. You may add the asset again or save the transaction without it.', $objAsset->AssetCode);
}
}
}
}
// Cancel Button Click
public function btnCancel_Click($strFormId, $strControlId, $strParameter) {
if ($this->blnEditMode) {
$this->objParentObject->DisplayTransaction(false);
$this->objAssetArray = null;
$this->txtNewAssetCode->Text = null;
$this->txtNote->Text = null;
$this->objParentObject->DisplayEdit(true);
$this->objAssetArray[] = $this->objAsset;
}
else {
QApplication::Redirect('asset_list.php');
}
}
// Prepare the Transaction form display depending on transaction type
public function SetupDisplay($intTransactionTypeId) {
$this->intTransactionTypeId = $intTransactionTypeId;
switch ($this->intTransactionTypeId) {
// Move
case 1:
$this->lstLocation->Display = true;
break;
// Check In
case 2:
$this->lstLocation->Display = true;
break;
// Check Out
case 3:
$this->lstLocation->Display = false;
break;
// Reserve
case 8:
$this->lstLocation->Display = false;
break;
// Unreserve
case 9:
$this->lstLocation->Display = false;
break;
}
// Redeclare in case the asset has been edited
$this->objAssetArray = null;
if ($this->blnEditMode && $this->objAsset instanceof Asset) {
$this->objAssetArray[] = Asset::Load($this->objAsset->AssetId);
}
}
// And our public getter/setters
public function __get($strName) {
switch ($strName) {
case "objAsset": return $this->objAsset;
case "objAssetArray": return $this->objAssetArray;
case "dtgAssetTransact": return $this->dtgAssetTransact;
case "intTransactionTypeId": return $this->intTransactionTypeId;
case "blnTransactionModified": return $this->blnTransactionModified;
default:
try {
return parent::__get($strName);
} catch (QCallerException $objExc) {
$objExc->IncrementOffset();
throw $objExc;
}
}
}
/////////////////////////
// Public Properties: SET
/////////////////////////
public function __set($strName, $mixValue) {
$this->blnModified = true;
switch ($strName) {
case "objAsset": $this->objAsset = $mixValue;
break;
case "objAssetArray": $this->objAssetArray = $mixValue;
break;
case "strTitleVerb": $this->strTitleVerb = $mixValue;
break;
case "blnEditMode": $this->blnEditMode = $mixValue;
break;
case "dtgAssetTransact": $this->dtgAssetTransact = $mixValue;
break;
case "intTransactionTypeId": $this->intTransactionTypeId = $mixValue;
break;
case "blnTransactionModified": $this->blnTransactionModified = $mixValue;
default:
try {
parent::__set($strName, $mixValue);
} catch (QCallerException $objExc) {
$objExc->IncrementOffset();
throw $objExc;
}
break;
}
}
}
?> | heshuai64/einv2 | includes/qcodo/qform/QAssetTransactComposite.class.php | PHP | gpl-2.0 | 20,711 |
'''
Created on Nov 13, 2013
@author: samriggs
CODE CHALLENGE: Solve the Minimum Skew Problem.
https://beta.stepic.org/Bioinformatics-Algorithms-2/Peculiar-Statistics-of-the-Forward-and-Reverse-Half-Strands-7/#step-6
'''
from bi_utils.helpers import sane_open
from cStringIO import StringIO
def min_skew(dataset=''):
if (not dataset):
dataset = "stepic_dataset.txt"
# O(n)
with sane_open(dataset) as f:
skew = 0
skew_list = []
for c in f.readline():
# calculate skew for each char
skew_list.append(skew)
if (c == "C"):
skew -= 1
elif (c == "G"):
skew += 1
# get min value, O(n)
min_skew = min(skew_list)
# O(n)
position = 0
file_str = StringIO()
for num in skew_list:
if (num == min_skew):
file_str.write( str(position) )
file_str.write(" ")
position += 1
print file_str.getvalue().strip()
if (__name__ == "__main__"):
min_skew() | samriggs/bioinf | Homeworks/bi-Python/chapter1/quiz6_solution.py | Python | gpl-2.0 | 1,112 |
<?php
/**
*
* Profile Flair. An extension for the phpBB Forum Software package.
*
* @copyright (c) 2017, Steve Guidetti, https://github.com/stevotvr
* @license GNU General Public License, version 2 (GPL-2.0)
*
*/
namespace stevotvr\flair\controller;
use phpbb\db\driver\driver_interface;
use phpbb\json_response;
use stevotvr\flair\operator\category_interface;
use stevotvr\flair\operator\flair_interface;
use stevotvr\flair\operator\user_interface;
/**
* Profile Flair user MCP controller.
*/
class mcp_user_controller extends acp_base_controller implements mcp_user_interface
{
/**
* @var driver_interface
*/
protected $db;
/**
* @var category_interface
*/
protected $cat_operator;
/**
* @var flair_interface
*/
protected $flair_operator;
/**
* @var user_interface
*/
protected $user_operator;
/**
* @var p_master
*/
protected $p_master;
/**
* Set up the controller.
*
* @param driver_interface $db
* @param category_interface $cat_operator
* @param flair_interface $flair_operator
* @param user_interface $user_operator
*/
public function setup(driver_interface $db, category_interface $cat_operator, flair_interface $flair_operator, user_interface $user_operator)
{
$this->db = $db;
$this->cat_operator = $cat_operator;
$this->flair_operator = $flair_operator;
$this->user_operator = $user_operator;
}
/**
* @inheritDoc
*/
public function set_p_master($p_master)
{
$this->p_master = $p_master;
}
/**
* @inheritDoc
*/
public function find_user()
{
$this->language->add_lang('acp/users');
$u_find_username = append_sid($this->root_path . 'memberlist.' . $this->php_ext,
'mode=searchuser&form=select_user&field=username&select_single=true');
$this->template->assign_vars(array(
'S_SELECT_USER' => true,
'U_ACTION' => str_replace('mode=front', 'mode=user_flair', $this->u_action),
'U_FIND_USERNAME' => $u_find_username,
));
}
/**
* @inheritDoc
*/
public function edit_user_flair()
{
$user_id = $this->request->variable('u', 0);
$username = $this->request->variable('username', '', true);
$where = ($user_id) ? 'user_id = ' . (int) $user_id : "username_clean = '" . $this->db->sql_escape(utf8_clean_string($username)) . "'";
$sql = 'SELECT user_id, username, user_colour
FROM ' . USERS_TABLE . '
WHERE ' . $where;
$this->db->sql_query($sql);
$userrow = $this->db->sql_fetchrow();
$this->db->sql_freeresult();
if (!$userrow)
{
trigger_error($this->language->lang('NO_USER'), E_USER_WARNING);
}
$user_id = (int) $userrow['user_id'];
if (strpos($this->u_action, '&u=' . $user_id) === false)
{
$this->p_master->adjust_url('&u=' . $user_id);
$this->u_action .= '&u=' . $user_id;
}
if ($this->request->is_set_post('add_flair'))
{
$this->change_flair($user_id, 'add');
}
else if ($this->request->is_set_post('remove_flair'))
{
$this->change_flair($user_id, 'remove');
}
else if ($this->request->is_set_post('set_flair'))
{
$this->change_flair($user_id, 'set');
}
$user_flair = $this->user_operator->get_user_flair((array) $user_id);
$user_flair = isset($user_flair[$user_id]) ? $user_flair[$user_id] : array();
$this->assign_tpl_vars($user_id, $userrow['username'], $userrow['user_colour'], $user_flair);
}
/**
* Assign the template variables for the page.
*
* @param int $user_id The ID of the user being worked on
* @param string $username The name of the user being worked on
* @param string $user_colour The color of the user being worked on
* @param array $user_flair The flair items assigned to the user being worked on
*/
protected function assign_tpl_vars($user_id, $username, $user_colour, array $user_flair)
{
$this->template->assign_vars(array(
'FLAIR_USER' => $username,
'FLAIR_USER_FULL' => get_username_string('full', $user_id, $username, $user_colour),
'U_ACTION' => $this->u_action . '&u=' . $user_id,
));
$this->assign_flair_tpl_vars();
$this->assign_user_tpl_vars($user_flair);
}
/**
* Assign template variables for the available flair.
*/
protected function assign_flair_tpl_vars()
{
$available_cats = $this->cat_operator->get_categories();
$categories = array(array('category' => $this->language->lang('FLAIR_UNCATEGORIZED')));
foreach ($available_cats as $entity)
{
$categories[$entity->get_id()]['category'] = $entity->get_name();
}
$flair = $this->flair_operator->get_flair();
foreach ($flair as $entity)
{
$categories[$entity->get_category()]['items'][] = $entity;
}
foreach ($categories as $category)
{
if (!isset($category['items']))
{
continue;
}
$this->template->assign_block_vars('cat', array(
'CAT_NAME' => $category['category'],
));
foreach ($category['items'] as $entity)
{
$this->template->assign_block_vars('cat.item', array(
'FLAIR_TYPE' => $entity->get_type(),
'FLAIR_SIZE' => 2,
'FLAIR_ID' => $entity->get_id(),
'FLAIR_NAME' => $entity->get_name(),
'FLAIR_NAME_SHORT' => truncate_string($entity->get_name(), 30, 255, false, '…'),
'FLAIR_COLOR' => $entity->get_color(),
'FLAIR_ICON' => $entity->get_icon(),
'FLAIR_ICON_COLOR' => $entity->get_icon_color(),
'FLAIR_IMG' => $this->img_path . $entity->get_img(2),
));
}
}
}
/**
* Assign template variables for the user flair.
*
* @param array $user_flair The flair items assigned to the user being worked on
*/
protected function assign_user_tpl_vars(array $user_flair)
{
foreach ($user_flair as $category)
{
$this->template->assign_block_vars('flair', array(
'CAT_NAME' => $category['category']->get_name(),
));
foreach ($category['items'] as $item)
{
$entity = $item['flair'];
$this->template->assign_block_vars('flair.item', array(
'S_FROM_GROUP' => $item['from_group'],
'FLAIR_TYPE' => $entity->get_type(),
'FLAIR_SIZE' => 2,
'FLAIR_ID' => $entity->get_id(),
'FLAIR_NAME' => $entity->get_name(),
'FLAIR_NAME_SHORT' => truncate_string($entity->get_name(), 30, 255, false, '…'),
'FLAIR_COLOR' => $entity->get_color(),
'FLAIR_ICON' => $entity->get_icon(),
'FLAIR_ICON_COLOR' => $entity->get_icon_color(),
'FLAIR_IMG' => $this->img_path . $entity->get_img(2),
'FLAIR_FONT_COLOR' => $entity->get_font_color(),
'FLAIR_COUNT' => $item['count'],
));
}
}
}
/**
* Make a change to the flair assigned to the user or group being worked on.
*
* @param int $user_id The ID of the user being worked on
* @param string $change The type of change to make (add|remove|set)
*/
protected function change_flair($user_id, $change)
{
$action = $this->request->variable($change . '_flair', array('' => ''));
if (is_array($action))
{
list($id, ) = each($action);
}
if ($id)
{
if ($change === 'remove')
{
if (!confirm_box(true))
{
$hidden_fields = build_hidden_fields(array(
'remove_flair[' . $id . ']' => true,
));
confirm_box(false, $this->language->lang('MCP_FLAIR_REMOVE_CONFIRM'), $hidden_fields);
return;
}
$this->user_operator->set_flair_count($user_id, $id, 0);
}
else
{
$counts = $this->request->variable($change . '_count', array('' => ''));
$count = (isset($counts[$id])) ? (int) $counts[$id] : 1;
if ($change === 'add')
{
$this->user_operator->add_flair($user_id, $id, $count);
}
else if ($change === 'set')
{
$this->user_operator->set_flair_count($user_id, $id, $count);
}
}
if ($this->request->is_ajax())
{
$json_response = new json_response();
$json_response->send(array(
'REFRESH_DATA' => array(
'url' => html_entity_decode($this->u_action) . '&u=' . $user_id,
),
));
}
}
redirect($this->u_action . '&u=' . $user_id);
}
}
| stevotvr/phpbb-flair | controller/mcp_user_controller.php | PHP | gpl-2.0 | 7,940 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XWINDOWS")]
[assembly: AssemblyDescription("WINDOWS Model for XORCISM")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jerome Athias")]
[assembly: AssemblyProduct("XWINDOWS")]
[assembly: AssemblyCopyright("Copyright © Jerome Athias 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c113e364-c8b6-4791-aff4-9814a8495859")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| athiasjerome/XORCISM | SOURCES/XWINDOWS/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,443 |
<?php
/**
* @package EasySocial
* @copyright Copyright (C) 2010 - 2013 Stack Ideas Sdn Bhd. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* EasySocial is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
defined( '_JEXEC' ) or die( 'Unauthorized Access' );
?>
<?php if( $params->get( 'format' , 1 ) == 1 ){ ?>
<?php echo $name->first;?> <?php echo $name->middle;?> <?php echo $name->last;?>
<?php } ?>
<?php if( $params->get( 'format' , 1 ) == 2 ){ ?>
<?php echo $name->last;?> <?php echo $name->middle;?> <?php echo $name->first;?>
<?php } ?>
<?php if( $params->get( 'format' , 1 ) == 3 ){ ?>
<?php echo $name->name;?>
<?php } ?>
| cuongnd/test_pro | media/com_easysocial/apps/fields/user/joomla_fullname/themes/default/display_content.php | PHP | gpl-2.0 | 909 |
package anzac.peripherals.proxy;
public class ClientProxy extends CommonProxy {
@Override
public void registerKeyBindings() {
// TODO Auto-generated method stub
}
}
| williamanzac/anzacperipherals | src/main/java/anzac/peripherals/proxy/ClientProxy.java | Java | gpl-2.0 | 181 |
/*
* Copyright (C) 2011-2021 Project SkyFire <https://www.projectskyfire.org/>
* Copyright (C) 2008-2021 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2021 MaNGOS <https://www.getmangos.eu/>
* Copyright (C) 2006-2014 ScriptDev2 <https://github.com/scriptdev2/scriptdev2/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ObjectMgr.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellAuraEffects.h"
#include "Group.h"
#include "Spell.h"
#include "icecrown_citadel.h"
#include "Vehicle.h"
#include "GridNotifiers.h"
enum Say
{
// Festergut
SAY_FESTERGUT_GASEOUS_BLIGHT = 0,
SAY_FESTERGUT_DEATH = 1,
// Rotface
SAY_ROTFACE_OOZE_FLOOD = 2,
SAY_ROTFACE_DEATH = 3,
// Professor Putricide
SAY_AGGRO = 4,
EMOTE_UNSTABLE_EXPERIMENT = 5,
SAY_PHASE_TRANSITION_HEROIC = 6,
SAY_TRANSFORM_1 = 7,
SAY_TRANSFORM_2 = 8, // always used for phase2 change, DO NOT GROUP WITH SAY_TRANSFORM_1
EMOTE_MALLEABLE_GOO = 9,
EMOTE_CHOKING_GAS_BOMB = 10,
SAY_KILL = 11,
SAY_BERSERK = 12,
SAY_DEATH = 13
};
enum Spells
{
// Festergut
SPELL_RELEASE_GAS_VISUAL = 69125,
SPELL_GASEOUS_BLIGHT_LARGE = 69157,
SPELL_GASEOUS_BLIGHT_MEDIUM = 69162,
SPELL_GASEOUS_BLIGHT_SMALL = 69164,
SPELL_MALLEABLE_GOO_H = 72296,
SPELL_MALLEABLE_GOO_SUMMON = 72299,
// Professor Putricide
SPELL_SLIME_PUDDLE_TRIGGER = 70341,
SPELL_MALLEABLE_GOO = 70852,
SPELL_UNSTABLE_EXPERIMENT = 70351,
SPELL_TEAR_GAS = 71617, // phase transition
SPELL_TEAR_GAS_CREATURE = 71618,
SPELL_TEAR_GAS_CANCEL = 71620,
SPELL_TEAR_GAS_PERIODIC_TRIGGER = 73170,
SPELL_CREATE_CONCOCTION = 71621,
SPELL_GUZZLE_POTIONS = 71893,
SPELL_OOZE_TANK_PROTECTION = 71770, // protects the tank
SPELL_CHOKING_GAS_BOMB = 71255,
SPELL_OOZE_VARIABLE = 74118,
SPELL_GAS_VARIABLE = 74119,
SPELL_UNBOUND_PLAGUE = 70911,
SPELL_UNBOUND_PLAGUE_SEARCHER = 70917,
SPELL_PLAGUE_SICKNESS = 70953,
SPELL_UNBOUND_PLAGUE_PROTECTION = 70955,
SPELL_MUTATED_PLAGUE = 72451,
SPELL_MUTATED_PLAGUE_CLEAR = 72618,
// Slime Puddle
SPELL_GROW_STACKER = 70345,
SPELL_GROW = 70347,
SPELL_SLIME_PUDDLE_AURA = 70343,
// Gas Cloud
SPELL_GASEOUS_BLOAT_PROC = 70215,
SPELL_GASEOUS_BLOAT = 70672,
SPELL_GASEOUS_BLOAT_PROTECTION = 70812,
SPELL_EXPUNGED_GAS = 70701,
// Volatile Ooze
SPELL_OOZE_ERUPTION = 70492,
SPELL_VOLATILE_OOZE_ADHESIVE = 70447,
SPELL_OOZE_ERUPTION_SEARCH_PERIODIC = 70457,
SPELL_VOLATILE_OOZE_PROTECTION = 70530,
// Choking Gas Bomb
SPELL_CHOKING_GAS_BOMB_PERIODIC = 71259,
SPELL_CHOKING_GAS_EXPLOSION_TRIGGER = 71280,
// Mutated Abomination vehicle
SPELL_ABOMINATION_VEHICLE_POWER_DRAIN = 70385,
SPELL_MUTATED_TRANSFORMATION = 70311,
SPELL_MUTATED_TRANSFORMATION_DAMAGE = 70405,
SPELL_MUTATED_TRANSFORMATION_NAME = 72401,
// Unholy Infusion
SPELL_UNHOLY_INFUSION_CREDIT = 71518
};
#define SPELL_GASEOUS_BLOAT_HELPER RAID_MODE<uint32>(70672, 72455, 72832, 72833)
enum Events
{
// Festergut
EVENT_FESTERGUT_DIES = 1,
EVENT_FESTERGUT_GOO = 2,
// Rotface
EVENT_ROTFACE_DIES = 3,
EVENT_ROTFACE_OOZE_FLOOD = 5,
// Professor Putricide
EVENT_BERSERK = 6, // all phases
EVENT_SLIME_PUDDLE = 7, // all phases
EVENT_UNSTABLE_EXPERIMENT = 8, // P1 && P2
EVENT_TEAR_GAS = 9, // phase transition not heroic
EVENT_RESUME_ATTACK = 10,
EVENT_MALLEABLE_GOO = 11,
EVENT_CHOKING_GAS_BOMB = 12,
EVENT_UNBOUND_PLAGUE = 13,
EVENT_MUTATED_PLAGUE = 14,
EVENT_PHASE_TRANSITION = 15
};
enum Phases
{
PHASE_NONE = 0,
PHASE_FESTERGUT = 1,
PHASE_ROTFACE = 2,
PHASE_COMBAT_1 = 4,
PHASE_COMBAT_2 = 5,
PHASE_COMBAT_3 = 6
};
enum Points
{
POINT_FESTERGUT = 366260,
POINT_ROTFACE = 366270,
POINT_TABLE = 366780
};
Position const festergutWatchPos = {4324.820f, 3166.03f, 389.3831f, 3.316126f}; //emote 432 (release gas)
Position const rotfaceWatchPos = {4390.371f, 3164.50f, 389.3890f, 5.497787f}; //emote 432 (release ooze)
Position const tablePos = {4356.190f, 3262.90f, 389.4820f, 1.483530f};
// used in Rotface encounter
uint32 const oozeFloodSpells[4] = {69782, 69796, 69798, 69801};
enum PutricideData
{
DATA_EXPERIMENT_STAGE = 1,
DATA_PHASE = 2,
DATA_ABOMINATION = 3
};
#define EXPERIMENT_STATE_OOZE false
#define EXPERIMENT_STATE_GAS true
class AbominationDespawner
{
public:
explicit AbominationDespawner(Unit* owner) : _owner(owner) { }
bool operator()(uint64 guid)
{
if (Unit* summon = ObjectAccessor::GetUnit(*_owner, guid))
{
if (summon->GetEntry() == NPC_MUTATED_ABOMINATION_10 || summon->GetEntry() == NPC_MUTATED_ABOMINATION_25)
{
if (Vehicle* veh = summon->GetVehicleKit())
veh->RemoveAllPassengers(); // also despawns the vehicle
// Found unit is Mutated Abomination, remove it
return true;
}
// Found unit is not Mutated Abomintaion, leave it
return false;
}
// No unit found, remove from SummonList
return true;
}
private:
Unit* _owner;
};
struct RotfaceHeightCheck
{
RotfaceHeightCheck(Creature* rotface) : _rotface(rotface) { }
bool operator()(Creature* stalker) const
{
return stalker->GetPositionZ() < _rotface->GetPositionZ() + 5.0f;
}
private:
Creature* _rotface;
};
class boss_professor_putricide : public CreatureScript
{
public:
boss_professor_putricide() : CreatureScript("boss_professor_putricide") { }
struct boss_professor_putricideAI : public BossAI
{
boss_professor_putricideAI(Creature* creature) : BossAI(creature, DATA_PROFESSOR_PUTRICIDE),
_baseSpeed(creature->GetSpeedRate(MOVE_RUN)), _experimentState(EXPERIMENT_STATE_OOZE)
{
_phase = PHASE_NONE;
}
void Reset() OVERRIDE
{
if (!(events.IsInPhase(PHASE_ROTFACE) || events.IsInPhase(PHASE_FESTERGUT)))
instance->SetBossState(DATA_PROFESSOR_PUTRICIDE, NOT_STARTED);
instance->SetData(DATA_NAUSEA_ACHIEVEMENT, uint32(true));
events.Reset();
summons.DespawnAll();
SetPhase(PHASE_COMBAT_1);
_experimentState = EXPERIMENT_STATE_OOZE;
me->SetReactState(REACT_DEFENSIVE);
me->SetWalk(false);
if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
me->GetMotionMaster()->MovementExpired();
if (instance->GetBossState(DATA_ROTFACE) == DONE && instance->GetBossState(DATA_FESTERGUT) == DONE)
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_SELECTABLE);
}
void EnterCombat(Unit* who) OVERRIDE
{
if (events.IsInPhase(PHASE_ROTFACE) || events.IsInPhase(PHASE_FESTERGUT))
return;
if (!instance->CheckRequiredBosses(DATA_PROFESSOR_PUTRICIDE, who->ToPlayer()))
{
EnterEvadeMode();
instance->DoCastSpellOnPlayers(LIGHT_S_HAMMER_TELEPORT);
return;
}
me->setActive(true);
events.Reset();
events.ScheduleEvent(EVENT_BERSERK, 600000);
events.ScheduleEvent(EVENT_SLIME_PUDDLE, 10000);
events.ScheduleEvent(EVENT_UNSTABLE_EXPERIMENT, urand(30000, 35000));
if (IsHeroic())
events.ScheduleEvent(EVENT_UNBOUND_PLAGUE, 20000);
SetPhase(PHASE_COMBAT_1);
Talk(SAY_AGGRO);
DoCast(me, SPELL_OOZE_TANK_PROTECTION, true);
DoZoneInCombat(me);
instance->SetBossState(DATA_PROFESSOR_PUTRICIDE, IN_PROGRESS);
}
void JustReachedHome() OVERRIDE
{
_JustReachedHome();
me->SetWalk(false);
if (events.IsInPhase(PHASE_COMBAT_1) || events.IsInPhase(PHASE_COMBAT_2) || events.IsInPhase(PHASE_COMBAT_3))
instance->SetBossState(DATA_PROFESSOR_PUTRICIDE, FAIL);
}
void KilledUnit(Unit* victim) OVERRIDE
{
if (victim->GetTypeId() == TypeID::TYPEID_PLAYER)
Talk(SAY_KILL);
}
void JustDied(Unit* /*killer*/) OVERRIDE
{
_JustDied();
Talk(SAY_DEATH);
if (Is25ManRaid() && me->HasAura(SPELL_SHADOWS_FATE))
DoCastAOE(SPELL_UNHOLY_INFUSION_CREDIT, true);
DoCast(SPELL_MUTATED_PLAGUE_CLEAR);
}
void JustSummoned(Creature* summon) OVERRIDE
{
summons.Summon(summon);
switch (summon->GetEntry())
{
case NPC_MALLEABLE_OOZE_STALKER:
DoCast(summon, SPELL_MALLEABLE_GOO_H);
return;
case NPC_GROWING_OOZE_PUDDLE:
summon->CastSpell(summon, SPELL_GROW_STACKER, true);
summon->CastSpell(summon, SPELL_SLIME_PUDDLE_AURA, true);
// blizzard casts this spell 7 times initially (confirmed in sniff)
for (uint8 i = 0; i < 7; ++i)
summon->CastSpell(summon, SPELL_GROW, true);
break;
case NPC_GAS_CLOUD:
// no possible aura seen in sniff adding the aurastate
summon->ModifyAuraState(AURA_STATE_UNKNOWN22, true);
summon->CastSpell(summon, SPELL_GASEOUS_BLOAT_PROC, true);
summon->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
summon->SetReactState(REACT_PASSIVE);
break;
case NPC_VOLATILE_OOZE:
// no possible aura seen in sniff adding the aurastate
summon->ModifyAuraState(AURA_STATE_UNKNOWN19, true);
summon->CastSpell(summon, SPELL_OOZE_ERUPTION_SEARCH_PERIODIC, true);
summon->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
summon->SetReactState(REACT_PASSIVE);
break;
case NPC_CHOKING_GAS_BOMB:
summon->CastSpell(summon, SPELL_CHOKING_GAS_BOMB_PERIODIC, true);
summon->CastSpell(summon, SPELL_CHOKING_GAS_EXPLOSION_TRIGGER, true);
return;
case NPC_MUTATED_ABOMINATION_10:
case NPC_MUTATED_ABOMINATION_25:
return;
default:
break;
}
if (me->IsInCombat())
DoZoneInCombat(summon);
}
void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/) OVERRIDE
{
switch (_phase)
{
case PHASE_COMBAT_1:
if (HealthAbovePct(80))
return;
me->SetReactState(REACT_PASSIVE);
DoAction(ACTION_CHANGE_PHASE);
break;
case PHASE_COMBAT_2:
if (HealthAbovePct(35))
return;
me->SetReactState(REACT_PASSIVE);
DoAction(ACTION_CHANGE_PHASE);
break;
default:
break;
}
}
void MovementInform(uint32 type, uint32 id) OVERRIDE
{
if (type != POINT_MOTION_TYPE)
return;
switch (id)
{
case POINT_FESTERGUT:
instance->SetBossState(DATA_FESTERGUT, IN_PROGRESS); // needed here for delayed gate close
me->SetSpeed(MOVE_RUN, _baseSpeed, true);
DoAction(ACTION_FESTERGUT_GAS);
if (Creature* festergut = Unit::GetCreature(*me, instance->GetData64(DATA_FESTERGUT)))
festergut->CastSpell(festergut, SPELL_GASEOUS_BLIGHT_LARGE, false, NULL, NULL, festergut->GetGUID());
break;
case POINT_ROTFACE:
instance->SetBossState(DATA_ROTFACE, IN_PROGRESS); // needed here for delayed gate close
me->SetSpeed(MOVE_RUN, _baseSpeed, true);
DoAction(ACTION_ROTFACE_OOZE);
events.ScheduleEvent(EVENT_ROTFACE_OOZE_FLOOD, 25000, 0, PHASE_ROTFACE);
break;
case POINT_TABLE:
// stop attack
me->GetMotionMaster()->MoveIdle();
me->SetSpeed(MOVE_RUN, _baseSpeed, true);
if (GameObject* table = ObjectAccessor::GetGameObject(*me, instance->GetData64(DATA_PUTRICIDE_TABLE)))
me->SetFacingToObject(table);
// operating on new phase already
switch (_phase)
{
case PHASE_COMBAT_2:
{
SpellInfo const* spell = sSpellMgr->GetSpellInfo(SPELL_CREATE_CONCOCTION);
DoCast(me, SPELL_CREATE_CONCOCTION);
events.ScheduleEvent(EVENT_PHASE_TRANSITION, sSpellMgr->GetSpellForDifficultyFromSpell(spell, me)->CalcCastTime() + 100);
break;
}
case PHASE_COMBAT_3:
{
SpellInfo const* spell = sSpellMgr->GetSpellInfo(SPELL_GUZZLE_POTIONS);
DoCast(me, SPELL_GUZZLE_POTIONS);
events.ScheduleEvent(EVENT_PHASE_TRANSITION, sSpellMgr->GetSpellForDifficultyFromSpell(spell, me)->CalcCastTime() + 100);
break;
}
default:
break;
}
break;
default:
break;
}
}
void DoAction(int32 action) OVERRIDE
{
switch (action)
{
case ACTION_FESTERGUT_COMBAT:
SetPhase(PHASE_FESTERGUT);
me->SetSpeed(MOVE_RUN, _baseSpeed*2.0f, true);
me->GetMotionMaster()->MovePoint(POINT_FESTERGUT, festergutWatchPos);
me->SetReactState(REACT_PASSIVE);
DoZoneInCombat(me);
if (IsHeroic())
events.ScheduleEvent(EVENT_FESTERGUT_GOO, urand(13000, 18000), 0, PHASE_FESTERGUT);
break;
case ACTION_FESTERGUT_GAS:
Talk(SAY_FESTERGUT_GASEOUS_BLIGHT);
DoCast(me, SPELL_RELEASE_GAS_VISUAL, true);
break;
case ACTION_FESTERGUT_DEATH:
events.ScheduleEvent(EVENT_FESTERGUT_DIES, 4000, 0, PHASE_FESTERGUT);
break;
case ACTION_ROTFACE_COMBAT:
{
SetPhase(PHASE_ROTFACE);
me->SetSpeed(MOVE_RUN, _baseSpeed*2.0f, true);
me->GetMotionMaster()->MovePoint(POINT_ROTFACE, rotfaceWatchPos);
me->SetReactState(REACT_PASSIVE);
_oozeFloodStage = 0;
DoZoneInCombat(me);
// init random sequence of floods
if (Creature* rotface = Unit::GetCreature(*me, instance->GetData64(DATA_ROTFACE)))
{
std::list<Creature*> list;
GetCreatureListWithEntryInGrid(list, rotface, NPC_PUDDLE_STALKER, 50.0f);
list.remove_if(RotfaceHeightCheck(rotface));
if (list.size() > 4)
{
list.sort(Skyfire::ObjectDistanceOrderPred(rotface));
do
{
list.pop_back();
} while (list.size() > 4);
}
uint8 i = 0;
while (!list.empty())
{
std::list<Creature*>::iterator itr = list.begin();
std::advance(itr, urand(0, list.size()-1));
_oozeFloodDummyGUIDs[i++] = (*itr)->GetGUID();
list.erase(itr);
}
}
break;
}
case ACTION_ROTFACE_OOZE:
Talk(SAY_ROTFACE_OOZE_FLOOD);
if (Creature* dummy = Unit::GetCreature(*me, _oozeFloodDummyGUIDs[_oozeFloodStage]))
dummy->CastSpell(dummy, oozeFloodSpells[_oozeFloodStage], true, NULL, NULL, me->GetGUID()); // cast from self for LoS (with prof's GUID for logs)
if (++_oozeFloodStage == 4)
_oozeFloodStage = 0;
break;
case ACTION_ROTFACE_DEATH:
events.ScheduleEvent(EVENT_ROTFACE_DIES, 4500, 0, PHASE_ROTFACE);
break;
case ACTION_CHANGE_PHASE:
me->SetSpeed(MOVE_RUN, _baseSpeed*2.0f, true);
events.DelayEvents(30000);
me->AttackStop();
if (!IsHeroic())
{
DoCast(me, SPELL_TEAR_GAS);
events.ScheduleEvent(EVENT_TEAR_GAS, 2500);
}
else
{
Talk(SAY_PHASE_TRANSITION_HEROIC);
DoCast(me, SPELL_UNSTABLE_EXPERIMENT, true);
DoCast(me, SPELL_UNSTABLE_EXPERIMENT, true);
// cast variables
if (Is25ManRaid())
{
std::list<Unit*> targetList;
{
const std::list<HostileReference*>& threatlist = me->getThreatManager().getThreatList();
for (std::list<HostileReference*>::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr)
if ((*itr)->getTarget()->GetTypeId() == TypeID::TYPEID_PLAYER)
targetList.push_back((*itr)->getTarget());
}
size_t half = targetList.size()/2;
// half gets ooze variable
while (half < targetList.size())
{
std::list<Unit*>::iterator itr = targetList.begin();
advance(itr, urand(0, targetList.size() - 1));
(*itr)->CastSpell(*itr, SPELL_OOZE_VARIABLE, true);
targetList.erase(itr);
}
// and half gets gas
for (std::list<Unit*>::iterator itr = targetList.begin(); itr != targetList.end(); ++itr)
(*itr)->CastSpell(*itr, SPELL_GAS_VARIABLE, true);
}
me->GetMotionMaster()->MovePoint(POINT_TABLE, tablePos);
}
switch (_phase)
{
case PHASE_COMBAT_1:
SetPhase(PHASE_COMBAT_2);
events.ScheduleEvent(EVENT_MALLEABLE_GOO, urand(21000, 26000));
events.ScheduleEvent(EVENT_CHOKING_GAS_BOMB, urand(35000, 40000));
break;
case PHASE_COMBAT_2:
SetPhase(PHASE_COMBAT_3);
events.ScheduleEvent(EVENT_MUTATED_PLAGUE, 25000);
events.CancelEvent(EVENT_UNSTABLE_EXPERIMENT);
break;
default:
break;
}
break;
default:
break;
}
}
uint32 GetData(uint32 type) const OVERRIDE
{
switch (type)
{
case DATA_EXPERIMENT_STAGE:
return _experimentState;
case DATA_PHASE:
return _phase;
case DATA_ABOMINATION:
return uint32(summons.HasEntry(NPC_MUTATED_ABOMINATION_10) || summons.HasEntry(NPC_MUTATED_ABOMINATION_25));
default:
break;
}
return 0;
}
void SetData(uint32 id, uint32 data) OVERRIDE
{
if (id == DATA_EXPERIMENT_STAGE)
_experimentState = bool(data);
}
void UpdateAI(uint32 diff) OVERRIDE
{
if ((!(events.IsInPhase(PHASE_ROTFACE) || events.IsInPhase(PHASE_FESTERGUT)) && !UpdateVictim()) || !CheckInRoom())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FESTERGUT_DIES:
Talk(SAY_FESTERGUT_DEATH);
EnterEvadeMode();
break;
case EVENT_FESTERGUT_GOO:
me->CastCustomSpell(SPELL_MALLEABLE_GOO_SUMMON, SPELLVALUE_MAX_TARGETS, 1, NULL, true);
events.ScheduleEvent(EVENT_FESTERGUT_GOO, (Is25ManRaid() ? 10000 : 30000) + urand(0, 5000), 0, PHASE_FESTERGUT);
break;
case EVENT_ROTFACE_DIES:
Talk(SAY_ROTFACE_DEATH);
EnterEvadeMode();
break;
case EVENT_ROTFACE_OOZE_FLOOD:
DoAction(ACTION_ROTFACE_OOZE);
events.ScheduleEvent(EVENT_ROTFACE_OOZE_FLOOD, 25000, 0, PHASE_ROTFACE);
break;
case EVENT_BERSERK:
Talk(SAY_BERSERK);
DoCast(me, SPELL_BERSERK2);
break;
case EVENT_SLIME_PUDDLE:
{
std::list<Unit*> targets;
SelectTargetList(targets, 2, SELECT_TARGET_RANDOM, 0.0f, true);
if (!targets.empty())
for (std::list<Unit*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
DoCast(*itr, SPELL_SLIME_PUDDLE_TRIGGER);
events.ScheduleEvent(EVENT_SLIME_PUDDLE, 35000);
break;
}
case EVENT_UNSTABLE_EXPERIMENT:
Talk(EMOTE_UNSTABLE_EXPERIMENT);
DoCast(me, SPELL_UNSTABLE_EXPERIMENT);
events.ScheduleEvent(EVENT_UNSTABLE_EXPERIMENT, urand(35000, 40000));
break;
case EVENT_TEAR_GAS:
me->GetMotionMaster()->MovePoint(POINT_TABLE, tablePos);
DoCast(me, SPELL_TEAR_GAS_PERIODIC_TRIGGER, true);
break;
case EVENT_RESUME_ATTACK:
me->SetReactState(REACT_DEFENSIVE);
AttackStart(me->GetVictim());
// remove Tear Gas
me->RemoveAurasDueToSpell(SPELL_TEAR_GAS_PERIODIC_TRIGGER);
instance->DoRemoveAurasDueToSpellOnPlayers(71615);
DoCastAOE(SPELL_TEAR_GAS_CANCEL);
instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_GAS_VARIABLE);
instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_OOZE_VARIABLE);
break;
case EVENT_MALLEABLE_GOO:
if (Is25ManRaid())
{
std::list<Unit*> targets;
SelectTargetList(targets, 2, SELECT_TARGET_RANDOM, -7.0f, true);
if (!targets.empty())
{
Talk(EMOTE_MALLEABLE_GOO);
for (std::list<Unit*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
DoCast(*itr, SPELL_MALLEABLE_GOO);
}
}
else
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, -7.0f, true))
{
Talk(EMOTE_MALLEABLE_GOO);
DoCast(target, SPELL_MALLEABLE_GOO);
}
}
events.ScheduleEvent(EVENT_MALLEABLE_GOO, urand(25000, 30000));
break;
case EVENT_CHOKING_GAS_BOMB:
Talk(EMOTE_CHOKING_GAS_BOMB);
DoCast(me, SPELL_CHOKING_GAS_BOMB);
events.ScheduleEvent(EVENT_CHOKING_GAS_BOMB, urand(35000, 40000));
break;
case EVENT_UNBOUND_PLAGUE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, NonTankTargetSelector(me)))
{
DoCast(target, SPELL_UNBOUND_PLAGUE);
DoCast(target, SPELL_UNBOUND_PLAGUE_SEARCHER);
}
events.ScheduleEvent(EVENT_UNBOUND_PLAGUE, 90000);
break;
case EVENT_MUTATED_PLAGUE:
DoCastVictim(SPELL_MUTATED_PLAGUE);
events.ScheduleEvent(EVENT_MUTATED_PLAGUE, 10000);
break;
case EVENT_PHASE_TRANSITION:
{
switch (_phase)
{
case PHASE_COMBAT_2:
if (Creature* face = me->FindNearestCreature(NPC_TEAR_GAS_TARGET_STALKER, 50.0f))
me->SetFacingToObject(face);
me->HandleEmoteCommand(EMOTE_ONESHOT_KNEEL);
Talk(SAY_TRANSFORM_1);
events.ScheduleEvent(EVENT_RESUME_ATTACK, 5500, 0, PHASE_COMBAT_2);
break;
case PHASE_COMBAT_3:
if (Creature* face = me->FindNearestCreature(NPC_TEAR_GAS_TARGET_STALKER, 50.0f))
me->SetFacingToObject(face);
me->HandleEmoteCommand(EMOTE_ONESHOT_KNEEL);
Talk(SAY_TRANSFORM_2);
summons.DespawnIf(AbominationDespawner(me));
events.ScheduleEvent(EVENT_RESUME_ATTACK, 8500, 0, PHASE_COMBAT_3);
break;
default:
break;
}
}
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
void SetPhase(Phases newPhase)
{
_phase = newPhase;
events.SetPhase(newPhase);
}
uint64 _oozeFloodDummyGUIDs[4];
Phases _phase; // external of EventMap because event phase gets reset on evade
float const _baseSpeed;
uint8 _oozeFloodStage;
bool _experimentState;
};
CreatureAI* GetAI(Creature* creature) const OVERRIDE
{
return GetIcecrownCitadelAI<boss_professor_putricideAI>(creature);
}
};
class npc_putricide_oozeAI : public ScriptedAI
{
public:
npc_putricide_oozeAI(Creature* creature, uint32 hitTargetSpellId) : ScriptedAI(creature),
_hitTargetSpellId(hitTargetSpellId), _newTargetSelectTimer(0)
{
}
void SpellHitTarget(Unit* /*target*/, SpellInfo const* spell) OVERRIDE
{
if (!_newTargetSelectTimer && spell->Id == sSpellMgr->GetSpellIdForDifficulty(_hitTargetSpellId, me))
_newTargetSelectTimer = 1000;
}
void SpellHit(Unit* /*caster*/, SpellInfo const* spell) OVERRIDE
{
if (spell->Id == SPELL_TEAR_GAS_CREATURE)
_newTargetSelectTimer = 1000;
}
void UpdateAI(uint32 diff) OVERRIDE
{
if (!UpdateVictim() && !_newTargetSelectTimer)
return;
if (!_newTargetSelectTimer && !me->IsNonMeleeSpellCasted(false, false, true, false, true))
_newTargetSelectTimer = 1000;
DoMeleeAttackIfReady();
if (!_newTargetSelectTimer)
return;
if (me->HasAura(SPELL_TEAR_GAS_CREATURE))
return;
if (_newTargetSelectTimer <= diff)
{
_newTargetSelectTimer = 0;
CastMainSpell();
}
else
_newTargetSelectTimer -= diff;
}
virtual void CastMainSpell() = 0;
private:
uint32 _hitTargetSpellId;
uint32 _newTargetSelectTimer;
};
class npc_volatile_ooze : public CreatureScript
{
public:
npc_volatile_ooze() : CreatureScript("npc_volatile_ooze") { }
struct npc_volatile_oozeAI : public npc_putricide_oozeAI
{
npc_volatile_oozeAI(Creature* creature) : npc_putricide_oozeAI(creature, SPELL_OOZE_ERUPTION)
{
}
void CastMainSpell()
{
me->CastSpell(me, SPELL_VOLATILE_OOZE_ADHESIVE, false);
}
};
CreatureAI* GetAI(Creature* creature) const OVERRIDE
{
return GetIcecrownCitadelAI<npc_volatile_oozeAI>(creature);
}
};
class npc_gas_cloud : public CreatureScript
{
public:
npc_gas_cloud() : CreatureScript("npc_gas_cloud") { }
struct npc_gas_cloudAI : public npc_putricide_oozeAI
{
npc_gas_cloudAI(Creature* creature) : npc_putricide_oozeAI(creature, SPELL_EXPUNGED_GAS)
{
_newTargetSelectTimer = 0;
}
void CastMainSpell()
{
me->CastCustomSpell(SPELL_GASEOUS_BLOAT, SPELLVALUE_AURA_STACK, 10, me, false);
}
private:
uint32 _newTargetSelectTimer;
};
CreatureAI* GetAI(Creature* creature) const OVERRIDE
{
return GetIcecrownCitadelAI<npc_gas_cloudAI>(creature);
}
};
class spell_putricide_gaseous_bloat : public SpellScriptLoader
{
public:
spell_putricide_gaseous_bloat() : SpellScriptLoader("spell_putricide_gaseous_bloat") { }
class spell_putricide_gaseous_bloat_AuraScript : public AuraScript
{
PrepareAuraScript(spell_putricide_gaseous_bloat_AuraScript);
void HandleExtraEffect(AuraEffect const* /*aurEff*/)
{
Unit* target = GetTarget();
if (Unit* caster = GetCaster())
{
target->RemoveAuraFromStack(GetSpellInfo()->Id, GetCasterGUID());
if (!target->HasAura(GetId()))
caster->CastCustomSpell(SPELL_GASEOUS_BLOAT, SPELLVALUE_AURA_STACK, 10, caster, false);
}
}
void Register() OVERRIDE
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_putricide_gaseous_bloat_AuraScript::HandleExtraEffect, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE);
}
};
AuraScript* GetAuraScript() const OVERRIDE
{
return new spell_putricide_gaseous_bloat_AuraScript();
}
};
class spell_putricide_ooze_channel : public SpellScriptLoader
{
public:
spell_putricide_ooze_channel() : SpellScriptLoader("spell_putricide_ooze_channel") { }
class spell_putricide_ooze_channel_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_ooze_channel_SpellScript);
bool Validate(SpellInfo const* spell) OVERRIDE
{
if (!spell->ExcludeTargetAuraSpell)
return false;
if (!sSpellMgr->GetSpellInfo(spell->ExcludeTargetAuraSpell))
return false;
return true;
}
// set up initial variables and check if caster is creature
// this will let use safely use ToCreature() casts in entire script
bool Load() OVERRIDE
{
_target = NULL;
return GetCaster()->GetTypeId() == TypeID::TYPEID_UNIT;
}
void SelectTarget(std::list<WorldObject*>& targets)
{
if (targets.empty())
{
FinishCast(SpellCastResult::SPELL_FAILED_NO_VALID_TARGETS);
GetCaster()->ToCreature()->DespawnOrUnsummon(1); // despawn next update
return;
}
WorldObject* target = Skyfire::Containers::SelectRandomContainerElement(targets);
targets.clear();
targets.push_back(target);
_target = target;
}
void SetTarget(std::list<WorldObject*>& targets)
{
targets.clear();
if (_target)
targets.push_back(_target);
}
void StartAttack()
{
GetCaster()->ClearUnitState(UNIT_STATE_CASTING);
GetCaster()->DeleteThreatList();
GetCaster()->ToCreature()->AI()->AttackStart(GetHitUnit());
GetCaster()->AddThreat(GetHitUnit(), 500000000.0f); // value seen in sniff
}
void Register() OVERRIDE
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_ooze_channel_SpellScript::SelectTarget, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_ooze_channel_SpellScript::SetTarget, EFFECT_1, TARGET_UNIT_SRC_AREA_ENEMY);
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_ooze_channel_SpellScript::SetTarget, EFFECT_2, TARGET_UNIT_SRC_AREA_ENEMY);
AfterHit += SpellHitFn(spell_putricide_ooze_channel_SpellScript::StartAttack);
}
WorldObject* _target;
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_ooze_channel_SpellScript();
}
};
class ExactDistanceCheck
{
public:
ExactDistanceCheck(Unit* source, float dist) : _source(source), _dist(dist) { }
bool operator()(WorldObject* unit) const
{
return _source->GetExactDist2d(unit) > _dist;
}
private:
Unit* _source;
float _dist;
};
class spell_putricide_slime_puddle : public SpellScriptLoader
{
public:
spell_putricide_slime_puddle() : SpellScriptLoader("spell_putricide_slime_puddle") { }
class spell_putricide_slime_puddle_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_slime_puddle_SpellScript);
void ScaleRange(std::list<WorldObject*>& targets)
{
targets.remove_if(ExactDistanceCheck(GetCaster(), 2.5f * GetCaster()->GetObjectScale()));
}
void Register() OVERRIDE
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_slime_puddle_SpellScript::ScaleRange, EFFECT_0, TARGET_UNIT_DEST_AREA_ENEMY);
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_slime_puddle_SpellScript::ScaleRange, EFFECT_1, TARGET_UNIT_DEST_AREA_ENTRY);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_slime_puddle_SpellScript();
}
};
// this is here only because on retail you dont actually enter HEROIC mode for ICC
class spell_putricide_slime_puddle_aura : public SpellScriptLoader
{
public:
spell_putricide_slime_puddle_aura() : SpellScriptLoader("spell_putricide_slime_puddle_aura") { }
class spell_putricide_slime_puddle_aura_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_slime_puddle_aura_SpellScript);
void ReplaceAura()
{
if (Unit* target = GetHitUnit())
GetCaster()->AddAura((GetCaster()->GetMap()->GetSpawnMode() & 1) ? 72456 : 70346, target);
}
void Register() OVERRIDE
{
OnHit += SpellHitFn(spell_putricide_slime_puddle_aura_SpellScript::ReplaceAura);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_slime_puddle_aura_SpellScript();
}
};
class spell_putricide_unstable_experiment : public SpellScriptLoader
{
public:
spell_putricide_unstable_experiment() : SpellScriptLoader("spell_putricide_unstable_experiment") { }
class spell_putricide_unstable_experiment_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_unstable_experiment_SpellScript);
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
if (GetCaster()->GetTypeId() != TypeID::TYPEID_UNIT)
return;
Creature* creature = GetCaster()->ToCreature();
uint32 stage = creature->AI()->GetData(DATA_EXPERIMENT_STAGE);
creature->AI()->SetData(DATA_EXPERIMENT_STAGE, stage ^ true);
Creature* target = NULL;
std::list<Creature*> creList;
GetCreatureListWithEntryInGrid(creList, GetCaster(), NPC_ABOMINATION_WING_MAD_SCIENTIST_STALKER, 200.0f);
// 2 of them are spawned at green place - weird trick blizz
for (std::list<Creature*>::iterator itr = creList.begin(); itr != creList.end(); ++itr)
{
target = *itr;
std::list<Creature*> tmp;
GetCreatureListWithEntryInGrid(tmp, target, NPC_ABOMINATION_WING_MAD_SCIENTIST_STALKER, 10.0f);
if ((!stage && tmp.size() > 1) || (stage && tmp.size() == 1))
break;
}
GetCaster()->CastSpell(target, uint32(GetSpellInfo()->Effects[stage].CalcValue()), true, NULL, NULL, GetCaster()->GetGUID());
}
void Register() OVERRIDE
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_unstable_experiment_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_unstable_experiment_SpellScript();
}
};
class spell_putricide_ooze_eruption_searcher : public SpellScriptLoader
{
public:
spell_putricide_ooze_eruption_searcher() : SpellScriptLoader("spell_putricide_ooze_eruption_searcher") { }
class spell_putricide_ooze_eruption_searcher_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_ooze_eruption_searcher_SpellScript);
void HandleDummy(SpellEffIndex /*effIndex*/)
{
uint32 adhesiveId = sSpellMgr->GetSpellIdForDifficulty(SPELL_VOLATILE_OOZE_ADHESIVE, GetCaster());
if (GetHitUnit()->HasAura(adhesiveId))
{
GetCaster()->CastSpell(GetHitUnit(), SPELL_OOZE_ERUPTION, true);
GetHitUnit()->RemoveAurasDueToSpell(adhesiveId, GetCaster()->GetGUID(), 0, AURA_REMOVE_BY_ENEMY_SPELL);
}
}
void Register() OVERRIDE
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_ooze_eruption_searcher_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_ooze_eruption_searcher_SpellScript();
}
};
class spell_putricide_choking_gas_bomb : public SpellScriptLoader
{
public:
spell_putricide_choking_gas_bomb() : SpellScriptLoader("spell_putricide_choking_gas_bomb") { }
class spell_putricide_choking_gas_bomb_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_choking_gas_bomb_SpellScript);
void HandleScript(SpellEffIndex /*effIndex*/)
{
uint32 skipIndex = urand(0, 2);
for (uint32 i = 0; i < 3; ++i)
{
if (i == skipIndex)
continue;
uint32 spellId = uint32(GetSpellInfo()->Effects[i].CalcValue());
GetCaster()->CastSpell(GetCaster(), spellId, true, NULL, NULL, GetCaster()->GetGUID());
}
}
void Register() OVERRIDE
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_choking_gas_bomb_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_choking_gas_bomb_SpellScript();
}
};
class spell_putricide_unbound_plague : public SpellScriptLoader
{
public:
spell_putricide_unbound_plague() : SpellScriptLoader("spell_putricide_unbound_plague") { }
class spell_putricide_unbound_plague_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_unbound_plague_SpellScript);
bool Validate(SpellInfo const* /*spell*/) OVERRIDE
{
if (!sSpellMgr->GetSpellInfo(SPELL_UNBOUND_PLAGUE))
return false;
if (!sSpellMgr->GetSpellInfo(SPELL_UNBOUND_PLAGUE_SEARCHER))
return false;
return true;
}
void FilterTargets(std::list<WorldObject*>& targets)
{
if (AuraEffect const* eff = GetCaster()->GetAuraEffect(SPELL_UNBOUND_PLAGUE_SEARCHER, EFFECT_0))
{
if (eff->GetTickNumber() < 2)
{
targets.clear();
return;
}
}
targets.remove_if(Skyfire::UnitAuraCheck(true, sSpellMgr->GetSpellIdForDifficulty(SPELL_UNBOUND_PLAGUE, GetCaster())));
Skyfire::Containers::RandomResizeList(targets, 1);
}
void HandleScript(SpellEffIndex /*effIndex*/)
{
if (!GetHitUnit())
return;
InstanceScript* instance = GetCaster()->GetInstanceScript();
if (!instance)
return;
uint32 plagueId = sSpellMgr->GetSpellIdForDifficulty(SPELL_UNBOUND_PLAGUE, GetCaster());
if (!GetHitUnit()->HasAura(plagueId))
{
if (Creature* professor = ObjectAccessor::GetCreature(*GetCaster(), instance->GetData64(DATA_PROFESSOR_PUTRICIDE)))
{
if (Aura* oldPlague = GetCaster()->GetAura(plagueId, professor->GetGUID()))
{
if (Aura* newPlague = professor->AddAura(plagueId, GetHitUnit()))
{
newPlague->SetMaxDuration(oldPlague->GetMaxDuration());
newPlague->SetDuration(oldPlague->GetDuration());
oldPlague->Remove();
GetCaster()->RemoveAurasDueToSpell(SPELL_UNBOUND_PLAGUE_SEARCHER);
GetCaster()->CastSpell(GetCaster(), SPELL_PLAGUE_SICKNESS, true);
GetCaster()->CastSpell(GetCaster(), SPELL_UNBOUND_PLAGUE_PROTECTION, true);
professor->CastSpell(GetHitUnit(), SPELL_UNBOUND_PLAGUE_SEARCHER, true);
}
}
}
}
}
void Register() OVERRIDE
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_unbound_plague_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ALLY);
OnEffectHitTarget += SpellEffectFn(spell_putricide_unbound_plague_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_unbound_plague_SpellScript();
}
};
class spell_putricide_eat_ooze : public SpellScriptLoader
{
public:
spell_putricide_eat_ooze() : SpellScriptLoader("spell_putricide_eat_ooze") { }
class spell_putricide_eat_ooze_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_eat_ooze_SpellScript);
void SelectTarget(std::list<WorldObject*>& targets)
{
if (targets.empty())
return;
targets.sort(Skyfire::ObjectDistanceOrderPred(GetCaster()));
WorldObject* target = targets.front();
targets.clear();
targets.push_back(target);
}
void HandleScript(SpellEffIndex /*effIndex*/)
{
Creature* target = GetHitCreature();
if (!target)
return;
if (Aura* grow = target->GetAura(uint32(GetEffectValue())))
{
if (grow->GetStackAmount() < 3)
{
target->RemoveAurasDueToSpell(SPELL_GROW_STACKER);
target->RemoveAura(grow);
target->DespawnOrUnsummon(1);
}
else
grow->ModStackAmount(-3);
}
}
void Register() OVERRIDE
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_eat_ooze_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_eat_ooze_SpellScript::SelectTarget, EFFECT_0, TARGET_UNIT_DEST_AREA_ENTRY);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_eat_ooze_SpellScript();
}
};
class spell_putricide_mutated_plague : public SpellScriptLoader
{
public:
spell_putricide_mutated_plague() : SpellScriptLoader("spell_putricide_mutated_plague") { }
class spell_putricide_mutated_plague_AuraScript : public AuraScript
{
PrepareAuraScript(spell_putricide_mutated_plague_AuraScript);
void HandleTriggerSpell(AuraEffect const* aurEff)
{
PreventDefaultAction();
Unit* caster = GetCaster();
if (!caster)
return;
uint32 triggerSpell = GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell;
SpellInfo const* spell = sSpellMgr->GetSpellInfo(triggerSpell);
spell = sSpellMgr->GetSpellForDifficultyFromSpell(spell, caster);
int32 damage = spell->Effects[EFFECT_0].CalcValue(caster);
float multiplier = 2.0f;
if (GetTarget()->GetMap()->GetSpawnMode() & 1)
multiplier = 3.0f;
damage *= int32(pow(multiplier, GetStackAmount()));
damage = int32(damage * 1.5f);
GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_BASE_POINT0, damage, GetTarget(), true, NULL, aurEff, GetCasterGUID());
}
void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
uint32 healSpell = uint32(GetSpellInfo()->Effects[EFFECT_0].CalcValue());
GetTarget()->CastSpell(GetTarget(), healSpell, true, NULL, NULL, GetCasterGUID());
}
void Register() OVERRIDE
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_putricide_mutated_plague_AuraScript::HandleTriggerSpell, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL);
AfterEffectRemove += AuraEffectRemoveFn(spell_putricide_mutated_plague_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL);
}
};
AuraScript* GetAuraScript() const OVERRIDE
{
return new spell_putricide_mutated_plague_AuraScript();
}
};
class spell_putricide_mutation_init : public SpellScriptLoader
{
public:
spell_putricide_mutation_init() : SpellScriptLoader("spell_putricide_mutation_init") { }
class spell_putricide_mutation_init_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_mutation_init_SpellScript);
SpellCastResult CheckRequirementInternal(SpellCustomErrors& extendedError)
{
InstanceScript* instance = GetExplTargetUnit()->GetInstanceScript();
if (!instance)
return SpellCastResult::SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW;
Creature* professor = ObjectAccessor::GetCreature(*GetExplTargetUnit(), instance->GetData64(DATA_PROFESSOR_PUTRICIDE));
if (!professor)
return SpellCastResult::SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW;
if (professor->AI()->GetData(DATA_PHASE) == PHASE_COMBAT_3 || !professor->IsAlive())
{
extendedError = SPELL_CUSTOM_ERROR_ALL_POTIONS_USED;
return SpellCastResult::SPELL_FAILED_CUSTOM_ERROR;
}
if (professor->AI()->GetData(DATA_ABOMINATION))
{
extendedError = SPELL_CUSTOM_ERROR_TOO_MANY_ABOMINATIONS;
return SpellCastResult::SPELL_FAILED_CUSTOM_ERROR;
}
return SpellCastResult::SPELL_CAST_OK;
}
SpellCastResult CheckRequirement()
{
if (!GetExplTargetUnit())
return SpellCastResult::SPELL_FAILED_BAD_TARGETS;
if (GetExplTargetUnit()->GetTypeId() != TypeID::TYPEID_PLAYER)
return SpellCastResult::SPELL_FAILED_TARGET_NOT_PLAYER;
SpellCustomErrors extension = SPELL_CUSTOM_ERROR_NONE;
SpellCastResult result = CheckRequirementInternal(extension);
if (result != SpellCastResult::SPELL_CAST_OK)
{
Spell::SendCastResult(GetExplTargetUnit()->ToPlayer(), GetSpellInfo(), 0, result, extension);
return result;
}
return SpellCastResult::SPELL_CAST_OK;
}
void Register() OVERRIDE
{
OnCheckCast += SpellCheckCastFn(spell_putricide_mutation_init_SpellScript::CheckRequirement);
}
};
class spell_putricide_mutation_init_AuraScript : public AuraScript
{
PrepareAuraScript(spell_putricide_mutation_init_AuraScript);
void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
uint32 spellId = 70311;
if (GetTarget()->GetMap()->GetSpawnMode() & 1)
spellId = 71503;
GetTarget()->CastSpell(GetTarget(), spellId, true);
}
void Register() OVERRIDE
{
AfterEffectRemove += AuraEffectRemoveFn(spell_putricide_mutation_init_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_mutation_init_SpellScript();
}
AuraScript* GetAuraScript() const OVERRIDE
{
return new spell_putricide_mutation_init_AuraScript();
}
};
class spell_putricide_mutated_transformation_dismiss : public SpellScriptLoader
{
public:
spell_putricide_mutated_transformation_dismiss() : SpellScriptLoader("spell_putricide_mutated_transformation_dismiss") { }
class spell_putricide_mutated_transformation_dismiss_AuraScript : public AuraScript
{
PrepareAuraScript(spell_putricide_mutated_transformation_dismiss_AuraScript);
void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
if (Vehicle* veh = GetTarget()->GetVehicleKit())
veh->RemoveAllPassengers();
}
void Register() OVERRIDE
{
AfterEffectRemove += AuraEffectRemoveFn(spell_putricide_mutated_transformation_dismiss_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL);
}
};
AuraScript* GetAuraScript() const OVERRIDE
{
return new spell_putricide_mutated_transformation_dismiss_AuraScript();
}
};
class spell_putricide_mutated_transformation : public SpellScriptLoader
{
public:
spell_putricide_mutated_transformation() : SpellScriptLoader("spell_putricide_mutated_transformation") { }
class spell_putricide_mutated_transformation_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_mutated_transformation_SpellScript);
void HandleSummon(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
Unit* caster = GetOriginalCaster();
if (!caster)
return;
InstanceScript* instance = caster->GetInstanceScript();
if (!instance)
return;
Creature* putricide = ObjectAccessor::GetCreature(*caster, instance->GetData64(DATA_PROFESSOR_PUTRICIDE));
if (!putricide)
return;
if (putricide->AI()->GetData(DATA_ABOMINATION))
{
if (Player* player = caster->ToPlayer())
Spell::SendCastResult(player, GetSpellInfo(), 0, SpellCastResult::SPELL_FAILED_CUSTOM_ERROR, SPELL_CUSTOM_ERROR_TOO_MANY_ABOMINATIONS);
return;
}
uint32 entry = uint32(GetSpellInfo()->Effects[effIndex].MiscValue);
SummonPropertiesEntry const* properties = sSummonPropertiesStore.LookupEntry(uint32(GetSpellInfo()->Effects[effIndex].MiscValueB));
uint32 duration = uint32(GetSpellInfo()->GetDuration());
Position pos;
caster->GetPosition(&pos);
TempSummon* summon = caster->GetMap()->SummonCreature(entry, pos, properties, duration, caster, GetSpellInfo()->Id);
if (!summon || !summon->IsVehicle())
return;
summon->CastSpell(summon, SPELL_ABOMINATION_VEHICLE_POWER_DRAIN, true);
summon->CastSpell(summon, SPELL_MUTATED_TRANSFORMATION_DAMAGE, true);
caster->CastSpell(summon, SPELL_MUTATED_TRANSFORMATION_NAME, true);
caster->EnterVehicle(summon, 0); // VEHICLE_SPELL_RIDE_HARDCODED is used according to sniff, this is ok
summon->SetCreatorGUID(caster->GetGUID());
putricide->AI()->JustSummoned(summon);
}
void Register() OVERRIDE
{
OnEffectHit += SpellEffectFn(spell_putricide_mutated_transformation_SpellScript::HandleSummon, EFFECT_0, SPELL_EFFECT_SUMMON);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_mutated_transformation_SpellScript();
}
};
class spell_putricide_mutated_transformation_dmg : public SpellScriptLoader
{
public:
spell_putricide_mutated_transformation_dmg() : SpellScriptLoader("spell_putricide_mutated_transformation_dmg") { }
class spell_putricide_mutated_transformation_dmg_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_mutated_transformation_dmg_SpellScript);
void FilterTargetsInitial(std::list<WorldObject*>& targets)
{
if (Unit* owner = ObjectAccessor::GetUnit(*GetCaster(), GetCaster()->GetCreatorGUID()))
targets.remove(owner);
}
void Register() OVERRIDE
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_mutated_transformation_dmg_SpellScript::FilterTargetsInitial, EFFECT_0, TARGET_UNIT_SRC_AREA_ALLY);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_mutated_transformation_dmg_SpellScript();
}
};
class spell_putricide_regurgitated_ooze : public SpellScriptLoader
{
public:
spell_putricide_regurgitated_ooze() : SpellScriptLoader("spell_putricide_regurgitated_ooze") { }
class spell_putricide_regurgitated_ooze_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_regurgitated_ooze_SpellScript);
// the only purpose of this hook is to fail the achievement
void ExtraEffect(SpellEffIndex /*effIndex*/)
{
if (InstanceScript* instance = GetCaster()->GetInstanceScript())
instance->SetData(DATA_NAUSEA_ACHIEVEMENT, uint32(false));
}
void Register() OVERRIDE
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_regurgitated_ooze_SpellScript::ExtraEffect, EFFECT_0, SPELL_EFFECT_APPLY_AURA);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_regurgitated_ooze_SpellScript();
}
};
// Removes aura with id stored in effect value
class spell_putricide_clear_aura_effect_value : public SpellScriptLoader
{
public:
spell_putricide_clear_aura_effect_value() : SpellScriptLoader("spell_putricide_clear_aura_effect_value") { }
class spell_putricide_clear_aura_effect_value_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_clear_aura_effect_value_SpellScript);
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
uint32 auraId = sSpellMgr->GetSpellIdForDifficulty(uint32(GetEffectValue()), GetCaster());
GetHitUnit()->RemoveAurasDueToSpell(auraId);
}
void Register() OVERRIDE
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_clear_aura_effect_value_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_putricide_clear_aura_effect_value_SpellScript();
}
};
// Stinky and Precious spell, it's here because its used for both (Festergut and Rotface "pets")
class spell_stinky_precious_decimate : public SpellScriptLoader
{
public:
spell_stinky_precious_decimate() : SpellScriptLoader("spell_stinky_precious_decimate") { }
class spell_stinky_precious_decimate_SpellScript : public SpellScript
{
PrepareSpellScript(spell_stinky_precious_decimate_SpellScript);
void HandleScript(SpellEffIndex /*effIndex*/)
{
if (GetHitUnit()->GetHealthPct() > float(GetEffectValue()))
{
uint32 newHealth = GetHitUnit()->GetMaxHealth() * uint32(GetEffectValue()) / 100;
GetHitUnit()->SetHealth(newHealth);
}
}
void Register() OVERRIDE
{
OnEffectHitTarget += SpellEffectFn(spell_stinky_precious_decimate_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const OVERRIDE
{
return new spell_stinky_precious_decimate_SpellScript();
}
};
void AddSC_boss_professor_putricide()
{
new boss_professor_putricide();
new npc_volatile_ooze();
new npc_gas_cloud();
new spell_putricide_gaseous_bloat();
new spell_putricide_ooze_channel();
new spell_putricide_slime_puddle();
new spell_putricide_slime_puddle_aura();
new spell_putricide_unstable_experiment();
new spell_putricide_ooze_eruption_searcher();
new spell_putricide_choking_gas_bomb();
new spell_putricide_unbound_plague();
new spell_putricide_eat_ooze();
new spell_putricide_mutated_plague();
new spell_putricide_mutation_init();
new spell_putricide_mutated_transformation_dismiss();
new spell_putricide_mutated_transformation();
new spell_putricide_mutated_transformation_dmg();
new spell_putricide_regurgitated_ooze();
new spell_putricide_clear_aura_effect_value();
new spell_stinky_precious_decimate();
}
| ProjectSkyfire/SkyFire.548 | src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp | C++ | gpl-2.0 | 66,166 |
<?php
/**
* @file
* Contains \Drupal\faq\Form\QuestionsForm.
*/
namespace Drupal\faq\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Form for the FAQ settings page - questions tab.
*/
class QuestionsForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'faq_questions_settings_form';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$faq_settings = $this->config('faq.settings');
$display_options['questions_inline'] = $this->t('Questions inline');
$display_options['questions_top'] = $this->t('Clicking on question takes user to answer further down the page');
$display_options['hide_answer'] = $this->t('Clicking on question opens/hides answer under question');
$display_options['new_page'] = $this->t('Clicking on question opens the answer in a new page');
$form['faq_display'] = array(
'#type' => 'radios',
'#options' => $display_options,
'#title' => $this->t('Page layout'),
'#description' => $this->t('This controls how the questions and answers are displayed on the page and what happens when someone clicks on the question.'),
'#default_value' => $faq_settings->get('display')
);
$form['faq_questions_misc'] = array(
'#type' => 'details',
'#title' => $this->t('Miscellaneous layout settings'),
'#open' => TRUE
);
$form['faq_questions_misc']['faq_question_listing'] = array(
'#type' => 'select',
'#options' => array(
'ol' => $this->t('Ordered list'),
'ul' => $this->t('Unordered list'),
),
'#title' => $this->t('Questions listing style'),
'#description' => $this->t("This allows to select how the questions listing is presented. It only applies to the layouts: 'Clicking on question takes user to answer further down the page' and 'Clicking on question opens the answer in a new page'. An ordered listing would number the questions, whereas an unordered list will have a bullet to the left of each question."),
'#default_value' => $faq_settings->get('question_listing')
);
$form['faq_questions_misc']['faq_qa_mark'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Label questions and answers'),
'#description' => $this->t('This option is only valid for the "Questions Inline" and "Clicking on question takes user to answer further down the page" layouts. It labels all questions on the faq page with the "question label" setting and all answers with the "answer label" setting. For example these could be set to "Q:" and "A:".'),
'#default_value' => $faq_settings->get('qa_mark')
);
$form['faq_questions_misc']['faq_question_label'] = array(
'#type' => 'textfield',
'#title' => $this->t('Question Label'),
'#description' => $this->t('The label to pre-pend to the question text in the "Questions Inline" layout if labelling is enabled.'),
'#default_value' => $faq_settings->get('question_label')
);
$form['faq_questions_misc']['faq_answer_label'] = array(
'#type' => 'textfield',
'#title' => $this->t('Answer Label'),
'#description' => $this->t('The label to pre-pend to the answer text in the "Questions Inline" layout if labelling is enabled.'),
'#default_value' => $faq_settings->get('answer_label')
);
$form['faq_questions_misc']['faq_question_length'] = array(
'#type' => 'radios',
'#title' => $this->t('Question length'),
'#options' => array(
'long' => $this->t('Display longer text'),
'short' => $this->t('Display short text'),
'both' => $this->t('Display both short and long questions'),
),
'#description' => t("The length of question text to display on the FAQ page. The short question will always be displayed in the FAQ blocks."),
'#default_value' => $faq_settings->get('question_length')
);
$form['faq_questions_misc']['faq_question_long_form'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Allow long question text to be configured'),
'#default_value' => $faq_settings->get('question_long_form')
);
$form['faq_questions_misc']['faq_hide_qa_accordion'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Use accordion effect for "opens/hides answer under question" layout'),
'#description' => $this->t('This enables an "accordion" style effect where when a question is clicked, the answer appears beneath, and is then hidden when another question is opened.'),
'#default_value' => $faq_settings->get('hide_qa_accordion')
);
$form['faq_questions_misc']['faq_show_expand_all'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Show "expand / collapse all" links for collapsed questions'),
'#description' => $this->t('The links will only be displayed if using the "opens/hides answer under question" or "opens/hides questions and answers under category" layouts.'),
'#default_value' => $faq_settings->get('show_expand_all')
);
$form['faq_questions_misc']['faq_use_teaser'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Use answer teaser'),
'#description' => t("This enables the display of the answer teaser text instead of the full answer when using the 'Questions inline' or 'Clicking on question takes user to answer further down the page' display options. This is useful when you have long descriptive text. The user can see the full answer by clicking on the question."),
'#default_value' => $faq_settings->get('use_teaser')
);
// This setting has no meaning in D8 since comments are fields and read more link depends on view mode settings
//$form['faq_questions_misc']['faq_show_node_links'] = array(
// '#type' => 'checkbox',
// '#title' => $this->t('Show node links'),
// '#description' => $this->t('This enables the display of links under the answer text on the faq page. Examples of these links include "Read more", "Add comment".'),
// '#default_value' => $faq_settings->get('show_node_links')
//);
$form['faq_questions_misc']['faq_back_to_top'] = array(
'#type' => 'textfield',
'#title' => $this->t('"Back to Top" link text'),
'#description' => $this->t('This allows the user to change the text displayed for the links which return the user to the top of the page on certain page layouts. Defaults to "Back to Top". Leave blank to have no link.'),
'#default_value' => $faq_settings->get('back_to_top')
);
$form['faq_questions_misc']['faq_disable_node_links'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Disable question links to nodes'),
'#description' => $this->t('This allows the user to prevent the questions being links to the faq node in all layouts except "Clicking on question opens the answer in a new page".'),
'#default_value' => $faq_settings->get('disable_node_links'),
);
$form['faq_questions_misc']['faq_default_sorting'] = array(
'#type' => 'select',
'#title' => $this->t('Default sorting for unordered FAQs'),
'#options' => array(
'DESC' => $this->t('Date Descending'),
'ASC' => $this->t('Date Ascending'),
),
'#description' => t("This controls the default ordering behaviour for new FAQ nodes which haven't been assigned a position."),
'#default_value' => $faq_settings->get('default_sorting')
);
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Remove unnecessary values.
$form_state->cleanValues();
$this->configFactory()->getEditable('faq.settings')
->set('display', $form_state->getValue('faq_display'))
->set('question_listing', $form_state->getValue('faq_question_listing'))
->set('qa_mark', $form_state->getValue('faq_qa_mark'))
->set('question_label', $form_state->getValue('faq_question_label'))
->set('answer_label', $form_state->getValue('faq_answer_label'))
->set('question_length', $form_state->getValue('faq_question_length'))
->set('question_long_form', $form_state->getValue('faq_question_long_form'))
->set('hide_qa_accordion', $form_state->getValue('faq_hide_qa_accordion'))
->set('show_expand_all', $form_state->getValue('faq_show_expand_all'))
->set('use_teaser', $form_state->getValue('faq_use_teaser'))
->set('back_to_top', $form_state->getValue('faq_back_to_top'))
->set('disable_node_links', $form_state->getValue('faq_disable_node_links'))
->set('default_sorting', $form_state->getValue('faq_default_sorting'))
->save();
parent::submitForm($form, $form_state);
}
}
| psunthar/intapp | docroot/modules/contrib/faq/src/Form/QuestionsForm.php | PHP | gpl-2.0 | 8,970 |
<?php
if (cfr('CAPAB')) {
$altercfg = rcms_parse_ini_file(CONFIG_PATH . "alter.ini");
if ($altercfg['CAPABDIR_ENABLED']) {
$capabilities = new CapabilitiesDirectory();
//process deletion
if (wf_CheckGet(array('delete'))) {
if (cfr('ROOT')) {
$capabilities->deleteCapability($_GET['delete']);
rcms_redirect("?module=capabilities");
} else {
show_error(__('Permission denied'));
}
}
//process creation
if (wf_CheckPost(array('newaddress', 'newphone'))) {
$newaddress = $_POST['newaddress'];
$newphone = $_POST['newphone'];
@$newnotes = $_POST['newnotes'];
$capabilities->addCapability($newaddress, $newphone, $newnotes);
rcms_redirect("?module=capabilities");
}
//show editing form
if (wf_CheckGet(array('edit'))) {
//editing processing
if (wf_CheckPost(array('editaddress', 'editphone'))) {
$capabilities->editCapability($_GET['edit'], $_POST['editaddress'], $_POST['editphone'], $_POST['editstateid'], @$_POST['editnotes'], @$_POST['editprice'], $_POST['editemployeeid']);
rcms_redirect("?module=capabilities");
}
show_window(__('Edit'), $capabilities->editForm($_GET['edit']));
}
//show current states editor
if (wf_CheckGet(array('states'))) {
//creating new state
if (wf_CheckPost(array('createstate', 'createstatecolor'))) {
$capabilities->statesCreate($_POST['createstate'], $_POST['createstatecolor']);
rcms_redirect("?module=capabilities&states=true");
}
//deleting existing state
if (wf_CheckGet(array('deletestate'))) {
$capabilities->statesDelete($_GET['deletestate']);
rcms_redirect("?module=capabilities&states=true");
}
if (!wf_CheckGet(array('editstate'))) {
show_window(__('Create new states'), $capabilities->statesAddForm());
show_window(__('Available states'), $capabilities->statesList());
} else {
//editing of existing states
if (wf_CheckPost(array('editstate', 'editstatecolor'))) {
$capabilities->statesChange($_GET['editstate'], $_POST['editstate'], $_POST['editstatecolor']);
rcms_redirect("?module=capabilities&states=true");
}
show_window(__('Edit'), $capabilities->statesEditForm($_GET['editstate']));
}
}
//show available
if (!wf_CheckGet(array('edit'))) {
if (!wf_CheckGet(array('states'))) {
show_window(__('Available connection capabilities'), $capabilities->render());
}
}
} else {
show_error(__('This module is disabled'));
}
} else {
show_error(__('You cant control this module'));
}
?>
| mehulsbhatt/Ubilling | modules/general/capabilities/index.php | PHP | gpl-2.0 | 3,022 |
<?php // $Id: fieldset.tpl.php,v 1.1.2.3.2.1 2010/11/24 21:31:56 adrinux Exp $ ?>
<?php print $pre; ?>
<div <?php print drupal_attributes($attributes_array); ?>>
<?php if ($title): ?>
<h2 class='fieldset-title'>
<?php print $title; ?>
</h2>
<?php endif; ?>
<?php if ($content): ?>
<div class='fieldset-content clearfix'>
<?php print $content; ?>
</div>
<?php endif; ?>
</div>
<?php print $post; ?>
| google-code/app7 | sites/all/themes/clean/fieldset.tpl.php | PHP | gpl-2.0 | 438 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_weblinks
*
* @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
use \AcceptanceTester;
class AdministratorWeblinksCest
{
private $title;
public function __construct()
{
// This way works just fine, but not 100% sure if that is the recommended way:
$this->title = 'automated testing' . rand(1,100);
}
public function administratorCreateWeblink(AcceptanceTester $I)
{
$I->am('Administrator');
$I->wantToTest('Weblink creation in /administrator/');
$I->doAdministratorLogin();
$I->amGoingTo('Navigate to Weblinks page in /administrator/');
$I->amOnPage('administrator/index.php?option=com_weblinks');
$I->waitForText('Web Links Manager: Web Links','5',['css' => 'h1']);
$I->expectTo('see weblinks page');
$I->checkForPhpNoticesOrWarnings();
$I->amGoingTo('try to save a weblink with a filled title and URL');
$I->click(['xpath'=> "//button[@onclick=\"Joomla.submitbutton('weblink.add')\"]"]);
$I->waitForText('Web Links Manager: Web Link','5',['css' => 'h1']);
$I->fillField(['id' => 'jform_title'], $this->title);
$I->fillField(['id' => 'jform_url'],'http://example.com/automated_testing' . $this->title);
$I->click(['xpath'=> "//button[@onclick=\"Joomla.submitbutton('weblink.save')\"]"]);
$I->waitForText('Web Links Manager: Web Link','5',['css' => 'h1']);
$I->expectTo('see a success message and the weblink added after saving the weblink');
$I->see('Web link successfully saved',['id' => 'system-message-container']);
$I->see($this->title,['id' => 'weblinkList']);
}
/**
* @depends administratorCreateWeblink
*
* @param AcceptanceTester $I
*/
public function administratorCreateWeblinkTrash(AcceptanceTester $I)
{
$I->am('Administrator');
$I->wantToTest('Weblink removal in /administrator/');
$I->doAdministratorLogin();
$I->amGoingTo('Navigate to Weblinks page in /administrator/');
$I->amOnPage('administrator/index.php?option=com_weblinks');
$I->waitForText('Web Links Manager: Web Links','5',['css' => 'h1']);
$I->expectTo('see weblinks page');
$I->checkForPhpNoticesOrWarnings();
$I->amGoingTo('Search the just saved weblink');
$I->fillField(['id' => 'filter_search'], $this->title . "\n");
$I->waitForText('Web Links Manager: Web Links','5',['css' => 'h1']);
$I->expectTo('see weblinks page');
$I->checkForPhpNoticesOrWarnings();
$I->amGoingTo('Delete the just saved weblink');
$I->click(['id' => 'cb0']);
$I->click(['xpath'=> "//button[@onclick=\"if (document.adminForm.boxchecked.value==0){alert('Please first make a selection from the list');}else{ Joomla.submitbutton('weblinks.trash')}\"]"]);
$I->waitForText('Web Links Manager: Web Link','5',['css' => 'h1']);
$I->expectTo('see a success message and the weblink removed from the list');
$I->see('Web link successfully trashed',['id' => 'system-message-container']);
$I->cantSee($this->title,['id' => 'weblinkList']);
}
public function administratorCreateWeblinkWithoutTitleFails(AcceptanceTester $I)
{
$I->am('Administrator');
$I->wantToTest('Weblink creation without title fails in /administrator/');
$I->doAdministratorLogin();
$I->amGoingTo('Navigate to Weblinks page in /administrator/');
$I->amOnPage('administrator/index.php?option=com_weblinks');
$I->waitForText('Web Links Manager: Web Links','5',['css' => 'h1']);
$I->expectTo('see weblinks page');
$I->checkForPhpNoticesOrWarnings();
$I->amGoingTo('try to save a weblink with empty title and it should fail');
$I->click(['xpath'=> "//button[@onclick=\"Joomla.submitbutton('weblink.add')\"]"]);
$I->waitForText('Web Links Manager: Web Link','5',['css' => 'h1']);
$I->click(['xpath'=> "//button[@onclick=\"Joomla.submitbutton('weblink.apply')\"]"]);
$I->expectTo('see an error when trying to save a weblink without title and without URL');
$I->see('Invalid field: Title',['id' => 'system-message-container']);
$I->see('Invalid field: URL',['id' => 'system-message-container']);
}
} | javigomez/weblinks | tests/acceptance/AdministratorWeblinksCest.php | PHP | gpl-2.0 | 4,140 |
<article id="post-<?php the_ID(); ?>" <?php post_class('post__holder'); ?>>
<?php formaticons(); ?>
<header class="post-header">
<?php if(!is_singular()) : ?>
<h2 class="post-title"><a href="<?php the_permalink(); ?>" title="<?php echo theme_locals('permalink_to');?> <?php the_title(); ?>"><?php the_title(); ?></a></h2>
<?php else :?>
<h2 class="post-title"><?php the_title(); ?></h2>
<?php endif; ?>
</header>
<?php $post_meta = of_get_option('post_meta');
if ($post_meta=='true' || $post_meta=='') {
get_template_part('includes/post-formats/post-meta');
} ?>
<?php
$hercules_gallery_type = get_post_meta(get_the_ID(), 'tz_gallery_format', true);
$hercules_targetheight = get_post_meta(get_the_ID(), 'tz_gallery_targetheight', true);
$hercules_gallery_margins = get_post_meta(get_the_ID(), 'tz_gallery_margins', true);
$hercules_gallery_captions = get_post_meta(get_the_ID(), 'tz_gallery_captions', true);
$hercules_gallery_randomize = get_post_meta(get_the_ID(), 'tz_gallery_randomize', true);
$hercules_random = hs_gener_random(10);
?>
<div class="post-thumb clearfix">
<?php if ($hercules_gallery_type=='slideshow') {
global $hercules_add_owl;
$hercules_add_owl = true; ?>
<script type="text/javascript">
jQuery(window).load(function() {
jQuery("#owl-demo_<?php echo $hercules_random ?>").owlCarousel({
autoPlay : 5000,
stopOnHover : true,
navigation:false,
//items : 2,
paginationSpeed : 5000,
goToFirstSpeed : 2000,
singleItem : true,
autoHeight : false,
transitionStyle:"fade"
});
});
</script>
<!-- Slider -->
<div id="owl-demo_<?php echo $hercules_random ?>" class="owl-carousel">
<?php
$hercules_attachments = get_children(array('post_parent' => get_the_ID(), 'numberposts' => -1, 'post_type' => 'attachment', 'post_mime_type' => 'image' ));
if ($hercules_attachments) :
foreach ($hercules_attachments as $attachment) :
?>
<div class="featured-thumbnail thumbnail large"><?php echo wp_get_attachment_image($attachment->ID, 'slideshow-post'); ?></div>
<?php
endforeach;
endif;
?>
</div>
<!-- /Slider -->
<?php } ?>
<!-- Grid -->
<?php if ($hercules_gallery_type=='grid') {
global $hercules_add_collageplus;
$hercules_add_collageplus = true;
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery(".justifiedgall_<?php echo $hercules_random ?>").justifiedGallery({
rowHeight: <?php if( ! empty( $hercules_targetheight ) ) {echo $hercules_targetheight;}else{echo '400';} ?>,
fixedHeight: false,
lastRow: 'justify',
captions : <?php if( ! empty( $hercules_gallery_captions ) ) {echo $hercules_gallery_captions;}else{echo 'true';} ?>,
margins: <?php if( ! empty( $hercules_gallery_margins ) ) {echo $hercules_gallery_margins;}else{echo '10';} ?>,
randomize: <?php if( ! empty( $hercules_targetheight ) ) {echo $hercules_gallery_randomize;}else{echo 'false';} ?>
}); });
</script>
<div class="zoom-gallery justifiedgall_<?php echo $hercules_random ?>" style="margin: 0px 0px 1.5em;">
<div class="spinner"><span></span><span></span><span></span></div>
<?php
$hercules_attachments = get_children(array('post_parent' => get_the_ID(), 'numberposts' => -1, 'post_type' => 'attachment', 'post_mime_type' => 'image' ));
if ($hercules_attachments) :
foreach ($hercules_attachments as $attachment) :
$attachment_url = wp_get_attachment_image_src( $attachment->ID, 'full' );
$caption = apply_filters('the_title', $attachment->post_excerpt);
?>
<a class="zoomer" title="<?php echo apply_filters('the_title', $attachment->post_excerpt); ?>" data-source="<?php echo $attachment_url[0]; ?>" href="<?php echo $attachment_url[0]; ?>"><?php echo wp_get_attachment_image($attachment->ID, 'full'); ?></a>
<?php
endforeach;
endif;
?>
</div>
<?php } ?>
<!-- /Grid -->
<div class="row-fluid">
<div class="span12">
<?php
$full_content = of_get_option('full_content');
if(!is_singular() && $full_content!='true') : ?>
<!-- Post Content -->
<div class="post_content">
<?php $post_excerpt = of_get_option('post_excerpt');
$blog_excerpt = of_get_option('blog_excerpt_count'); ?>
<?php if ($post_excerpt=='true') { ?>
<div class="excerpt">
<?php
$content = get_the_content();
if (has_excerpt()) {
the_excerpt();
} else {
echo limit_text($content,$blog_excerpt);
} ?>
</div>
<?php } else if ($post_excerpt=='') {
the_content('<div class="readmore-button">'.theme_locals("continue_reading").'</div>');
wp_link_pages('before=<div class="pagelink">&after=</div>'); ?>
<div class="clear"></div>
<?php } ?>
<?php $readmore_button = of_get_option('readmore_button');
if ($readmore_button=='yes') { ?>
<div class="readmore-button">
<a href="<?php the_permalink() ?>" class=""><?php echo theme_locals("continue_reading"); ?></a>
</div>
<div class="clear"></div>
<?php } ?>
</div>
<?php else :?>
<!-- Post Content -->
<div class="post_content">
<?php the_content('<div class="readmore-button">'.theme_locals("continue_reading").'</div>'); ?>
<?php wp_link_pages('before=<div class="pagelink">&after=</div>'); ?>
<div class="clear"></div>
</div>
<!-- //Post Content -->
<?php endif; ?>
</div> </div>
</div>
<?php get_template_part( 'includes/post-formats/share-buttons' ); ?>
</article><!--//.post__holder--> | FelixNong1990/andy | wp-content/themes/BUZZBLOG-theme/includes/post-formats/gallery.php | PHP | gpl-2.0 | 5,576 |
#!/usr/bin/python
#GraphML-Topo-to-Mininet-Network-Generator
#
# This file parses Network Topologies in GraphML format from the Internet Topology Zoo.
# A python file for creating Mininet Topologies will be created as Output.
# Files have to be in the same directory.
#
# Arguments:
# -f [filename of GraphML input file]
# --file [filename of GraphML input file]
# -o [filename of GraphML output file]
# --output [filename of GraphML output file]
# -b [number as integer for bandwidth in mbit]
# --bw [number as integer for bandwidth in mbit]
# --bandwidth [number as integer for bandwidth in mbit]
# -c [controller ip as string]
# --controller [controller ip as string]
#
# Without any input, program will terminate.
# Without specified output, outputfile will have the same name as the input file.
# This means, the argument for the outputfile can be omitted.
# Parameters for bandwith and controller ip have default values, if they are omitted, too.
#
#
# sjas
# Wed Jul 17 02:59:06 PDT 2013
#
#
# TODO's:
# - fix double name error of some topologies
# - fix topoparsing (choose by name, not element <d..>)
# = topos with duplicate labels
# - use 'argparse' for script parameters, eases help creation
#
#################################################################################
import xml.etree.ElementTree as ET
import sys
import math
import re
from sys import argv
input_file_name = ''
output_file_name = ''
bandwidth_argument = ''
controller_ip = ''
# first check commandline arguments
for i in range(len(argv)):
if argv[i] == '-f':
input_file_name = argv[i+1]
if argv[i] == '--file':
input_file_name = argv[i+1]
if argv[i] == '-o':
output_file_name = argv[i+1]
if argv[i] == '--output':
output_file_name = argv[i+1]
if argv[i] == '-b':
bandwidth_argument = argv[i+1]
if argv[i] == '--bw':
bandwidth_argument = argv[i+1]
if argv[i] == '--bandwidth':
bandwidth_argument = argv[i+1]
if argv[i] == '-c':
controller_ip = argv[i+1]
if argv[i] == '--controller':
controller_ip = argv[i+1]
# terminate when inputfile is missing
if input_file_name == '':
sys.exit('\n\tNo input file was specified as argument....!')
# define string fragments for output later on
outputstring_1 = '''#!/usr/bin/python
"""
Custom topology for Mininet, generated by GraphML-Topo-to-Mininet-Network-Generator.
"""
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import RemoteController
from mininet.node import Node
from mininet.node import CPULimitedHost
from mininet.link import TCLink
from mininet.cli import CLI
from mininet.log import setLogLevel
from mininet.util import dumpNodeConnections
class GeneratedTopo( Topo ):
"Internet Topology Zoo Specimen."
def __init__( self, **opts ):
"Create a topology."
# Initialize Topology
Topo.__init__( self, **opts )
'''
outputstring_2a='''
# add nodes, switches first...
'''
outputstring_2b='''
# ... and now hosts
'''
outputstring_3a='''
# add edges between switch and corresponding host
'''
outputstring_3b='''
# add edges between switches
'''
outputstring_4a='''
topos = { 'generated': ( lambda: GeneratedTopo() ) }
# HERE THE CODE DEFINITION OF THE TOPOLOGY ENDS
# the following code produces an executable script working with a remote controller
# and providing ssh access to the the mininet hosts from within the ubuntu vm
'''
outputstring_4b = '''
def setupNetwork(controller_ip):
"Create network and run simple performance test"
# check if remote controller's ip was set
# else set it to localhost
topo = GeneratedTopo()
if controller_ip == '':
#controller_ip = '10.0.2.2';
controller_ip = '127.0.0.1';
net = Mininet(topo=topo, controller=lambda a: RemoteController( a, ip=controller_ip, port=6633 ), host=CPULimitedHost, link=TCLink)
return net
def connectToRootNS( network, switch, ip, prefixLen, routes ):
"Connect hosts to root namespace via switch. Starts network."
"network: Mininet() network object"
"switch: switch to connect to root namespace"
"ip: IP address for root namespace node"
"prefixLen: IP address prefix length (e.g. 8, 16, 24)"
"routes: host networks to route to"
# Create a node in root namespace and link to switch 0
root = Node( 'root', inNamespace=False )
intf = TCLink( root, switch ).intf1
root.setIP( ip, prefixLen, intf )
# Start network that now includes link to root namespace
network.start()
# Add routes from root ns to hosts
for route in routes:
root.cmd( 'route add -net ' + route + ' dev ' + str( intf ) )
# Run D-ITG logger on root
root.cmd('ITGLog &')
def sshd( network, cmd='/usr/sbin/sshd', opts='-D' ):
"Start a network, connect it to root ns, and run sshd on all hosts."
switch = network.switches[ 0 ] # switch to use
ip = '10.123.123.1' # our IP address on host network
routes = [ '10.0.0.0/8' ] # host networks to route to
connectToRootNS( network, switch, ip, 8, routes )
for host in network.hosts:
host.cmd( cmd + ' ' + opts + '&' )
host.cmd( 'ITGRecv -l /tmp/ITGRecv-Logs/ITGRecv-' + host.IP() + '.log > /dev/null &' )
# DEBUGGING INFO
print
print "Dumping host connections"
dumpNodeConnections(network.hosts)
print
print "*** Hosts are running sshd at the following addresses:"
print
for host in network.hosts:
print host.name, host.IP()
print
print "*** Type 'exit' or control-D to shut down network"
print
print "*** For testing network connectivity among the hosts, wait a bit for the controller to create all the routes, then do 'pingall' on the mininet console."
print
CLI( network )
for host in network.hosts:
host.cmd( 'kill %' + cmd )
network.stop()
if __name__ == '__main__':
setLogLevel('info')
#setLogLevel('debug')
sshd( setupNetwork(controller_ip) )
'''
#WHERE TO PUT RESULTS
outputstring_to_be_exported = ''
outputstring_to_be_exported += outputstring_1
#READ FILE AND DO ALL THE ACTUAL PARSING IN THE NEXT PARTS
xml_tree = ET.parse(input_file_name)
namespace = "{http://graphml.graphdrawing.org/xmlns}"
ns = namespace # just doing shortcutting, namespace is needed often.
#GET ALL ELEMENTS THAT ARE PARENTS OF ELEMENTS NEEDED LATER ON
root_element = xml_tree.getroot()
graph_element = root_element.find(ns + 'graph')
# GET ALL ELEMENT SETS NEEDED LATER ON
index_values_set = root_element.findall(ns + 'key')
node_set = graph_element.findall(ns + 'node')
edge_set = graph_element.findall(ns + 'edge')
# SET SOME VARIABLES TO SAVE FOUND DATA FIRST
# memomorize the values' ids to search for in current topology
node_label_name_in_graphml = ''
node_latitude_name_in_graphml = ''
node_longitude_name_in_graphml = ''
# for saving the current values
node_index_value = ''
node_name_value = ''
node_longitude_value = ''
node_latitude_value = ''
# id:value dictionaries
id_node_name_dict = {} # to hold all 'id: node_name_value' pairs
id_longitude_dict = {} # to hold all 'id: node_longitude_value' pairs
id_latitude_dict = {} # to hold all 'id: node_latitude_value' pairs
# FIND OUT WHAT KEYS ARE TO BE USED, SINCE THIS DIFFERS IN DIFFERENT GRAPHML TOPOLOGIES
for i in index_values_set:
if i.attrib['attr.name'] == 'label' and i.attrib['for'] == 'node':
node_label_name_in_graphml = i.attrib['id']
if i.attrib['attr.name'] == 'Longitude':
node_longitude_name_in_graphml = i.attrib['id']
if i.attrib['attr.name'] == 'Latitude':
node_latitude_name_in_graphml = i.attrib['id']
# NOW PARSE ELEMENT SETS TO GET THE DATA FOR THE TOPO
# GET NODE_NAME DATA
# GET LONGITUDE DATK
# GET LATITUDE DATA
for n in node_set:
node_index_value = n.attrib['id']
#get all data elements residing under all node elements
data_set = n.findall(ns + 'data')
#finally get all needed values
for d in data_set:
#node name
if d.attrib['key'] == node_label_name_in_graphml:
#strip all whitespace from names so they can be used as id's
node_name_value = re.sub(r'\s+', '', d.text)
#longitude data
if d.attrib['key'] == node_longitude_name_in_graphml:
node_longitude_value = d.text
#latitude data
if d.attrib['key'] == node_latitude_name_in_graphml:
node_latitude_value = d.text
#save id:data couple
id_node_name_dict[node_index_value] = node_name_value
id_longitude_dict[node_index_value] = node_longitude_value
id_latitude_dict[node_index_value] = node_latitude_value
# STRING CREATION
# FIRST CREATE THE SWITCHES AND HOSTS
tempstring1 = ''
tempstring2 = ''
tempstring3 = ''
for i in range(0, len(id_node_name_dict)):
#create switch
temp1 = ' '
temp1 += id_node_name_dict[str(i)]
temp1 += " = self.addSwitch( 's"
temp1 += str(i)
temp1 += "' )\n"
#create corresponding host
temp2 = ' '
temp2 += id_node_name_dict[str(i)]
temp2 += "_host = self.addHost( 'h"
temp2 += str(i)
temp2 += "' )\n"
tempstring1 += temp1
tempstring2 += temp2
# link each switch and its host...
temp3 = ' self.addLink( '
temp3 += id_node_name_dict[str(i)]
temp3 += ' , '
temp3 += id_node_name_dict[str(i)]
temp3 += "_host )"
temp3 += '\n'
tempstring3 += temp3
outputstring_to_be_exported += outputstring_2a
outputstring_to_be_exported += tempstring1
outputstring_to_be_exported += outputstring_2b
outputstring_to_be_exported += tempstring2
outputstring_to_be_exported += outputstring_3a
outputstring_to_be_exported += tempstring3
outputstring_to_be_exported += outputstring_3b
# SECOND CALCULATE DISTANCES BETWEEN SWITCHES,
# set global bandwidth and create the edges between switches,
# and link each single host to its corresponding switch
tempstring4 = ''
tempstring5 = ''
distance = 0.0
latency = 0.0
for e in edge_set:
# GET IDS FOR EASIER HANDLING
src_id = e.attrib['source']
dst_id = e.attrib['target']
# CALCULATE DELAYS
# CALCULATION EXPLANATION
#
# formula: (for distance)
# dist(SP,EP) = arccos{ sin(La[EP]) * sin(La[SP]) + cos(La[EP]) * cos(La[SP]) * cos(Lo[EP] - Lo[SP])} * r
# r = 6378.137 km
#
# formula: (speed of light, not within a vacuumed box)
# v = 1.97 * 10**8 m/s
#
# formula: (latency being calculated from distance and light speed)
# t = distance / speed of light
# t (in ms) = ( distance in km * 1000 (for meters) ) / ( speed of light / 1000 (for ms))
# ACTUAL CALCULATION: implementing this was no fun.
latitude_src = math.radians(float(id_latitude_dict[src_id]))
latitude_dst = math.radians(float(id_latitude_dict[dst_id]))
longitude_src = math.radians(float(id_longitude_dict[src_id]))
longitude_dst = math.radians(float(id_longitude_dict[dst_id]))
first_product = math.sin(latitude_dst) * math.sin(latitude_src)
second_product_first_part = math.cos(latitude_dst) * math.cos(latitude_src)
second_product_second_part = math.cos(longitude_dst - longitude_src)
distance = math.acos(first_product + (second_product_first_part * second_product_second_part)) * 6378.137
# t (in ms) = ( distance in km * 1000 (for meters) ) / ( speed of light / 1000 (for ms))
# t = ( distance * 1000 ) / ( 1.97 * 10**8 / 1000 )
latency = ( distance * 1000 ) / ( 197000 )
# BANDWIDTH LIMITING
#set bw to 10mbit if nothing was specified otherwise on startup
if bandwidth_argument == '':
bandwidth_argument = '10';
# ... and link all corresponding switches with each other
temp4 = ' self.addLink( '
temp4 += id_node_name_dict[src_id]
temp4 += ' , '
temp4 += id_node_name_dict[dst_id]
temp4 += ", bw="
temp4 += bandwidth_argument
temp4 += ", delay='"
temp4 += str(latency)
temp4 += "ms')"
temp4 += '\n'
# next line so i dont have to look up other possible settings
#temp += "ms', loss=0, max_queue_size=1000, use_htb=True)"
tempstring4 += temp4
outputstring_to_be_exported += tempstring4
outputstring_to_be_exported += outputstring_4a
# this is kind of dirty, due to having to use mixed '' ""
temp5 = "controller_ip = '"
temp5 += controller_ip
temp5 += "'\n"
tempstring5 += temp5
outputstring_to_be_exported += tempstring5
outputstring_to_be_exported += outputstring_4b
# GENERATION FINISHED, WRITE STRING TO FILE
outputfile = ''
if output_file_name == '':
output_file_name = input_file_name + '-generated-Mininet-Topo.py'
outputfile = open(output_file_name, 'w')
outputfile.write(outputstring_to_be_exported)
outputfile.close()
print "Topology generation SUCCESSFUL!"
| yossisolomon/assessing-mininet | parser/GraphML-Topo-to-Mininet-Network-Generator.py | Python | gpl-2.0 | 13,124 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Xml.XPath;
using System.Xml;
using SenseNet.ApplicationModel;
using SenseNet.ContentRepository.Storage;
namespace SenseNet.ContentRepository.Xpath
{
[DebuggerDisplay("<{Name} : {NodeType}")]
internal abstract class ElementBase
{
public NavigatorContext Context { get; private set; }
public Content Content { get; private set; }
public string Name { get; private set; }
public ElementBase Parent { get; private set; }
public ElementBase FirstChild { get; private set; }
public ElementBase FollowingSibling { get; private set; }
public ElementBase PrecedingSibling { get; private set; }
public abstract bool IsEmpty { get; }
public virtual XPathNodeType NodeType { get { return XPathNodeType.Element; } }
public ElementBase(NavigatorContext context, Content content, string name, ElementBase parent)
{
Name = name;
Parent = parent;
Context = context;
Content = content;
}
private bool _firstChildCompleted;
private bool _siblingsCompleted;
public ElementBase GetFirstChild()
{
if (!_firstChildCompleted)
{
FirstChild = CreateFirstChild();
_firstChildCompleted = true;
}
else
{
}
return FirstChild;
}
public abstract ElementBase CreateFirstChild();
public ElementBase GetNextElement()
{
if (FollowingSibling != null)
return FollowingSibling;
if(_siblingsCompleted)
return FollowingSibling;
var element = CreateNextElement();
if (element != null)
{
element.PrecedingSibling = this;
this.FollowingSibling = element;
}
else
{
_siblingsCompleted = true;
}
return element;
}
public abstract ElementBase CreateNextElement();
public ElementBase GetPreviousElement()
{
return PrecedingSibling;
}
public virtual string[] GetAttributeNames()
{
return null;
}
public virtual string GetAttributeValue(string name)
{
return string.Empty;
}
public string CollectTextValue()
{
var sb = new StringBuilder();
CollectTextValue(sb);
return sb.ToString();
}
protected virtual void CollectTextValue(StringBuilder sb)
{
var child = GetFirstChild();
if (child != null)
{
child.CollectTextValue(sb);
while ((child = child.FollowingSibling) != null)
child.CollectTextValue(sb);
}
}
internal void RemoveHashSignFromName()
{
Name = Name.Substring(1);
}
}
internal abstract class ContainerElement : ElementBase
{
public ContainerElement(NavigatorContext context, Content content, string name, ElementBase parent) : base(context, content, name, parent) { }
}
internal class RootElement : ContainerElement
{
public override bool IsEmpty { get { return false; } }
public override XPathNodeType NodeType { get { return XPathNodeType.Root; } }
public RootElement(NavigatorContext context, Content content) : base(context, content, "#document", null)
{
context.SetRoot(this);
}
public override ElementBase CreateFirstChild()
{
return new ContentElement(this.Context, Context.MainContent, this, false, 0);
}
public override ElementBase CreateNextElement()
{
return null;
}
}
internal class ChildrenElement : ContainerElement
{
public override bool IsEmpty { get { return Context.Children.Length == 0; } }
public ChildrenElement(NavigatorContext context, Content content, ElementBase parent) : base(context, content, "Children", parent) { }
public override ElementBase CreateFirstChild()
{
if (IsEmpty)
return null;
var content = Context.Children[0];
return new ContentElement(this.Context, content, this, true, 0);
}
public override ElementBase CreateNextElement() { return null; }
}
internal class ContentElement : ContainerElement
{
public override bool IsEmpty { get { return false; } }
public bool IsChildContent { get; private set; }
public int ContentIndex { get; private set; }
public ContentElement(NavigatorContext context, Content content, ElementBase parent, bool isChildContent, int contentIndex)
: base(context, content, "Content", parent)
{
IsChildContent = isChildContent;
ContentIndex = contentIndex;
}
public override ElementBase CreateFirstChild()
{
return new ContentHeadElement(this.Context, this.Content, "ContentType", this);
}
public override ElementBase CreateNextElement()
{
if (!IsChildContent)
return null;
var index = ContentIndex + 1;
if (index == Context.Children.Length)
return null;
var content = Context.Children[index];
return new ContentElement(Context, content, Parent, true, index);
}
}
internal class TextElement : ElementBase
{
public override XPathNodeType NodeType { get { return XPathNodeType.Text; } }
public override bool IsEmpty { get { return true; } }
private string _textValue;
public TextElement(NavigatorContext context, Content content, ElementBase parent, string textValue)
: base(context, content, "#text", parent)
{
_textValue = textValue;
}
public override ElementBase CreateFirstChild() { return null; }
public override ElementBase CreateNextElement() { return null; }
protected override void CollectTextValue(StringBuilder sb)
{
sb.Append(_textValue);
}
}
internal class ContentHeadElement : ElementBase
{
public override bool IsEmpty { get { return String.IsNullOrEmpty(GetValue()); } }
public ContentHeadElement(NavigatorContext context, Content content, string name, ElementBase parent) : base(context, content, name, parent) { }
private string _value;
private bool? _hasValue;
private string GetValue()
{
if (_hasValue != null)
return _value;
_value = GetFieldValue();
_hasValue = _value != null;
return _value;
}
private string GetFieldValue()
{
var contentType = Content.ContentType;
switch (Name)
{
case "ContentType": return contentType == null ? String.Empty : contentType.Name;
case "ContentTypePath": return contentType == null ? String.Empty : contentType.Path;
case "ContentTypeTitle": return contentType == null ? String.Empty : contentType.DisplayName;
case "ContentName": return Content.Name;
case "Icon": return contentType.Icon;
case "SelfLink": return this.Content.Path;
case "IsFolder": return (this.Content.ContentHandler is IFolder).ToString().ToLowerInvariant();
default:
throw new SnNotSupportedException();
}
}
public override ElementBase CreateFirstChild()
{
if (GetValue() == null)
return null;
return new TextElement(Context, Content, this, GetValue());
}
public override ElementBase CreateNextElement()
{
switch (Name)
{
case "ContentType": return new ContentHeadElement(this.Context, this.Content, "ContentTypePath", this.Parent);
case "ContentTypePath": return new ContentHeadElement(this.Context, this.Content, "ContentTypeTitle", this.Parent);
case "ContentTypeTitle": return new ContentHeadElement(this.Context, this.Content, "ContentName", this.Parent);
case "ContentName": return new ContentHeadElement(this.Context, this.Content, "Icon", this.Parent);
case "Icon": return new ContentHeadElement(this.Context, this.Content, "SelfLink", this.Parent);
case "SelfLink": return new ContentHeadElement(this.Context, this.Content, "IsFolder", this.Parent);
case "IsFolder": return new FieldsElement(this.Context, this.Content, this.Parent);
default:
throw new SnNotSupportedException("##");
}
}
}
internal class FieldsElement : ContainerElement
{
internal IEnumerator<Field> FieldEnumerator { get; private set; }
private bool _isEmpty;
public override bool IsEmpty { get { return _isEmpty; } }
public FieldsElement(NavigatorContext context, Content content, ElementBase parent)
: base(context, content, "Fields", parent)
{
var enumerator = content.Fields.Values.AsEnumerable<Field>().GetEnumerator();
FieldEnumerator = new FieldEnumerator(enumerator);
_isEmpty = !FieldEnumerator.MoveNext();
}
public override ElementBase CreateFirstChild()
{
if (this.IsEmpty)
return null;
return FieldElement.Create(Context, Content, this, FieldEnumerator.Current);
}
public override ElementBase CreateNextElement()
{
return new ActionsElement(this.Context, this.Content, this.Parent);
}
}
internal abstract class FieldElement : ElementBase
{
private IXmlAttributeOwner _attributeContainer;
private bool _isListField;
public Field Field { get; private set; }
protected FieldElement(NavigatorContext context, Content content, string name, ElementBase parent, Field field)
: base(context, content, name, parent)
{
this.Field = field;
_attributeContainer = field as IXmlAttributeOwner;
_isListField = field.Name[0] == '#';
if (_isListField)
base.RemoveHashSignFromName();
}
public override string[] GetAttributeNames()
{
if (_isListField)
{
if (_attributeContainer == null)
return new[] { Field.FIELDSUBTYPEATTRIBUTENAME };
var names = _attributeContainer.GetXmlAttributeNames().ToList();
names.Add(Field.FIELDSUBTYPEATTRIBUTENAME);
return names.ToArray();
}
if (_attributeContainer != null)
return _attributeContainer.GetXmlAttributeNames().ToArray();
return null;
}
public override string GetAttributeValue(string name)
{
if (name == Field.FIELDSUBTYPEATTRIBUTENAME)
return "ContentList";
return _attributeContainer.GetXmlAttribute(name);
}
public override ElementBase CreateNextElement()
{
var enumerator = ((FieldsElement)Parent).FieldEnumerator;
var hasNextField = enumerator.MoveNext();
if (!hasNextField)
return null;
return FieldElement.Create(Context, Content, Parent, enumerator.Current);
}
internal static FieldElement Create(NavigatorContext context, Content content, ElementBase parent, Field field)
{
if (field is IXmlChildList)
return new ItemContainerElement(context, content, field.Name, parent, field);
if (field is IRawXmlContainer)
return new XmlFieldElement(context, content, field.Name, parent, field);
return new SimpleFieldElement(context, content, field.Name, parent, field);
}
}
internal class SimpleFieldElement : FieldElement
{
public override bool IsEmpty { get { return String.IsNullOrEmpty(GetValue()); } }
public SimpleFieldElement(NavigatorContext context, Content content, string name, ElementBase parent, Field field) : base(context, content, name, parent, field) { }
private string _value;
private bool? _hasValue;
public string GetValue()
{
if (_hasValue != null)
return _value;
_value = GetFieldValue();
_hasValue = _value != null;
return _value;
}
private string GetFieldValue()
{
var value = Field.GetInnerXml();
if (String.IsNullOrEmpty(value))
return null;
return value;
}
public override ElementBase CreateFirstChild()
{
if (GetValue() == null)
return null;
return new TextElement(Context, Content, this, GetValue());
}
}
internal class ItemContainerElement : FieldElement
{
internal IEnumerator<string> ChildValueEnumerator { get; private set; }
internal string ChildItemName { get; private set; }
private bool _isEmpty;
public override bool IsEmpty { get { return _isEmpty; } }
public ItemContainerElement(NavigatorContext context, Content content, string name, ElementBase parent, Field field)
: base(context, content, name, parent, field)
{
var listField = (IXmlChildList)field;
ChildItemName = listField.GetXmlChildName();
ChildValueEnumerator = listField.GetXmlChildValues().GetEnumerator();
_isEmpty = !ChildValueEnumerator.MoveNext();
}
public override ElementBase CreateFirstChild()
{
if (this.IsEmpty)
return null;
return new ChildItemElement(Context, Content, this, ChildItemName, ChildValueEnumerator.Current);
}
}
internal class ChildItemElement : ElementBase
{
private string _value;
public override bool IsEmpty { get { return false; } }
public ChildItemElement(NavigatorContext context, Content content, ElementBase parent, string name, string value)
: base(context, content, name, parent)
{
_value = value;
}
public override ElementBase CreateFirstChild()
{
if (_value == null)
return null;
return new TextElement(Context, Content, this, _value);
}
public override ElementBase CreateNextElement()
{
var enumerator = ((ItemContainerElement)Parent).ChildValueEnumerator;
var hasNextItem = enumerator.MoveNext();
if (!hasNextItem)
return null;
return new ChildItemElement(Context, Content, Parent, this.Name, enumerator.Current);
}
}
internal class ActionsElement : ContainerElement
{
internal IEnumerator<ActionBase> ActionEnumerator { get; private set; }
private bool _isEmpty;
public override bool IsEmpty { get { return _isEmpty; } }
public ActionsElement(NavigatorContext context, Content content, ElementBase parent)
: base(context, content, "Actions", parent)
{
ActionEnumerator = ActionFramework.GetActionsForContentNavigator(content).GetEnumerator();
_isEmpty = !ActionEnumerator.MoveNext();
}
public override ElementBase CreateFirstChild()
{
if (this.IsEmpty)
return null;
return ActionElement.Create(Context, Content, this, ActionEnumerator.Current);
}
public override ElementBase CreateNextElement()
{
if (((ContentElement)Parent).IsChildContent)
return null;
if (!Context.WithChildren)
return null;
var mainContent = Context.MainContent;
if (mainContent.Children == null)
return null;
if (mainContent.Children.Count() == 0)
return null;
return new ChildrenElement(this.Context, this.Content, this.Parent);
}
}
internal class ActionElement : ElementBase
{
private ActionBase _action;
public override bool IsEmpty { get { return false; } }
private ActionElement(NavigatorContext context, Content content, string name, ElementBase parent, ActionBase action)
: base(context, content, name, parent)
{
_action = action;
}
public override string[] GetAttributeNames()
{
if (!_action.IncludeBackUrl)
return new[] { ActionBase.BackUrlParameterName };
return null;
}
public override string GetAttributeValue(string name)
{
if (name == ActionBase.BackUrlParameterName)
return _action.BackUrlWithParameter;
return string.Empty;
}
public override ElementBase CreateFirstChild()
{
return new TextElement(Context, Content, this, _action.Uri);
}
public override ElementBase CreateNextElement()
{
var enumerator = ((ActionsElement)Parent).ActionEnumerator;
var hasNextAction = enumerator.MoveNext();
if (!hasNextAction)
return null;
return ActionElement.Create(Context, Content, Parent, enumerator.Current);
}
internal static ActionElement Create(NavigatorContext context, Content content, ElementBase parent, ActionBase action)
{
return new ActionElement(context, content, action.Name, parent, action);
}
}
/*-----------------------------------------------------------------*/
internal class XmlNodeWrapper : ElementBase
{
private XmlNode _wrappedNode;
public XmlNodeWrapper(NavigatorContext context, Content content, string name, ElementBase parent, XmlNode wrappedNode)
: base(context, content, name, parent)
{
_wrappedNode = wrappedNode;
}
public override bool IsEmpty
{
get { throw new SnNotSupportedException(); }
}
public override XPathNodeType NodeType
{
get
{
switch (_wrappedNode.NodeType)
{
case XmlNodeType.Attribute: return XPathNodeType.Attribute;
case XmlNodeType.CDATA: return XPathNodeType.Text;
case XmlNodeType.Comment: return XPathNodeType.Comment;
case XmlNodeType.Element: return XPathNodeType.Element;
case XmlNodeType.ProcessingInstruction: return XPathNodeType.ProcessingInstruction;
case XmlNodeType.SignificantWhitespace: return XPathNodeType.SignificantWhitespace;
case XmlNodeType.Text: return XPathNodeType.Text;
case XmlNodeType.Whitespace: return XPathNodeType.Whitespace;
default:
throw new NotSupportedException("Not supported NodeType: " + _wrappedNode.NodeType);
}
}
}
public override string[] GetAttributeNames()
{
var attrs = _wrappedNode.Attributes;
if (attrs.Count == 0)
return null;
var names = new string[attrs.Count];
for (int i = 0; i < attrs.Count; i++)
names[i] = attrs[i].Name;
return names;
}
public override string GetAttributeValue(string name)
{
return _wrappedNode.Attributes[name].Value;
}
public string Value
{
get { return _wrappedNode.Value; }
}
protected override void CollectTextValue(StringBuilder sb)
{
sb.Append(_wrappedNode.InnerText);
}
public override ElementBase CreateFirstChild()
{
var firstChild = _wrappedNode.FirstChild;
if (firstChild == null)
return null;
return XmlNodeWrapper.Create(Context, Content, firstChild.LocalName, this, firstChild);
}
public override ElementBase CreateNextElement()
{
var node = _wrappedNode.NextSibling;
if (node == null)
return null;
return Create(Context, Content, node.Name, Parent, node);
}
internal static XmlNodeWrapper Create(NavigatorContext context, Content content, string name, ElementBase parent, XmlNode wrappedNode)
{
return new XmlNodeWrapper(context, content, name, parent, wrappedNode);
}
}
internal class XmlFieldElement : FieldElement
{
private const string INNERNAVIGATORROOTELEMENTNAME = "innerdocumentroot";
private XmlDocument __innerDocument;
private XmlDocument InnerDocument
{
get
{
if (__innerDocument == null)
{
__innerDocument = new XmlDocument();
__innerDocument.LoadXml(String.Concat("<", INNERNAVIGATORROOTELEMENTNAME, ">",
((IRawXmlContainer)this.Field).GetRawXml(), "</", INNERNAVIGATORROOTELEMENTNAME, ">"));
}
return __innerDocument;
}
}
public override bool IsEmpty
{
get { return String.IsNullOrEmpty(FieldValue); }
}
private string _fieldValue;
private bool? _hasFieldValue;
public string FieldValue
{
get
{
if (_hasFieldValue != null)
return _fieldValue;
_fieldValue = this.Field.GetData().ToString();
_hasFieldValue = _fieldValue != null;
return _fieldValue;
}
}
private string _value;
private bool? _hasValue;
public string GetValue()
{
if (_hasValue != null)
return _value;
_value = GetValue1();
_hasValue = _value != null;
return _value;
}
private string GetValue1()
{
return InnerDocument.DocumentElement.InnerText;
}
protected override void CollectTextValue(StringBuilder sb)
{
sb.Append(InnerDocument.DocumentElement.InnerText);
}
public XmlFieldElement(NavigatorContext context, Content content, string name, ElementBase parent, Field field) : base(context, content, name, parent, field) { }
public override ElementBase CreateFirstChild()
{
if (GetValue() == null)
return null;
var firstChild = InnerDocument.DocumentElement.FirstChild;
return XmlNodeWrapper.Create(Context, Content, firstChild.LocalName, this, firstChild);
}
}
/*=================================================================*/
internal class FieldEnumerator : IEnumerator<Field>
{
private IEnumerator<Field> _wrappedEnumerator;
public FieldEnumerator(IEnumerator<Field> enumerator)
{
_wrappedEnumerator = enumerator;
}
public Field Current
{
get { return _wrappedEnumerator.Current; }
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
while (true)
{
if (!_wrappedEnumerator.MoveNext())
return false;
if (CurrentIsAllowed())
break;
}
return true;
}
private bool CurrentIsAllowed()
{
var field = Current;
if (field.Name == "Name")
return false;
return true;
}
public void Reset()
{
_wrappedEnumerator.Reset();
}
public void Dispose()
{
}
}
}
| SenseNet/sensenet | src/ContentRepository/Xpath/Elements.cs | C# | gpl-2.0 | 25,411 |
<?php
/**
* Wrapper for Symfony Dumper + die
*
* PHP Version 5
*
* @category PHP
* @package Phputils
* @author Unamata Sanatarai <unamatasanatarai@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
* @link https://github.com/unamatasanatarai/phputils
*/
use Symfony\Component\VarDumper\VarDumper;
if (!function_exists('dd')) {
/**
* Wrapper for Symfony Dupmer + die
*
* @return null
*/
function dd()
{
$callstack = debug_backtrace();
VarDumper::dump(
'called from: ' . $callstack[0]['file'] . ':'. $callstack[0]['line']
);
foreach (func_get_args() as $var) {
VarDumper::dump($var);
}
die;
}
}
| unamatasanatarai/phputils | src/phputils/dd.php | PHP | gpl-2.0 | 757 |
from django.conf.urls import url
from kraut_accounts import views
urlpatterns = [
url(r'^logout/$', views.accounts_logout, name='logout'),
url(r'^login/$', views.accounts_login, name='login'),
url(r'^changepw/$', views.accounts_change_password, name='changepw'),
]
| zeroq/kraut_salad | kraut_accounts/urls.py | Python | gpl-2.0 | 278 |
<?php
//event-type: return-html
e("recipes/admin/design/browsers/browserFoodTypes", array(
"section-title" => "Food types",
"records" => RecipesModel::getRecords("foodtype")));
// End of file | pragres/recipescookbook.org | packages/recipes/admin/view/browsers/browserFoodTypes.event.php | PHP | gpl-2.0 | 205 |
<?php
/**
* Gerenciador Clínico Odontológico
* Copyright (C) 2006 - 2009
* Autores: Ivis Silva Andrade - Engenharia e Design(ivis@expandweb.com)
* Pedro Henrique Braga Moreira - Engenharia e Programação(ikkinet@gmail.com)
*
* Este arquivo é parte do programa Gerenciador Clínico Odontológico
*
* Gerenciador Clínico Odontológico é um software livre; você pode
* redistribuí-lo e/ou modificá-lo dentro dos termos da Licença
* Pública Geral GNU como publicada pela Fundação do Software Livre
* (FSF); na versão 2 da Licença invariavelmente.
*
* Este programa é distribuído na esperança que possa ser útil,
* mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÂO
* a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a
* Licença Pública Geral GNU para maiores detalhes.
*
* Você recebeu uma cópia da Licença Pública Geral GNU,
* que está localizada na raíz do programa no arquivo COPYING ou COPYING.TXT
* junto com este programa. Se não, visite o endereço para maiores informações:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html (Inglês)
* http://www.magnux.org/doc/GPL-pt_BR.txt (Português - Brasil)
*
* Em caso de dúvidas quanto ao software ou quanto à licença, visite o
* endereço eletrônico ou envie-nos um e-mail:
*
* http://www.smileodonto.com.br/gco
* smile@smileodonto.com.br
*
* Ou envie sua carta para o endereço:
*
* Smile Odontolóogia
* Rua Laudemira Maria de Jesus, 51 - Lourdes
* Arcos - MG - CEP 35588-000
*
*
*/
include "../lib/config.inc.php";
include "../lib/func.inc.php";
include "../lib/classes.inc.php";
require_once '../lang/'.$idioma.'.php';
header("Content-type: text/html; charset=UTF-8", true);
if(!checklog()) {
echo '<script>Ajax("wallpapers/index", "conteudo", "");</script>';
die();
}
if(!verifica_nivel('patrimonio', 'L')) {
echo $LANG['general']['you_tried_to_access_a_restricted_area'];
die();
}
if($_GET[confirm_del] == "delete") {
mysql_query("DELETE FROM `patrimonio` WHERE `codigo` = '".$_GET[codigo]."'") or die(mysql_error());
}
?>
<div class="conteudo" id="conteudo_central">
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="conteudo">
<tr>
<td width="46%"> <img src="patrimonio/img/patrimonio.png" alt="<?php echo $LANG['patrimony']['manage_patrimony']?>"> <span class="h3"><?php echo $LANG['patrimony']['manage_patrimony']?></span></td>
<td width="27%" valign="bottom">
<?php echo $LANG['patrimony']['search_for']?>
<input name="procurar" id="procurar" type="text" class="forms" size="20" maxlength="40" onkeyup="javascript:Ajax('patrimonio/pesquisa', 'pesquisa', 'pesquisa='%2Bthis.value)">
</td>
<td width="23%" align="right" valign="bottom"><?php echo ((verifica_nivel('patrimonio', 'I'))?'<img src="imagens/icones/novo.png" alt="Incluir" width="19" height="22" border="0"><a href="javascript:Ajax(\'patrimonio/incluir\', \'conteudo\', \'\')">'.$LANG['patrimony']['include_new_item'].'</a>':'')?></td>
<td width="2%" valign="bottom"> </td>
<td width="2%" valign="bottom"> </td>
</tr>
</table>
<div class="conteudo" id="table dados"><br>
<table width="750" border="0" align="center" cellpadding="0" cellspacing="0" class="tabela_titulo">
<tr bgcolor="#009BE6">
<td colspan="6"> </td>
</tr>
<tr>
<td width="50" height="23" align="left"><?php echo $LANG['patrimony']['code']?></td>
<td width="338" align="left"><?php echo $LANG['patrimony']['description']?> </td>
<td width="130" align="left"><?php echo $LANG['patrimony']['sector']?></td>
<td width="107" align="center"><?php echo $LANG['patrimony']['value']?></td>
<td width="59" align="center"><?php echo $LANG['patrimony']['edit_view']?></td>
<td width="66" align="center"><?php echo $LANG['patrimony']['delete']?></td>
</tr>
</table>
<div id="pesquisa"></div>
<script>
Ajax('patrimonio/pesquisa', 'pesquisa', 'pesquisa=');
</script>
</div>
| artsjedi/GCO | http/patrimonio/gerenciar_ajax.php | PHP | gpl-2.0 | 4,182 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package utilesGUIx.plugin.toolBar;
import java.io.Serializable;
public interface ICompCMB extends Serializable {
public String getText();
public String getCodigo();
}
| Creativa3d/box3d | paquetes/src/utilesGUIx/plugin/toolBar/ICompCMB.java | Java | gpl-2.0 | 284 |
/*
Copyright (C) 2008 - 2016 by Mark de Wever <koraq@xs4all.nl>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
#define GETTEXT_DOMAIN "wesnoth-lib"
#include "gui/widgets/menu_button.hpp"
#include "gui/core/log.hpp"
#include "gui/core/widget_definition.hpp"
#include "gui/core/window_builder.hpp"
#include "gui/core/window_builder/helper.hpp"
#include "gui/core/register_widget.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
#include "gui/dialogs/drop_down_menu.hpp"
#include "config_assign.hpp"
#include "sound.hpp"
#include "utils/functional.hpp"
#define LOG_SCOPE_HEADER get_control_type() + " [" + id() + "] " + __func__
#define LOG_HEADER LOG_SCOPE_HEADER + ':'
namespace gui2
{
// ------------ WIDGET -----------{
REGISTER_WIDGET(menu_button)
menu_button::menu_button()
: styled_widget(COUNT)
, selectable_item()
, state_(ENABLED)
, retval_(0)
, values_()
, selected_()
, toggle_states_()
, keep_open_(false)
{
values_.push_back(config_of("label", this->get_label()));
connect_signal<event::MOUSE_ENTER>(
std::bind(&menu_button::signal_handler_mouse_enter, this, _2, _3));
connect_signal<event::MOUSE_LEAVE>(
std::bind(&menu_button::signal_handler_mouse_leave, this, _2, _3));
connect_signal<event::LEFT_BUTTON_DOWN>(std::bind(
&menu_button::signal_handler_left_button_down, this, _2, _3));
connect_signal<event::LEFT_BUTTON_UP>(
std::bind(&menu_button::signal_handler_left_button_up, this, _2, _3));
connect_signal<event::LEFT_BUTTON_CLICK>(std::bind(
&menu_button::signal_handler_left_button_click, this, _2, _3));
}
void menu_button::set_active(const bool active)
{
if(get_active() != active) {
set_state(active ? ENABLED : DISABLED);
}
}
bool menu_button::get_active() const
{
return state_ != DISABLED;
}
unsigned menu_button::get_state() const
{
return state_;
}
void menu_button::set_state(const state_t state)
{
if(state != state_) {
state_ = state;
set_is_dirty(true);
}
}
const std::string& menu_button::get_control_type() const
{
static const std::string type = "menu_button";
return type;
}
void menu_button::signal_handler_mouse_enter(const event::ui_event event, bool& handled)
{
DBG_GUI_E << LOG_HEADER << ' ' << event << ".\n";
set_state(FOCUSED);
handled = true;
}
void menu_button::signal_handler_mouse_leave(const event::ui_event event, bool& handled)
{
DBG_GUI_E << LOG_HEADER << ' ' << event << ".\n";
set_state(ENABLED);
handled = true;
}
void menu_button::signal_handler_left_button_down(const event::ui_event event, bool& handled)
{
DBG_GUI_E << LOG_HEADER << ' ' << event << ".\n";
window* window = get_window();
if(window) {
window->mouse_capture();
}
set_state(PRESSED);
handled = true;
}
void menu_button::signal_handler_left_button_up(const event::ui_event event, bool& handled)
{
DBG_GUI_E << LOG_HEADER << ' ' << event << ".\n";
set_state(FOCUSED);
handled = true;
}
void menu_button::signal_handler_left_button_click(const event::ui_event event, bool& handled)
{
assert(get_window());
DBG_GUI_E << LOG_HEADER << ' ' << event << ".\n";
sound::play_UI_sound(settings::sound_button_click);
// If a button has a retval do the default handling.
dialogs::drop_down_menu droplist(this->get_rectangle(), this->values_, this->selected_, this->get_use_markup(), this->keep_open_);
if(droplist.show(get_window()->video())) {
const int selected = droplist.selected_item();
// Saftey check. If the user clicks a selection in the dropdown and moves their mouse away too
// quickly, selected_ could be set to -1. This returns in that case, preventing crashes.
if(selected < 0) {
return;
}
selected_ = selected;
this->set_label(values_[selected_]["label"]);
fire(event::NOTIFY_MODIFIED, *this, nullptr);
if(callback_state_change_) {
callback_state_change_(*this);
}
if(retval_ != 0) {
if(window* window = get_window()) {
window->set_retval(retval_);
return;
}
}
}
// Toggle states are recorded regardless of dismissal type
toggle_states_ = droplist.get_toggle_states();
/* In order to allow toggle button states to be specified by verious dialogs in the values config, we write the state
* bools to the values_ config here, but only if a checkbox= key was already provided. The value of the checkbox= key
* is handled by the drop_down_menu widget.
*
* Passing the dynamic_bitset directly to the drop_down_menu ctor would mean bool values would need to be passed to this
* class independently of the values config by dialogs that use this widget. However, the bool states are also saved
* in a dynamic_bitset class member which can be fetched for other uses if necessary.
*/
for(unsigned i = 0; i < values_.size(); i++) {
::config& c = values_[i];
if(c.has_attribute("checkbox")) {
c["checkbox"] = toggle_states_[i];
}
}
handled = true;
}
void menu_button::set_values(const std::vector<::config>& values, int selected)
{
assert(static_cast<size_t>(selected) < values.size());
assert(static_cast<size_t>(selected_) < values_.size());
if(values[selected]["label"] != values_[selected_]["label"]) {
set_is_dirty(true);
}
values_ = values;
selected_ = selected;
toggle_states_.resize(values_.size(), false);
set_label(values_[selected_]["label"]);
}
void menu_button::set_selected(int selected)
{
assert(static_cast<size_t>(selected) < values_.size());
assert(static_cast<size_t>(selected_) < values_.size());
if(selected != selected_) {
set_is_dirty(true);
}
selected_ = selected;
set_label(values_[selected_]["label"]);
}
// }---------- DEFINITION ---------{
menu_button_definition::menu_button_definition(const config& cfg)
: styled_widget_definition(cfg)
{
DBG_GUI_P << "Parsing menu_button " << id << '\n';
load_resolutions<resolution>(cfg);
}
/*WIKI
* @page = GUIWidgetDefinitionWML
* @order = 1_menu_button
*
* == menu_button ==
*
* @macro = menu_button_description
*
* The following states exist:
* * state_enabled, the menu_button is enabled.
* * state_disabled, the menu_button is disabled.
* * state_pressed, the left mouse menu_button is down.
* * state_focused, the mouse is over the menu_button.
* @begin{parent}{name="gui/"}
* @begin{tag}{name="menu_button_definition"}{min=0}{max=-1}{super="generic/widget_definition"}
* @begin{tag}{name="resolution"}{min=0}{max=-1}{super="generic/widget_definition/resolution"}
* @begin{tag}{name="state_enabled"}{min=0}{max=1}{super="generic/state"}
* @end{tag}{name="state_enabled"}
* @begin{tag}{name="state_disabled"}{min=0}{max=1}{super="generic/state"}
* @end{tag}{name="state_disabled"}
* @begin{tag}{name="state_pressed"}{min=0}{max=1}{super="generic/state"}
* @end{tag}{name="state_pressed"}
* @begin{tag}{name="state_focused"}{min=0}{max=1}{super="generic/state"}
* @end{tag}{name="state_focused"}
* @end{tag}{name="resolution"}
* @end{tag}{name="menu_button_definition"}
* @end{parent}{name="gui/"}
*/
menu_button_definition::resolution::resolution(const config& cfg)
: resolution_definition(cfg)
{
// Note the order should be the same as the enum state_t in menu_button.hpp.
state.push_back(state_definition(cfg.child("state_enabled")));
state.push_back(state_definition(cfg.child("state_disabled")));
state.push_back(state_definition(cfg.child("state_pressed")));
state.push_back(state_definition(cfg.child("state_focused")));
}
// }---------- BUILDER -----------{
/*WIKI_MACRO
* @begin{macro}{menu_button_description}
*
* A menu_button is a styled_widget to choose an element from a list of elements.
* @end{macro}
*/
/*WIKI
* @page = GUIWidgetInstanceWML
* @order = 2_menu_button
* @begin{parent}{name="gui/window/resolution/grid/row/column/"}
* @begin{tag}{name="menu_button"}{min=0}{max=-1}{super="generic/widget_instance"}
* == menu_button ==
*
* @macro = menu_button_description
*
* Instance of a menu_button. When a menu_button has a return value it sets the
* return value for the window. Normally this closes the window and returns
* this value to the caller. The return value can either be defined by the
* user or determined from the id of the menu_button. The return value has a
* higher precedence as the one defined by the id. (Of course it's weird to
* give a menu_button an id and then override its return value.)
*
* When the menu_button doesn't have a standard id, but you still want to use the
* return value of that id, use return_value_id instead. This has a higher
* precedence as return_value.
*
* List with the menu_button specific variables:
* @begin{table}{config}
* return_value_id & string & "" & The return value id. $
* return_value & int & 0 & The return value. $
*
* @end{table}
* @end{tag}{name="menu_button"}
* @end{parent}{name="gui/window/resolution/grid/row/column/"}
*/
namespace implementation
{
builder_menu_button::builder_menu_button(const config& cfg)
: builder_styled_widget(cfg)
, retval_id_(cfg["return_value_id"])
, retval_(cfg["return_value"])
, options_()
{
for(const auto& option : cfg.child_range("option")) {
options_.push_back(option);
}
}
widget* builder_menu_button::build() const
{
menu_button* widget = new menu_button();
init_control(widget);
widget->set_retval(get_retval(retval_id_, retval_, id));
if(!options_.empty()) {
widget->set_values(options_);
}
DBG_GUI_G << "Window builder: placed menu_button '" << id
<< "' with definition '" << definition << "'.\n";
return widget;
}
} // namespace implementation
// }------------ END --------------
} // namespace gui2
| TakingInitiative/wesnoth | src/gui/widgets/menu_button.cpp | C++ | gpl-2.0 | 9,996 |
/*
This file is part of Shuriken Beat Slicer.
Copyright (C) 2014, 2015 Andrew M Taylor <a.m.taylor303@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>
or write to the Free Software Foundation, Inc., 51 Franklin Street,
Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "audiofilehandler.h"
#include <samplerate.h>
#include <QDir>
#include <QDebug>
//==================================================================================================
// Public:
AudioFileHandler::AudioFileHandler()
{
// Initialise sndlib so we can read header info not available through aubio's API
// and also open some audio file formats that may not be supported via aubio
const int errorCode = sndlibInit();
if ( errorCode == MUS_ERROR )
{
s_errorTitle = "Error initialising sndlib!";
s_errorInfo = "It may not be possible to read some audio files";
}
}
SharedSampleBuffer AudioFileHandler::getSampleData( const QString filePath )
{
return getSampleData( filePath, 0, 0 );
}
SharedSampleBuffer AudioFileHandler::getSampleData( const QString filePath, const int startFrame, const int numFramesToRead )
{
Q_ASSERT( ! filePath.isEmpty() );
QByteArray charArray = filePath.toLocal8Bit();
const char* path = charArray.data();
SharedSampleBuffer sampleBuffer;
#ifdef ENABLE_AUBIO_FILE_IO
// First try using aubio to load the file; if that fails, try using sndlib
sampleBuffer = aubioLoadFile( path, startFrame, numFramesToRead );
#else
// First try using libsndfile to load the file; if that fails, try using sndlib
sampleBuffer = sndfileLoadFile( path, startFrame, numFramesToRead );
#endif
if ( sampleBuffer.isNull() )
{
sampleBuffer = sndlibLoadFile( path, startFrame, numFramesToRead );
}
return sampleBuffer;
}
SharedSampleHeader AudioFileHandler::getSampleHeader( const QString filePath )
{
Q_ASSERT( ! filePath.isEmpty() );
QByteArray charArray = filePath.toLocal8Bit();
const char* path = charArray.data();
SharedSampleHeader sampleHeader;
// If `0` is passed as `samplerate` param to new_aubio_source, the sample rate of the original file is used.
aubio_source_t* aubioSource = new_aubio_source( const_cast<char*>(path), 0, 4096 );
if ( aubioSource != NULL ) // First try using aubio to read the header
{
sampleHeader = SharedSampleHeader( new SampleHeader );
sampleHeader->sampleRate = aubio_source_get_samplerate( aubioSource );
sampleHeader->numChans = aubio_source_get_channels( aubioSource );
del_aubio_source( aubioSource );
const int headerCode = mus_sound_header_type( path );
// If sndlib recognises the audio file type
if ( mus_header_type_p( headerCode ) )
{
sampleHeader->format = mus_header_type_name( headerCode );
sampleHeader->bitsPerSample = mus_sound_bits_per_sample( path );
}
else
{
sampleHeader->bitsPerSample = 0;
}
}
else // If aubio can't read the header, try using sndlib
{
const int headerCode = mus_sound_header_type( path );
// If sndlib recognises the audio file type
if ( mus_header_type_p( headerCode ) )
{
sampleHeader = SharedSampleHeader( new SampleHeader );
sampleHeader->format = mus_header_type_name( headerCode );
sampleHeader->numChans = mus_sound_chans( path );
sampleHeader->sampleRate = mus_sound_srate( path );
sampleHeader->bitsPerSample = mus_sound_bits_per_sample( path );
}
}
// It's essential that the sample rate is known
if ( ! sampleHeader.isNull() && sampleHeader->sampleRate < 1.0 )
{
sampleHeader.clear();
}
return sampleHeader;
}
QString AudioFileHandler::saveAudioFile( const QString dirPath,
const QString fileBaseName,
const SharedSampleBuffer sampleBuffer,
const int currentSampleRate,
const int outputSampleRate,
const int sndFileFormat,
const bool isOverwriteEnabled )
{
Q_ASSERT( currentSampleRate != 0 );
const int hopSize = 8192;
const int numChans = sampleBuffer->getNumChannels();
bool isSuccessful = false;
QDir saveDir( dirPath );
QString filePath;
if ( saveDir.exists() )
{
filePath = saveDir.absoluteFilePath( fileBaseName );
SF_INFO sfInfo;
memset( &sfInfo, 0, sizeof( SF_INFO ) );
sfInfo.samplerate = outputSampleRate;
sfInfo.channels = numChans;
sfInfo.format = sndFileFormat;
switch ( sndFileFormat & SF_FORMAT_TYPEMASK )
{
case SF_FORMAT_WAV:
filePath.append( ".wav" );
break;
case SF_FORMAT_AIFF:
filePath.append( ".aiff" );
break;
case SF_FORMAT_AU:
filePath.append( ".au" );
break;
case SF_FORMAT_FLAC:
filePath.append( ".flac" );
break;
case SF_FORMAT_OGG:
filePath.append( ".ogg" );
break;
default:
qDebug() << "Unknown format: " << sndFileFormat;
break;
}
Q_ASSERT( sf_format_check( &sfInfo ) );
if ( isOverwriteEnabled || ! QFileInfo( filePath ).exists() )
{
SNDFILE* fileID = sf_open( filePath.toLocal8Bit().data(), SFM_WRITE, &sfInfo );
if ( fileID != NULL )
{
if ( outputSampleRate == currentSampleRate )
{
isSuccessful = sndfileSaveAudioFile( fileID, sampleBuffer, hopSize );
}
else
{
const qreal sampleRateRatio = (qreal) outputSampleRate / (qreal) currentSampleRate;
Array<float> interleavedBuffer;
isSuccessful = convertSampleRate( sampleBuffer, sampleRateRatio, interleavedBuffer );
if ( isSuccessful )
{
isSuccessful = sndfileSaveAudioFile( fileID, interleavedBuffer, hopSize * numChans );
}
}
sf_write_sync( fileID );
sf_close( fileID );
}
else // Could not open file for writing
{
s_errorTitle = "Couldn't open file for writing";
s_errorInfo = sf_strerror( NULL );
isSuccessful = false;
}
}
else // File already exists and overwriting is not enabled
{
s_errorTitle = "Couldn't overwrite existing file";
s_errorInfo = "The file " + filePath + " already exists and could not be overwritten";
isSuccessful = false;
}
}
if ( ! isSuccessful )
{
filePath.clear();
}
return filePath;
}
//==================================================================================================
// Private Static:
QString AudioFileHandler::s_errorTitle;
QString AudioFileHandler::s_errorInfo;
void AudioFileHandler::interleaveSamples( const SharedSampleBuffer inputBuffer,
const int numChans,
const int inputStartFrame,
const int numFrames,
Array<float>& outputBuffer )
{
for ( int chanNum = 0; chanNum < numChans; ++chanNum )
{
const float* sampleData = inputBuffer->getReadPointer( chanNum, inputStartFrame );
for ( int frameNum = 0; frameNum < numFrames; ++frameNum )
{
outputBuffer.set( numChans * frameNum + chanNum, // Index
sampleData[ frameNum ] ); // Value
}
}
}
void AudioFileHandler::deinterleaveSamples( Array<float>& inputBuffer,
const int numChans,
const int outputStartFrame,
const int numFrames,
SharedSampleBuffer outputBuffer )
{
const float* inputSampleData = inputBuffer.getRawDataPointer();
for ( int chanNum = 0; chanNum < numChans; ++chanNum )
{
float* outputSampleData = outputBuffer->getWritePointer( chanNum, outputStartFrame );
for ( int frameNum = 0; frameNum < numFrames; ++frameNum )
{
outputSampleData[ frameNum ] = inputSampleData[ numChans * frameNum + chanNum ];
}
}
}
bool AudioFileHandler::convertSampleRate( const SharedSampleBuffer inputBuffer,
const qreal sampleRateRatio,
Array<float>& outputBuffer )
{
const int inputNumFrames = inputBuffer->getNumFrames();
const int numChans = inputBuffer->getNumChannels();
const long outputNumFrames = roundToIntAccurate( inputNumFrames * sampleRateRatio );
if ( outputBuffer.size() != outputNumFrames * numChans )
{
outputBuffer.resize( outputNumFrames * numChans );
}
Array<float> tempBuffer;
tempBuffer.resize( inputNumFrames * numChans );
interleaveSamples( inputBuffer, numChans, 0, inputNumFrames, tempBuffer );
SRC_DATA srcData;
memset( &srcData, 0, sizeof( SRC_DATA ) );
srcData.data_in = tempBuffer.getRawDataPointer();
srcData.data_out = outputBuffer.getRawDataPointer();
srcData.input_frames = inputNumFrames;
srcData.output_frames = outputNumFrames;
srcData.src_ratio = sampleRateRatio;
bool isSuccessful = true;
const int errorCode = src_simple( &srcData, SRC_SINC_BEST_QUALITY, numChans );
if ( errorCode > 0 )
{
s_errorTitle = "Couldn't convert sample rate!";
s_errorInfo = src_strerror( errorCode );
isSuccessful = false;
}
return isSuccessful;
}
bool AudioFileHandler::sndfileSaveAudioFile( SNDFILE* fileID, const SharedSampleBuffer sampleBuffer, const int hopSize )
{
const int totalNumFrames = sampleBuffer->getNumFrames();
const int numChans = sampleBuffer->getNumChannels();
int numFramesToWrite = 0;
int startFrame = 0;
int numSamplesWritten = 0;
Array<float> tempBuffer;
tempBuffer.resize( hopSize * numChans );
bool isSuccessful = true;
do
{
numFramesToWrite = totalNumFrames - startFrame >= hopSize ? hopSize : totalNumFrames - startFrame;
interleaveSamples( sampleBuffer, numChans, startFrame, numFramesToWrite, tempBuffer );
numSamplesWritten = sf_write_float( fileID, tempBuffer.getRawDataPointer(), numFramesToWrite * numChans );
if ( numSamplesWritten != numFramesToWrite * numChans )
{
sndfileRecordWriteError( numFramesToWrite * numChans, numSamplesWritten );
isSuccessful = false;
}
startFrame += hopSize;
}
while ( numFramesToWrite == hopSize && isSuccessful );
return isSuccessful;
}
bool AudioFileHandler::sndfileSaveAudioFile( SNDFILE* fileID, const Array<float> interleavedBuffer, const int hopSize )
{
const int totalNumSamples = interleavedBuffer.size();
int numSamplesToWrite = 0;
int startSample = 0;
int numSamplesWritten = 0;
Array<float> tempBuffer;
tempBuffer.resize( hopSize );
bool isSuccessful = true;
do
{
numSamplesToWrite = totalNumSamples - startSample >= hopSize ? hopSize : totalNumSamples - startSample;
for ( int i = 0; i < numSamplesToWrite; i++ )
{
tempBuffer.setUnchecked( i, interleavedBuffer.getUnchecked( startSample + i ) );
}
numSamplesWritten = sf_write_float( fileID, tempBuffer.getRawDataPointer(), numSamplesToWrite );
if ( numSamplesWritten != numSamplesToWrite )
{
sndfileRecordWriteError( numSamplesToWrite, numSamplesWritten );
isSuccessful = false;
}
startSample += hopSize;
}
while ( numSamplesToWrite == hopSize && isSuccessful );
return isSuccessful;
}
void AudioFileHandler::sndfileRecordWriteError( const int numSamplesToWrite, const int numSamplesWritten )
{
const QString samplesToWrite = QString::number( numSamplesToWrite );
const QString samplesWritten = QString::number( numSamplesWritten );
s_errorTitle = "Error while writing to audio file";
s_errorInfo = "no. of samples to write: " + samplesToWrite + ", " +
"no. of samples written: " + samplesWritten;
}
SharedSampleBuffer AudioFileHandler::sndfileLoadFile( const char* filePath, sf_count_t startFrame, sf_count_t numFramesToRead )
{
const sf_count_t hopSize = 4096;
SharedSampleBuffer sampleBuffer;
Array<float> tempBuffer;
SF_INFO sfInfo;
memset( &sfInfo, 0, sizeof( SF_INFO ) );
SNDFILE* fileID = sf_open( filePath, SFM_READ, &sfInfo );
if ( fileID == NULL )
{
s_errorTitle = "Couldn't open file for reading!";
s_errorInfo = sf_strerror( NULL );
goto end;
}
if ( sfInfo.channels < 1 )
{
mus_error( MUS_NO_CHANNEL, "File has no audio channels!" );
goto end;
}
if ( sfInfo.channels > 2 )
{
mus_error( MUS_UNSUPPORTED_DATA_FORMAT, "Only mono and stereo samples are supported" );
goto end;
}
tempBuffer.resize( hopSize * sfInfo.channels );
// If caller has not set `numFramesToRead` assume whole file should be read
if ( numFramesToRead < 1 ) // Read whole file
{
startFrame = 0;
numFramesToRead = 0;
sf_count_t numFramesRead = 0;
// Find the no. of frames the long way
do
{
numFramesRead = sf_readf_float( fileID, tempBuffer.getRawDataPointer(), hopSize );
numFramesToRead += numFramesRead;
}
while ( numFramesRead > 0 );
sf_seek( fileID, 0, SEEK_SET );
}
else // Read part of file
{
sf_seek( fileID, startFrame, SEEK_SET );
}
try
{
sampleBuffer = SharedSampleBuffer( new SampleBuffer( sfInfo.channels, numFramesToRead ) );
sf_count_t numFramesRead = 0;
sf_count_t totalNumFramesRead = 0;
do
{
numFramesRead = sf_readf_float( fileID, tempBuffer.getRawDataPointer(), hopSize );
deinterleaveSamples( tempBuffer, sfInfo.channels, totalNumFramesRead, numFramesRead, sampleBuffer );
totalNumFramesRead += numFramesRead;
}
while ( numFramesRead > 0 && totalNumFramesRead < numFramesToRead );
}
catch ( std::bad_alloc& )
{
mus_error( MUS_MEMORY_ALLOCATION_FAILED, "Not enough memory to load audio file" );
}
sf_close( fileID );
end:
return sampleBuffer;
}
int AudioFileHandler::sndlibInit()
{
if ( mus_sound_initialize() == MUS_ERROR )
{
return MUS_ERROR;
}
mus_error_set_handler( sndlibRecordError );
return MUS_NO_ERROR;
}
void AudioFileHandler::sndlibRecordError( int errorCode, char* errorMessage )
{
s_errorTitle = mus_error_type_to_string( errorCode );
s_errorInfo = errorMessage;
}
SharedSampleBuffer AudioFileHandler::sndlibLoadFile( const char* filePath, mus_long_t startFrame, mus_long_t numFramesToRead )
{
int fileID = 0;
int numChans = 0;
mus_long_t numFramesRead = 0;
SharedSampleBuffer sampleBuffer;
if ( ! mus_header_type_p( mus_sound_header_type(filePath) ) )
{
goto end;
}
if ( ! mus_data_format_p( mus_sound_data_format(filePath) ) )
{
goto end;
}
numChans = mus_sound_chans( filePath );
if ( numChans == MUS_ERROR )
{
goto end;
}
if ( numChans < 1 )
{
mus_error( MUS_NO_CHANNEL, "File has no audio channels!" );
goto end;
}
if ( numChans > 2 )
{
mus_error( MUS_UNSUPPORTED_DATA_FORMAT, "Only mono and stereo samples are supported" );
goto end;
}
if ( mus_sound_srate(filePath) == MUS_ERROR )
{
goto end;
}
// If caller has not set `numFramesToRead` assume whole file should be read
if ( numFramesToRead < 1 )
{
startFrame = 0;
numFramesToRead = mus_sound_frames( filePath );
if ( numFramesToRead == MUS_ERROR )
{
goto end;
}
}
try
{
sampleBuffer = SharedSampleBuffer( new SampleBuffer( numChans, numFramesToRead ) );
fileID = mus_sound_open_input( filePath );
if ( fileID == MUS_ERROR )
{
goto end;
}
if ( mus_file_seek_frame( fileID, startFrame ) == MUS_ERROR )
{
mus_sound_close_input( fileID );
goto end;
}
numFramesRead = mus_file_read( fileID,
0,
numFramesToRead - 1,
numChans,
sampleBuffer->getArrayOfWritePointers() );
if ( numFramesRead == MUS_ERROR )
{
mus_sound_close_input( fileID );
sampleBuffer.clear();
goto end;
}
mus_sound_close_input( fileID );
}
catch ( std::bad_alloc& )
{
mus_error( MUS_MEMORY_ALLOCATION_FAILED, "Not enough memory to load audio file" );
}
end:
return sampleBuffer;
}
SharedSampleBuffer AudioFileHandler::aubioLoadFile( const char* filePath, uint_t startFrame, uint_t numFramesToRead )
{
const uint_t hopSize = 4096;
uint_t sampleRate = 0; // If `0` is passed as `samplerate` to new_aubio_source, the sample rate of the original file is used.
uint_t endFrame = 0; // Exclusive
uint_t destStartFrame = 0; // Inclusive
uint_t numFramesRead = 0;
uint_t numFramesToCopy = 0;
uint_t numChans = 0;
aubio_source_t* aubioSource = new_aubio_source( const_cast<char*>(filePath), sampleRate, hopSize );
fmat_t* sampleData = NULL;
SharedSampleBuffer sampleBuffer;
if ( aubioSource != NULL )
{
sampleRate = aubio_source_get_samplerate( aubioSource );
numChans = aubio_source_get_channels( aubioSource );
if ( numChans > 2 )
{
mus_error( MUS_UNSUPPORTED_DATA_FORMAT, "Only mono and stereo samples are supported" );
}
else
{
sampleData = new_fmat( numChans, hopSize );
if ( sampleData != NULL )
{
// If caller has not set `numFramesToRead` assume whole file should be read
if ( numFramesToRead < 1 ) // Read whole file
{
startFrame = 0;
numFramesToRead = 0;
// Work out the no. of frames the long way
do
{
aubio_source_do_multi( aubioSource, sampleData, &numFramesRead );
numFramesToRead += numFramesRead;
}
while ( numFramesRead == hopSize );
aubio_source_seek( aubioSource, 0 );
numFramesRead = 0;
}
else // Read part of file
{
aubio_source_seek( aubioSource, startFrame );
}
endFrame = startFrame + numFramesToRead;
fmat_zeros( sampleData );
try
{
sampleBuffer = SharedSampleBuffer( new SampleBuffer( numChans, numFramesToRead ) );
// Read audio data from file
do
{
aubio_source_do_multi( aubioSource, sampleData, &numFramesRead );
numFramesToCopy = startFrame + numFramesRead <= endFrame ?
numFramesRead : endFrame - startFrame;
for ( uint_t chanNum = 0; chanNum < numChans; chanNum++ )
{
sampleBuffer->copyFrom( chanNum, destStartFrame, sampleData->data[ chanNum ], numFramesToCopy );
}
startFrame += numFramesRead;
destStartFrame += numFramesRead;
}
while ( startFrame < endFrame );
}
catch ( std::bad_alloc& )
{
mus_error( MUS_MEMORY_ALLOCATION_FAILED, "Not enough memory to load audio file" );
}
del_fmat( sampleData );
}
}
del_aubio_source( aubioSource );
}
return sampleBuffer;
}
| rock-hopper/shuriken | src/audiofilehandler.cpp | C++ | gpl-2.0 | 21,603 |
/* Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2011 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "GlideState.hpp"
#include <math.h>
#include "Util/Quadratic.hpp"
#include "Navigation/SpeedVector.hpp"
/**
* Quadratic function solver for MacCready theory constraint equation
*
* - document this equation!
*/
class AverageSpeedSolver: public Quadratic
{
public:
/**
* Constructor.
*
* @param task Task to initialse solver for
* @param V Speed (m/s)
*
* @return Initialised object (not solved)
*/
AverageSpeedSolver(const fixed dwcostheta, const fixed wind_speed_squared,
const fixed V) :
Quadratic(dwcostheta, wind_speed_squared - V * V)
{
}
/**
* Find ground speed from task and wind
*
* @return Ground speed during cruise (m/s)
*/
gcc_pure
fixed
Solve() const
{
if (Check())
/// @todo check this is correct for all theta
return SolutionMax();
return -fixed_one;
}
};
fixed
GlideState::CalcAverageSpeed(const fixed Veff) const
{
if (wind.is_non_zero()) {
// only need to solve if positive wind speed
return AverageSpeedSolver(head_wind_doubled, wind_speed_squared, Veff).Solve();
}
return Veff;
}
// dummy task
GlideState::GlideState(const GeoVector &vector, const fixed htarget,
fixed altitude, const SpeedVector wind) :
vector(vector),
min_height(htarget),
altitude_difference(altitude - min_height)
{
CalcSpeedups(wind);
}
void
GlideState::CalcSpeedups(const SpeedVector _wind)
{
if (_wind.is_non_zero()) {
wind = _wind;
effective_wind_angle = wind.bearing.Reciprocal() - vector.Bearing;
wind_speed_squared = wind.norm * wind.norm;
head_wind = -wind.norm * effective_wind_angle.cos();
head_wind_doubled = fixed_two * head_wind;
} else {
wind.bearing = Angle::zero();
wind.norm = fixed_zero;
effective_wind_angle = Angle::zero();
head_wind = fixed_zero;
wind_speed_squared = fixed_zero;
head_wind_doubled = fixed_zero;
}
}
fixed
GlideState::DriftedDistance(const fixed t_cl) const
{
if (wind.is_zero())
return vector.Distance;
const Angle wd = wind.bearing.Reciprocal();
fixed sinwd, coswd;
wd.sin_cos(sinwd, coswd);
const Angle tb = vector.Bearing;
fixed sintb, costb;
tb.sin_cos(sintb, costb);
const fixed aw = wind.norm * t_cl;
const fixed dx = vector.Distance * sintb - aw * sinwd;
const fixed dy = vector.Distance * costb - aw * coswd;
return hypot(dx, dy);
// ?? task.Bearing = RAD_TO_DEG*(atan2(dx,dy));
}
| smurry/XCSoar | src/Engine/GlideSolvers/GlideState.cpp | C++ | gpl-2.0 | 3,366 |
package com.dandrex.malfriends.controller.adapter;
import java.util.List;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.dandrex.malfriends.R;
import com.dandrex.malfriends.controller.util.RequestHelper;
import com.dandrex.malfriends.model.Friend;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class FriendAdapter extends ArrayAdapter<Friend> {
private List<Friend> friendsList;
private static ImageLoader imageLoader;
public FriendAdapter(Context context, List<Friend> friendsList) {
super(context, R.layout.friends_row_items, friendsList);
this.friendsList=friendsList;
imageLoader=RequestHelper.getImageLoader();
}
@SuppressLint("InflateParams")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = convertView;
Holder holder;
Friend friend = friendsList.get(position);
if (view==null) {
holder=new Holder();
view = inflater.inflate(R.layout.friends_row_items, null);
holder.image= (NetworkImageView) view.findViewById(R.id.friends_row_items_image);
holder.image.setDefaultImageResId(R.drawable.ic_default_avatar);
holder.image.setErrorImageResId(R.drawable.ic_default_avatar);
holder.name = (TextView) view.findViewById(R.id.friends_row_items_name);
view.setTag(holder);
}else {
holder = (Holder) view.getTag();
}
holder.name.setText(friend.getName());
holder.image.setImageUrl(friend.getImageUrl(), imageLoader);
// Log.i("FriendAdapter", friend.getName()+" avatar: "+friend.getImageUrl());
return view;
}
private class Holder {
NetworkImageView image;
TextView name;
}
}
| DandreX/MALFriends | src/com/dandrex/malfriends/controller/adapter/FriendAdapter.java | Java | gpl-2.0 | 1,975 |
package com.richousrick.computermod.items.ram;
import com.richousrick.computermod.items.ItemCM;
public class RamCore extends ItemCM{
public RamCore() {
super();
this.setMaxStackSize(1);
}
}
| richousrick/ComputerMod | src/main/java/com/richousrick/computermod/items/ram/RamCore.java | Java | gpl-2.0 | 202 |
<?php
/**
* Order details
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.2.0
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $woocommerce;
$order = new WC_Order( $order_id );
?>
<h2><?php _e( 'Order Details', 'woocommerce' ); ?></h2>
<table class="shop_table order_details">
<thead>
<tr>
<th class="product-name"><?php _e( 'Product', 'woocommerce' ); ?></th>
<th class="product-total"><?php _e( 'Total', 'woocommerce' ); ?></th>
</tr>
</thead>
<tfoot>
<?php
if ( $totals = $order->get_order_item_totals() ) foreach ( $totals as $total ) :
?>
<tr>
<th scope="row"><?php echo $total['label']; ?></th>
<td><?php echo $total['value']; ?></td>
</tr>
<?php
endforeach;
?>
</tfoot>
<tbody>
<?php
if (sizeof($order->get_items())>0) {
$i=0; foreach($order->get_items() as $item) {
$odd_even = $i & 1 ? 'even ' : 'odd ';
$_product = get_product( $item['variation_id'] ? $item['variation_id'] : $item['product_id'] );
echo '
<tr class = "' . $odd_even . esc_attr( apply_filters( 'woocommerce_order_table_item_class', 'order_table_item', $item, $order ) ) . '">
<td class="product-name">' .
apply_filters( 'woocommerce_order_table_product_title', '<a href="' . get_permalink( $item['product_id'] ) . '">' . $item['name'] . '</a>', $item ) . ' ' .
apply_filters( 'woocommerce_order_table_item_quantity', '<strong class="product-quantity">× ' . $item['qty'] . '</strong>', $item );
//$item_meta = new WC_Order_Item_Meta( $item['item_meta'] );
//$item_meta->display();
if ( $_product && $_product->exists() && $_product->is_downloadable() && $order->is_download_permitted() ) {
$download_file_urls = $order->get_downloadable_file_urls( $item['product_id'], $item['variation_id'], $item );
$i = 0;
$links = array();
foreach ( $download_file_urls as $file_url => $download_file_url ) {
$filename = woocommerce_get_filename_from_url( $file_url );
$links[] = '<small><a href="' . $download_file_url . '">' . sprintf( __( 'Download file%s', 'woocommerce' ), ( count( $download_file_urls ) > 1 ? ' ' . ( $i + 1 ) . ': ' : ': ' ) ) . $filename . '</a></small>';
$i++;
}
echo implode( '<br/>', $links );
}
echo '</td><td class="product-total">' . $order->get_formatted_line_subtotal( $item ) . '</td></tr>';
// Show any purchase notes
if ($order->status=='completed' || $order->status=='processing') {
if ($purchase_note = get_post_meta( $_product->id, '_purchase_note', true))
echo '<tr class="product-purchase-note"><td colspan="3">' . apply_filters('the_content', $purchase_note) . '</td></tr>';
}
$i++; }
}
do_action( 'woocommerce_order_items_table', $order );
?>
</tbody>
</table>
<?php if ( get_option('woocommerce_allow_customers_to_reorder') == 'yes' && $order->status=='completed' ) : ?>
<p class="order-again">
<a href="<?php echo esc_url( $woocommerce->nonce_url( 'order_again', add_query_arg( 'order_again', $order->id, add_query_arg( 'order', $order->id, get_permalink( woocommerce_get_page_id( 'view_order' ) ) ) ) ) ); ?>" class="button"><?php _e( 'Order Again', 'woocommerce' ); ?></a>
</p>
<?php endif; ?>
<?php do_action( 'woocommerce_order_details_after_order_table', $order ); ?>
<header>
<h2><?php _e( 'Customer details', 'woocommerce' ); ?></h2>
</header>
<dl class="customer_details">
<?php
if ($order->billing_email) echo '<dt><strong>'.__( 'Email:', 'woocommerce' ).'</strong></dt><dd>'.$order->billing_email.'</dd>';
if ($order->billing_phone) echo '<dt><strong>'.__( 'Telephone:', 'woocommerce' ).'</strong></dt><dd>'.$order->billing_phone.'</dd>';
?>
</dl>
<?php if (get_option('woocommerce_ship_to_billing_address_only')=='no') : ?>
<div class="col2-set addresses">
<div class="col-1">
<?php endif; ?>
<header class="title">
<h3><?php _e( 'Billing Address', 'woocommerce' ); ?></h3>
</header>
<address><p>
<?php
if (!$order->get_formatted_billing_address()) _e( 'N/A', 'woocommerce' ); else echo $order->get_formatted_billing_address();
?>
</p></address>
<?php if (get_option('woocommerce_ship_to_billing_address_only')=='no') : ?>
</div><!-- /.col-1 -->
<div class="col-2">
<header class="title">
<h3><?php _e( 'Shipping Address', 'woocommerce' ); ?></h3>
</header>
<address><p>
<?php
if (!$order->get_formatted_shipping_address()) _e( 'N/A', 'woocommerce' ); else echo $order->get_formatted_shipping_address();
?>
</p></address>
</div><!-- /.col-2 -->
</div><!-- /.col2-set -->
<?php endif; ?>
<div class="clear"></div>
| idies/voyages_sdss_wp | wp-content/themes/wpl-galaxy/woocommerce/order/order-details.php | PHP | gpl-2.0 | 4,674 |
<?php
namespace IngeniousWeb\Skeleton\Core;
use IngeniousWeb\Skeleton\Services\System\User;
class BaseController
{
/**
* @var $user
*/
//protected $user;
/**
* @param User $user
*/
public function __construct(/*User $user*/)
{
//$this->user = $user;
}
public function title($class)
{
return get_class($class);
}
public function view($view, $title, $user, $data = [], $token)
{
require_once '../web/templates/template.php';
}
} | joshCarlisleIT/Skeleton | src/Core/BaseController.php | PHP | gpl-2.0 | 457 |