code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<?php /** * @package tikiwiki */ // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: tiki-edit_structure.php 49961 2014-02-18 19:20:40Z jonnybradley $ $section = 'wiki page'; $auto_query_args = array('page_ref_id'); require_once ('tiki-setup.php'); include_once ('lib/structures/structlib.php'); $access->check_feature(array('feature_wiki','feature_wiki_structure')); if (!isset($_REQUEST["page_ref_id"])) { $smarty->assign('msg', tra("No structure indicated")); $smarty->display("error.tpl"); die; } $access->check_permission('tiki_p_view'); if (isset($_REQUEST['move_to'])) { check_ticket('edit-structure'); $structlib->move_to_structure($_REQUEST['page_ref_id'], $_REQUEST['structure_id'], $_REQUEST['begin']); } $structure_info = $structlib->s_get_structure_info($_REQUEST["page_ref_id"]); $page_info = $structlib->s_get_page_info($_REQUEST["page_ref_id"]); $smarty->assign('page_ref_id', $_REQUEST["page_ref_id"]); $smarty->assign('structure_id', $structure_info["page_ref_id"]); $smarty->assign('structure_name', $structure_info["pageName"]); $perms = Perms::get((array('type' => 'wiki page', 'object' => $structure_info["pageName"]))); $tikilib->get_perm_object($structure_info["pageName"], 'wiki page', $page_info); // global perms still needed for logic in categorize.tpl if ( ! $perms->view ) { $smarty->assign('errortype', 401); $smarty->assign('msg', tra('You do not have permission to view this page.')); $smarty->display("error.tpl"); die; } if ($perms->edit_structures) $editable = 'y'; else $editable = 'n'; $smarty->assign('editable', $editable); $alert_categorized = array(); $alert_in_st = array(); $alert_to_remove_cats = array(); $alert_to_remove_extra_cats = array(); // start security hardened section if ($perms->edit_structures) { $smarty->assign('remove', 'n'); if (isset($_REQUEST["remove"])) { check_ticket('edit-structure'); $smarty->assign('remove', 'y'); $remove_info = $structlib->s_get_page_info($_REQUEST["remove"]); $structs = $structlib->get_page_structures($remove_info['pageName'], $structure); //If page is member of more than one structure, do not give option to remove page $single_struct = (count($structs) == 1); if ($single_struct && $perms->remove) { $smarty->assign('page_removable', 'y'); } else { $smarty->assign('page_removable', 'n'); } $smarty->assign('removepage', $_REQUEST["remove"]); $smarty->assign('removePageName', $remove_info["pageName"]); } if (isset($_REQUEST["rremove"])) { $access->check_authenticity(); $structlib->s_remove_page($_REQUEST["rremove"], false, empty($_REQUEST['page'])? '': $_REQUEST['page']); $_REQUEST["page_ref_id"] = $page_info["parent_id"]; } # TODO : Case where the index page of the structure is removed seems to be unexpected, leaving a corrupted structure if (isset($_REQUEST["sremove"])) { $access->check_authenticity(); $page = $page_info["pageName"]; $delete = $tikilib->user_has_perm_on_object($user, $page_info['pageName'], 'wiki page', 'tiki_p_remove'); $structlib->s_remove_page($_REQUEST["sremove"], $delete, empty($_REQUEST['page'])? '': $_REQUEST['page']); $_REQUEST["page_ref_id"] = $page_info["parent_id"]; } if ($prefs['feature_user_watches'] == 'y' && $tiki_p_watch_structure == 'y' && $user && !empty($_REQUEST['watch_object']) && !empty($_REQUEST['watch_action'])) { check_ticket('edit-structure'); if ($_REQUEST['watch_action'] == 'add' && !empty($_REQUEST['page'])) { $tikilib->add_user_watch($user, 'structure_changed', $_REQUEST['watch_object'], 'structure', $page, "tiki-index.php?page_ref_id=".$_REQUEST['watch_object']); } elseif ($_REQUEST['watch_action'] == 'remove') { $tikilib->remove_user_watch($user, 'structure_changed', $_REQUEST['watch_object'], 'structure'); } } if (!isset($structure_info) or !isset($page_info) ) { $smarty->assign('msg', tra("Invalid structure_id or page_ref_id")); $smarty->display("error.tpl"); die; } $smarty->assign('alert_exists', 'n'); if (isset($_REQUEST["create"])) { check_ticket('edit-structure'); if (isset($_REQUEST["pageAlias"])) { $structlib->set_page_alias($_REQUEST["page_ref_id"], $_REQUEST["pageAlias"]); } $after = null; if (isset($_REQUEST['after_ref_id'])) { $after = $_REQUEST['after_ref_id']; } if (!(empty($_REQUEST['name']))) { if ($tikilib->page_exists($_REQUEST["name"])) { $smarty->assign('alert_exists', 'y'); } $structlib->s_create_page($_REQUEST['page_ref_id'], $after, $_REQUEST['name'], '', $structure_info['page_ref_id']); $userlib->copy_object_permissions($page_info["pageName"], $_REQUEST["name"], 'wiki page'); } elseif (!empty($_REQUEST['name2'])) { foreach ($_REQUEST['name2'] as $name) { $new_page_ref_id = $structlib->s_create_page($_REQUEST['page_ref_id'], $after, $name, '', $structure_info['page_ref_id']); $after = $new_page_ref_id; } } if ($prefs['feature_wiki_categorize_structure'] == 'y') { global $categlib; include_once('lib/categories/categlib.php'); $pages_added = array(); if (!(empty($_REQUEST['name']))) { $pages_added[] = $_REQUEST['name']; } elseif (!empty($_REQUEST['name2'])) { foreach ($_REQUEST['name2'] as $name) { $pages_added[] = $name; } } $cat_type = 'wiki page'; foreach ($pages_added as $name) { $structlib->categorizeNewStructurePage($name, $structure_info); } } } if (isset($_REQUEST["move_node"])) { if ($_REQUEST["move_node"] == '1') { $structlib->promote_node($_REQUEST["page_ref_id"]); } elseif ($_REQUEST["move_node"] == '2') { $structlib->move_before_previous_node($_REQUEST["page_ref_id"]); } elseif ($_REQUEST["move_node"] == '3') { $structlib->move_after_next_node($_REQUEST["page_ref_id"]); } elseif ($_REQUEST["move_node"] == '4') { $structlib->demote_node($_REQUEST["page_ref_id"]); } } } // end of security hardening $page_info = $structlib->s_get_page_info($_REQUEST["page_ref_id"]); $smarty->assign('pageName', $page_info["pageName"]); $smarty->assign('pageAlias', $page_info["page_alias"]); $smarty->assign('topPageAlias', $structure_info["page_alias"]); $subpages = $structlib->s_get_pages($_REQUEST["page_ref_id"]); $max = count($subpages); $smarty->assign_by_ref('subpages', $subpages); if ($max != 0) { $last_child = $subpages[$max - 1]; $smarty->assign('insert_after', $last_child["page_ref_id"]); } if (isset($_REQUEST["find_objects"])) { $find_objects = $_REQUEST["find_objects"]; } else { $find_objects = ''; } $smarty->assign('find_objects', $find_objects); $filter = ''; if (!empty($_REQUEST['categId'])) { $filter['categId'] = $_REQUEST['categId']; $smarty->assign('find_categId', $_REQUEST['categId']); } else { $smarty->assign('find_categId', ''); } // Get all wiki pages for the dropdown menu $listpages = $tikilib->list_pages(0, -1, 'pageName_asc', $find_objects, '', false, true, false, false, $filter); $smarty->assign_by_ref('listpages', $listpages["data"]); $structures = $structlib->list_structures(0, -1, 'pageName_asc'); $structures_filtered = array_filter($structures['data'], function ($struct) { return $struct['editable'] === 'y'; }); $smarty->assign_by_ref('structures', $structures_filtered); $subtree = $structlib->get_subtree($structure_info["page_ref_id"]); foreach ($subtree as $i=>$s) { // dammed recursivite - acn not do a left join if ($tikilib->user_watches($user, 'structure_changed', $s['page_ref_id'], 'structure')) { $subtree[$i]['event'] = true; } } $smarty->assign('subtree', $subtree); // Re-categorize if ($perms->edit_structures) { $all_editable = 'y'; foreach ($subtree as $k => $st) { if ($st['editable'] != 'y' && $k > 0) { $all_editable = 'n'; break; } } } else { $all_editable = 'n'; } $smarty->assign('all_editable', $all_editable); if (isset($_REQUEST["recategorize"]) && $prefs['feature_wiki_categorize_structure'] == 'y' && $all_editable == 'y') { $cat_name = $structure_info["pageName"]; $cat_objid = $cat_name; $cat_href="tiki-index.php?page=" . urlencode($cat_name); $cat_desc = ''; $cat_type='wiki page'; include_once("categorize.php"); $categories = array(); // needed to prevent double entering (the first time when page is being categorized in categorize.php) //include_once("categorize_list.php"); // needs to be up here to avoid picking up selection of cats from other existing sub-pages //get array of pages in structure $othobjid = $structlib->s_get_structure_pages($structure_info["page_ref_id"]); foreach ($othobjid as $othobjs) { if ($othobjs["parent_id"] > 0) { // check for page being in other structure. $strucs = $structlib->get_page_structures($othobjs["pageName"]); if (count($strucs) > 1) { $alert_in_st[] = $othobjs["pageName"]; } $cat_objid = $othobjs["pageName"]; $cat_name = $cat_objid; $cat_href = "tiki-index.php?page=".urlencode($cat_objid); $catObjectId = $categlib->is_categorized($cat_type, $cat_objid); if (!$catObjectId) { // page that is added is not categorized -> categorize it if necessary if (isset($_REQUEST["cat_categorize"]) && $_REQUEST["cat_categorize"] == 'on' && isset($_REQUEST["cat_categories"])) { $catObjectId = $categlib->add_categorized_object($cat_type, $cat_objid, $cat_desc, $cat_name, $cat_href); foreach ($_REQUEST["cat_categories"] as $cat_acat) { $categlib->categorize($catObjectId, $cat_acat); } } } else { // page that is added is categorized if (!isset($_REQUEST["cat_categories"]) || !isset($_REQUEST["cat_categorize"]) || isset($_REQUEST["cat_categorize"]) && $_REQUEST["cat_categorize"] != 'on') { if ($_REQUEST["cat_override"] == "on") { $categlib->uncategorize_object($cat_type, $cat_objid); } else { $alert_to_remove_cats[] = $cat_name; } } else { if ($_REQUEST["cat_override"] == "on") { $categlib->uncategorize_object($cat_type, $cat_objid); foreach ($_REQUEST["cat_categories"] as $cat_acat) { $catObjectId = $categlib->is_categorized($cat_type, $cat_objid); if (!$catObjectId) { // The object is not categorized $catObjectId = $categlib->add_categorized_object($cat_type, $cat_objid, $cat_desc, $cat_name, $cat_href); } $categlib->categorize($catObjectId, $cat_acat); } } else { $cats = $categlib->get_object_categories($cat_type, $cat_objid); $numberofcats = count($cats); foreach ($_REQUEST["cat_categories"] as $cat_acat) { if (!in_array($cat_acat, $cats, true)) { $categlib->categorize($catObjectId, $cat_acat); $numberofcats += 1; } } if ($numberofcats > count($_REQUEST["cat_categories"])) { $alert_to_remove_extra_cats[] = $cat_name; } } } } } } } $smarty->assign('alert_in_st', $alert_in_st); $smarty->assign('alert_categorized', $alert_categorized); $smarty->assign('alert_to_remove_cats', $alert_to_remove_cats); $smarty->assign('alert_to_remove_extra_cats', $alert_to_remove_extra_cats); if ($prefs['feature_wiki_categorize_structure'] == 'y' && $all_editable == 'y') { $cat_name = $structure_info["pageName"]; $cat_objid = $cat_name; $cat_href="tiki-index.php?page=" . urlencode($cat_name); $cat_desc = ''; $cat_type='wiki page'; include_once("categorize_list.php"); } elseif ($prefs['feature_categories'] == 'y') { global $categlib; include_once('lib/categories/categlib.php'); $categories = $categlib->getCategories(); $smarty->assign_by_ref('categories', $categories); } ask_ticket('edit-structure'); include_once ('tiki-section_options.php'); if ($prefs['feature_jquery_ui'] === 'y') { $headerlib->add_jsfile('lib/structures/tiki-edit_structure.js'); $headerlib->add_jsfile('vendor/jquery/plugins/nestedsortable/jquery.ui.nestedSortable.js'); global $structlib; include_once('lib/structures/structlib.php'); $structure_id = $structure_info['structure_id']; if (!$structure_id) { $structure_id = $structure_info['page_ref_id']; } $smarty->assign('nodelist', $structlib->get_toc($structure_id, 'asc', false, false, '', 'admin', $page_info['page_ref_id'], 0, '')); // $page_ref_id,$order='asc',$showdesc=false,$numbering=true,$numberPrefix='',$type='plain',$page='',$maxdepth=0, $structurePageName='' $smarty->assign('structure_id', $structure_id); } // disallow robots to index page: $smarty->assign('metatag_robots', 'NOINDEX, NOFOLLOW'); // Display the template $smarty->assign('mid', 'tiki-edit_structure.tpl'); $smarty->display("tiki.tpl");
upsafety/ToCiteWiki
tiki-edit_structure.php
PHP
lgpl-2.1
12,806
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2004-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // #include "MarbleDirs.h" #include "MarbleDebug.h" #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QString> #include <QtCore/QStringList> #include <QtGui/QApplication> #include <stdlib.h> #ifdef Q_OS_MACX //for getting app bundle path #include <ApplicationServices/ApplicationServices.h> #endif #ifdef Q_OS_WIN //for getting appdata path //mingw-w64 Internet Explorer 5.01 #define _WIN32_IE 0x0501 #include <shlobj.h> #endif #include <config-marble.h> using namespace Marble; namespace { QString runTimeMarbleDataPath = ""; QString runTimeMarblePluginPath = ""; } MarbleDirs::MarbleDirs() : d( 0 ) { } QString MarbleDirs::path( const QString& relativePath ) { QString localpath = localPath() + '/' + relativePath; // local path QString systempath = systemPath() + '/' + relativePath; // system path QString fullpath = systempath; if ( QFile::exists( localpath ) ) { fullpath = localpath; } return QDir( fullpath ).canonicalPath(); } QString MarbleDirs::pluginPath( const QString& relativePath ) { QString localpath = pluginLocalPath() + QDir::separator() + relativePath; // local path QString systempath = pluginSystemPath() + QDir::separator() + relativePath; // system path QString fullpath = systempath; if ( QFile::exists( localpath ) ) { fullpath = localpath; } return QDir( fullpath ).canonicalPath(); } QStringList MarbleDirs::entryList( const QString& relativePath, QDir::Filters filters ) { QStringList filesLocal = QDir( MarbleDirs::localPath() + '/' + relativePath ).entryList(filters); QStringList filesSystem = QDir( MarbleDirs::systemPath() + '/' + relativePath ).entryList(filters); QStringList allFiles( filesLocal ); allFiles << filesSystem; // remove duplicate entries allFiles.sort(); for ( int i = 1; i < allFiles.size(); ++i ) { if ( allFiles.at(i) == allFiles.at( i - 1 ) ) { allFiles.removeAt(i); --i; } } return allFiles; } QStringList MarbleDirs::pluginEntryList( const QString& relativePath, QDir::Filters filters ) { QStringList filesLocal = QDir( MarbleDirs::pluginLocalPath() + '/' + relativePath ).entryList(filters); QStringList filesSystem = QDir( MarbleDirs::pluginSystemPath() + '/' + relativePath ).entryList(filters); QStringList allFiles( filesLocal ); allFiles << filesSystem; // remove duplicate entries allFiles.sort(); for ( int i = 1; i < allFiles.size(); ++i ) { if ( allFiles.at(i) == allFiles.at( i - 1 ) ) { allFiles.removeAt(i); --i; } } return allFiles; } QString MarbleDirs::systemPath() { QString systempath; #ifdef Q_OS_MACX // // On OSX lets try to find any file first in the bundle // before branching out to home and sys dirs // CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle); const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding()); CFRelease(myBundleRef); CFRelease(myMacPath); QString myPath(mypPathPtr); //do some magick so that we can still find data dir if //marble was not built as a bundle if (myPath.contains(".app")) //its a bundle! { systempath = myPath + "/Contents/Resources/data"; } if ( QFile::exists( systempath ) ){ return systempath; } #endif // mac bundle // Should this happen before the Mac bundle already? if ( !runTimeMarbleDataPath.isEmpty() ) return runTimeMarbleDataPath; #ifdef MARBLE_DATA_PATH //MARBLE_DATA_PATH is a compiler define set by cmake QString compileTimeMarbleDataPath(MARBLE_DATA_PATH); if(QDir(compileTimeMarbleDataPath).exists()) return compileTimeMarbleDataPath; #endif // MARBLE_DATA_PATH return QDir( QCoreApplication::applicationDirPath() #if defined(QTONLY) + QLatin1String( "/data" ) #else + QLatin1String( "/../share/apps/marble/data" ) #endif ).canonicalPath(); } QString MarbleDirs::pluginSystemPath() { QString systempath; #ifdef Q_OS_MACX // // On OSX lets try to find any file first in the bundle // before branching out to home and sys dirs // CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle); const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding()); CFRelease(myBundleRef); CFRelease(myMacPath); QString myPath(mypPathPtr); //do some magick so that we can still find data dir if //marble was not built as a bundle if (myPath.contains(".app")) //its a bundle! { systempath = myPath + "/Contents/Resources/plugins"; } if ( QFile::exists( systempath ) ){ return systempath; } #endif // mac bundle // Should this happen before the Mac bundle already? if ( !runTimeMarblePluginPath.isEmpty() ) return runTimeMarblePluginPath; #ifdef MARBLE_PLUGIN_PATH //MARBLE_PLUGIN_PATH is a compiler define set by cmake QString compileTimeMarblePluginPath(MARBLE_PLUGIN_PATH); if(QDir(compileTimeMarblePluginPath).exists()) return compileTimeMarblePluginPath; #endif // MARBLE_PLUGIN_PATH return QDir( QCoreApplication::applicationDirPath() #if defined(QTONLY) + QLatin1String( "/plugins" ) #else + QLatin1String( "/../lib/kde4/plugins/marble" ) #endif ).canonicalPath(); } QString MarbleDirs::localPath() { #ifndef Q_OS_WIN QString dataHome = getenv( "XDG_DATA_HOME" ); if( dataHome.isEmpty() ) dataHome = QDir::homePath() + "/.local/share"; return dataHome + "/marble"; // local path #else HWND hwnd = 0; WCHAR *appdata_path = new WCHAR[MAX_PATH+1]; SHGetSpecialFolderPathW( hwnd, appdata_path, CSIDL_APPDATA, 0 ); QString appdata = QString::fromUtf16( reinterpret_cast<ushort*>( appdata_path ) ); delete[] appdata_path; return QString( QDir::fromNativeSeparators( appdata ) + "/.marble/data" ); // local path #endif } QStringList MarbleDirs::oldLocalPaths() { QStringList possibleOldPaths; #ifndef Q_OS_WIN QString oldDefault = QDir::homePath() + "/.marble/data"; possibleOldPaths.append( oldDefault ); QString xdgDefault = QDir::homePath() + "/.local/share/marble"; possibleOldPaths.append( xdgDefault ); QString xdg = getenv( "XDG_DATA_HOME" ); xdg += "/marble/"; possibleOldPaths.append( xdg ); #endif QString currentLocalPath = QDir( MarbleDirs::localPath() ).canonicalPath(); QStringList oldPaths; foreach( const QString& possibleOldPath, possibleOldPaths ) { if( !QDir().exists( possibleOldPath ) ) { continue; } QString canonicalPossibleOldPath = QDir( possibleOldPath ).canonicalPath(); if( canonicalPossibleOldPath == currentLocalPath ) { continue; } oldPaths.append( canonicalPossibleOldPath ); } return oldPaths; } QString MarbleDirs::pluginLocalPath() { #ifndef Q_OS_WIN return QString( QDir::homePath() + "/.marble/plugins" ); // local path #else HWND hwnd = 0; WCHAR *appdata_path = new WCHAR[MAX_PATH+1]; SHGetSpecialFolderPathW( hwnd, appdata_path, CSIDL_APPDATA, 0 ); QString appdata = QString::fromUtf16( reinterpret_cast<ushort*>( appdata_path ) ); delete[] appdata_path; return QString( QDir::fromNativeSeparators( appdata ) + "/.marble/plugins" ); // local path #endif } QString MarbleDirs::marbleDataPath() { return runTimeMarbleDataPath; } QString MarbleDirs::marblePluginPath() { return runTimeMarblePluginPath; } void MarbleDirs::setMarbleDataPath( const QString& adaptedPath ) { if ( !QDir::root().exists( adaptedPath ) ) { qWarning() << QString( "Invalid MarbleDataPath \"%1\". Using \"%2\" instead." ).arg( adaptedPath ).arg( systemPath() ); return; } runTimeMarbleDataPath = adaptedPath; } void MarbleDirs::setMarblePluginPath( const QString& adaptedPath ) { if ( !QDir::root().exists( adaptedPath ) ) { qWarning() << QString( "Invalid MarblePluginPath \"%1\". Using \"%2\" instead." ).arg( adaptedPath ).arg( pluginSystemPath() ); return; } runTimeMarblePluginPath = adaptedPath; } void MarbleDirs::debug() { mDebug() << "=== MarbleDirs: ==="; mDebug() << "Local Path:" << localPath(); mDebug() << "Plugin Local Path:" << pluginLocalPath(); mDebug() << ""; mDebug() << "Marble Data Path (Run Time) :" << runTimeMarbleDataPath; mDebug() << "Marble Data Path (Compile Time):" << QString(MARBLE_DATA_PATH); mDebug() << ""; mDebug() << "Marble Plugin Path (Run Time) :" << runTimeMarblePluginPath; mDebug() << "Marble Plugin Path (Compile Time):" << QString(MARBLE_PLUGIN_PATH); mDebug() << ""; mDebug() << "System Path:" << systemPath(); mDebug() << "Plugin System Path:" << pluginSystemPath(); mDebug() << "==================="; }
oberluz/marble
src/lib/MarbleDirs.cpp
C++
lgpl-2.1
9,567
/* * Hibernate OGM, Domain model persistence for NoSQL datastores * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.ogm.test.integration.jboss.service; import javax.ejb.Stateless; import javax.inject.Inject; import javax.persistence.EntityManager; import org.hibernate.ogm.test.integration.jboss.model.PhoneNumber; /** * @author Mark Paluch */ @Stateless public class PhoneNumberService { @Inject private EntityManager entityManager; public PhoneNumber createPhoneNumber(String name, String value) { PhoneNumber phoneNumber = new PhoneNumber( name, value ); entityManager.persist( phoneNumber ); return phoneNumber; } public PhoneNumber getPhoneNumber(String name) { return entityManager.find( PhoneNumber.class, name ); } public void deletePhoneNumber(String name) { entityManager.remove( getPhoneNumber( name ) ); } }
uugaa/hibernate-ogm
integrationtest/redis/src/test/java/org/hibernate/ogm/test/integration/jboss/service/PhoneNumberService.java
Java
lgpl-2.1
1,003
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_HELPER_deque_H #define SOFA_HELPER_deque_H #include <sofa/helper/helper.h> #include <deque> #include <string> #include <iostream> #include <sofa/helper/logging/Messaging.h> /// adding string serialization to std::deque to make it compatible with Data /// \todo: refactoring of the containers required /// More info PR #113: https://github.com/sofa-framework/sofa/pull/113 namespace std { /// Output stream template<class T> std::ostream& operator<< ( std::ostream& os, const std::deque<T>& d ) { if( d.size()>0 ) { for( unsigned int i=0, iend=d.size()-1; i<iend; ++i ) os<<d[i]<<" "; os<<d.last(); } return os; } /// Input stream template<class T> std::istream& operator>> ( std::istream& in, std::deque<T>& d ) { T t=T(); d.clear(); while(in>>t) d.push_back(t); if( in.rdstate() & std::ios_base::eofbit ) { in.clear(); } return in; } /// Input stream /// Specialization for reading deques of int and unsigned int using "A-B" notation for all integers between A and B, optionnally specifying a step using "A-B-step" notation. template<> inline std::istream& operator>>( std::istream& in, std::deque<int>& d ) { int t; d.clear(); std::string s; while(in>>s) { std::string::size_type hyphen = s.find_first_of('-',1); if (hyphen == std::string::npos) { t = atoi(s.c_str()); d.push_back(t); } else { int t1,t2,tinc; std::string s1(s,0,hyphen); t1 = atoi(s1.c_str()); std::string::size_type hyphen2 = s.find_first_of('-',hyphen+2); if (hyphen2 == std::string::npos) { std::string s2(s,hyphen+1); t2 = atoi(s2.c_str()); tinc = (t1<t2) ? 1 : -1; } else { std::string s2(s,hyphen+1,hyphen2); std::string s3(s,hyphen2+1); t2 = atoi(s2.c_str()); tinc = atoi(s3.c_str()); if (tinc == 0) { msg_error("deque") << "parsing \""<<s<<"\": increment is 0"; tinc = (t1<t2) ? 1 : -1; } if ((t2-t1)*tinc < 0) { // increment not of the same sign as t2-t1 : swap t1<->t2 t = t1; t1 = t2; t2 = t; } } if (tinc < 0) for (t=t1; t>=t2; t+=tinc) d.push_back(t); else for (t=t1; t<=t2; t+=tinc) d.push_back(t); } } if( in.rdstate() & std::ios_base::eofbit ) { in.clear(); } return in; } /// Output stream /// Specialization for writing deques of unsigned char template<> inline std::ostream& operator<<(std::ostream& os, const std::deque<unsigned char>& d) { if( d.size()>0 ) { unsigned int i=0, iend=d.size()-1; for( ; i<iend; ++i ) os<<(int)d[i]<<" "; os<<(int)d[iend]; } return os; } /// Inpu stream /// Specialization for writing deques of unsigned char template<> inline std::istream& operator>>(std::istream& in, std::deque<unsigned char>& d) { int t; d.clear(); while(in>>t) { d.push_back((unsigned char)t); } if( in.rdstate() & std::ios_base::eofbit ) { in.clear(); } return in; } /// Input stream /// Specialization for reading deques of int and unsigned int using "A-B" notation for all integers between A and B template<> inline std::istream& operator>>( std::istream& in, std::deque<unsigned int>& d ) { unsigned int t; d.clear(); std::string s; while(in>>s) { std::string::size_type hyphen = s.find_first_of('-',1); if (hyphen == std::string::npos) { t = atoi(s.c_str()); d.push_back(t); } else { unsigned int t1,t2; int tinc; std::string s1(s,0,hyphen); t1 = (unsigned int)atoi(s1.c_str()); std::string::size_type hyphen2 = s.find_first_of('-',hyphen+2); if (hyphen2 == std::string::npos) { std::string s2(s,hyphen+1); t2 = (unsigned int)atoi(s2.c_str()); tinc = (t1<t2) ? 1 : -1; } else { std::string s2(s,hyphen+1,hyphen2); std::string s3(s,hyphen2+1); t2 = (unsigned int)atoi(s2.c_str()); tinc = atoi(s3.c_str()); if (tinc == 0) { msg_error("deque") << "parsing \""<<s<<"\": increment is 0"; tinc = (t1<t2) ? 1 : -1; } if (((int)(t2-t1))*tinc < 0) { // increment not of the same sign as t2-t1 : swap t1<->t2 t = t1; t1 = t2; t2 = t; } } if (tinc < 0) for (t=t1; t>=t2; t=(unsigned int)((int)t+tinc)) d.push_back(t); else for (t=t1; t<=t2; t=(unsigned int)((int)t+tinc)) d.push_back(t); } } if( in.rdstate() & std::ios_base::eofbit ) { in.clear(); } return in; } } // namespace std #endif
FabienPean/sofa
SofaKernel/framework/sofa/helper/deque.h
C
lgpl-2.1
7,150
package railo.transformer.cfml; import railo.runtime.exp.TemplateException; import railo.transformer.bytecode.Page; import railo.transformer.bytecode.expression.Expression; import railo.transformer.cfml.evaluator.EvaluatorPool; import railo.transformer.library.function.FunctionLib; import railo.transformer.library.tag.TagLibTag; import railo.transformer.util.CFMLString; /** * Innerhalb einer TLD (Tag Library Descriptor) kann eine Klasse angemeldet werden, * welche das Interface ExprTransfomer implementiert, * um Ausdruecke die innerhalb von Attributen und dem Body von Tags vorkommen zu transformieren. * Die Idee dieses Interface ist es die Moeglichkeit zu bieten, * weitere ExprTransfomer zu erstellen zu koennen, * um fuer verschiedene TLD, verschiedene Ausdrucksarten zu bieten. * */ public interface ExprTransformer { /** * Wird aufgerufen um aus dem uebergebenen CFMLString einen Ausdruck auszulesen * und diesen in ein CFXD Element zu uebersetzten. * <br> * Beispiel eines uebergebenen String:<br> * "session.firstName" oder "trim(left('test'&var1,3))" * * @param fld Array von Function Libraries, * Mithilfe dieser Function Libraries kann der Transfomer buil-in Funktionen innerhalb des CFML Codes erkennen * und validieren. * @param doc XML Document des aktuellen zu erstellenden CFXD * @param cfml Text der transfomiert werden soll. * @return Element CFXD Element * @throws railo.runtime.exp.TemplateException * @throws TemplateException */ public Expression transform(Page page,EvaluatorPool ep,FunctionLib[] fld,TagLibTag[] scriptTags,CFMLString cfml, TransfomerSettings settings) throws TemplateException; /** * Wird aufgerufen um aus dem uebergebenen CFMLString einen Ausdruck auszulesen * und diesen in ein CFXD Element zu uebersetzten. Es wird aber davon ausgegangen das es sich um einen String handelt. * <br> * Beispiel eines uebergebenen String:<br> * "session.firstName" oder "trim(left('test'&var1,3))" * * @param fld Array von Function Libraries, * Mithilfe dieser Function Libraries kann der Transfomer buil-in Funktionen innerhalb des CFML Codes erkennen * und validieren. * @param doc XML Document des aktuellen zu erstellenden CFXD * @param cfml Text der transfomiert werden soll. * @return Element CFXD Element * @throws TemplateException */ public Expression transformAsString(Page page,EvaluatorPool ep,FunctionLib[] fld,TagLibTag[] scriptTags,CFMLString cfml, TransfomerSettings settings,boolean allowLowerThan) throws TemplateException; }
modius/railo
railo-java/railo-core/src/railo/transformer/cfml/ExprTransformer.java
Java
lgpl-2.1
2,618
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.workplace.explorer.menu; import org.opencms.file.CmsObject; import org.opencms.util.CmsStringUtil; import org.opencms.workplace.explorer.CmsResourceUtil; /** * Defines a menu item rule that sets the visibility to invisible * if the current resource is opened via the sitemap.<p> * * @since 8.0.0 */ public class CmsMirSitemapInvisible extends A_CmsMenuItemRule { /** * @see org.opencms.workplace.explorer.menu.I_CmsMenuItemRule#getVisibility(org.opencms.file.CmsObject, CmsResourceUtil[]) */ @Override public CmsMenuItemVisibilityMode getVisibility(CmsObject cms, CmsResourceUtil[] resourceUtil) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } /** * @see org.opencms.workplace.explorer.menu.I_CmsMenuItemRule#matches(org.opencms.file.CmsObject, org.opencms.workplace.explorer.CmsResourceUtil[]) */ public boolean matches(CmsObject cms, CmsResourceUtil[] resourceUtil) { String context = (String)cms.getRequestContext().getAttribute(I_CmsMenuItemRule.ATTR_CONTEXT_INFO); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(context)) { return context.toLowerCase().equals(I_CmsMenuItemRule.CONTEXT_SITEMAP); } return false; } }
mediaworx/opencms-core
src/org/opencms/workplace/explorer/menu/CmsMirSitemapInvisible.java
Java
lgpl-2.1
2,371
package net.minecraftforge.items; import net.minecraft.item.ItemStack; public interface IItemHandler { /** * Returns the number of slots available * * @return The number of slots available **/ int getSlots(); /** * Returns the ItemStack in a given slot. * * The result's stack size may be greater than the itemstacks max size. * * If the result is null, then the slot is empty. * If the result is not null but the stack size is zero, then it represents * an empty slot that will only accept* a specific itemstack. * * <p/> * IMPORTANT: This ItemStack MUST NOT be modified. This method is not for * altering an inventories contents. Any implementers who are able to detect * modification through this method should throw an exception. * <p/> * SERIOUSLY: DO NOT MODIFY THE RETURNED ITEMSTACK * * @param slot Slot to query * @return ItemStack in given slot. May be null. **/ ItemStack getStackInSlot(int slot); /** * Inserts an ItemStack into the given slot and return the remainder. * Note: This behaviour is subtly different from IFluidHandlers.fill() * * @param slot Slot to insert into. * @param stack ItemStack to insert * @param simulate If true, the insertion is only simulated * @return The remaining ItemStack that was not inserted (if the entire stack is accepted, then return null) **/ ItemStack insertItem(int slot, ItemStack stack, boolean simulate); /** * Extracts an ItemStack from the given slot. The returned value must be null * if nothing is extracted, otherwise it's stack size must not be greater than amount or the * itemstacks getMaxStackSize(). * * @param slot Slot to extract from. * @param amount Amount to extract (may be greater than the current stacks max limit) * @param simulate If true, the extraction is only simulated * @return ItemStack extracted from the slot, must be null, if nothing can be extracted **/ ItemStack extractItem(int slot, int amount, boolean simulate); }
CrafterKina/MinecraftForge
src/main/java/net/minecraftforge/items/IItemHandler.java
Java
lgpl-2.1
2,151
"""a readline console module (unix only). maxime.tournier@brain.riken.jp the module starts a subprocess for the readline console and communicates through pipes (prompt/cmd). the console is polled through a timer, which depends on PySide. """ from select import select import os import sys import signal if __name__ == '__main__': import readline # prompt input stream fd_in = int(sys.argv[1]) file_in = os.fdopen( fd_in ) # cmd output stream fd_out = int(sys.argv[2]) file_out = os.fdopen( fd_out, 'w' ) # some helpers def send(data): file_out.write(data + '\n') file_out.flush() def recv(): while True: res = file_in.readline().rstrip('\n') read, _, _ = select([ file_in ], [], [], 0) if not read: return res class History: """readline history safe open/close""" def __init__(self, filename): self.filename = os.path.expanduser( filename ) def __enter__(self): try: readline.read_history_file(self.filename) # print 'loaded console history from', self.filename except IOError: pass return self def __exit__(self, type, value, traceback): readline.write_history_file( self.filename ) def cleanup(*args): print('console cleanup') os.system('stty sane') for sig in [signal.SIGQUIT, signal.SIGTERM, signal.SIGILL, signal.SIGSEGV]: old = signal.getsignal(sig) def new(*args): cleanup() signal.signal(sig, old) os.kill(os.getpid(), sig) signal.signal(sig, new) # main loop try: with History( "~/.sofa-console" ): print 'console started' while True: send( raw_input( recv() ) ) except KeyboardInterrupt: print 'console exited (SIGINT)' except EOFError: ppid = os.getppid() try: os.kill(os.getppid(), signal.SIGTERM) print 'console exited (EOF), terminating parent process' except OSError: pass else: import subprocess import code import atexit _cleanup = None def _register( c ): global _cleanup if _cleanup: _cleanup() _cleanup = c class Console(code.InteractiveConsole): def __init__(self, locals = None, timeout = 100): """ python interpreter taking input from console subprocess scope is provided through 'locals' (usually: locals() or globals()) 'timeout' (in milliseconds) sets how often is the console polled. """ code.InteractiveConsole.__init__(self, locals) if timeout >= 0: def callback(): self.poll() from PySide import QtCore self.timer = QtCore.QTimer() self.timer.timeout.connect( callback ) self.timer.start( timeout ) _register( lambda: self.timer.stop() ) # execute next command, blocks on console input def next(self): line = recv() data = '>>> ' if self.push( line ): data = '... ' send( data ) # convenience def poll(self): if ready(): self.next() # send prompt to indicate we are ready def send(data): prompt_out.write(data + '\n') prompt_out.flush() # receive command line def recv(): res = cmd_in.readline() if res: return res.rstrip('\n') return res # is there any available command ? def ready(): read, _, _ = select([ cmd_in ], [], [], 0) return read # communication pipes prompt = os.pipe() cmd = os.pipe() # subprocess with in/out fd, and forwarding stdin sub = subprocess.Popen(['python', __file__, str(prompt[0]), str(cmd[1])], stdin = sys.stdin) # open the tubes ! prompt_out = os.fdopen(prompt[1], 'w') cmd_in = os.fdopen(cmd[0], 'r') # we're ready send('>>> ') # def cleanup(*args): # print('console cleanup') # os.system('stty sane') # def exit(*args): # print 'exit' # cleanup() # sys.exit(0) forces cleanup *from python* before the gui # closes. otherwise pyside causes segfault on python finalize. def handler(*args): sub.terminate() sub.wait() sys.exit(0) from PySide import QtCore app = QtCore.QCoreApplication.instance() app.aboutToQuit.connect( handler ) # import atexit # atexit.register( handler ) # import atexit # atexit.register( exit ) # for sig in [signal.SIGSEGV, signal.SIGILL]: # old = signal.getsignal(sig) # def h(*args): # print args # sub.terminate() # signal.signal(sig, old) # os.kill(os.getpid(), sig) # signal.signal(sig, h)
FabienPean/sofa
applications/plugins/SofaPython/python/SofaPython/console.py
Python
lgpl-2.1
5,349
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="sr" sourcelanguage="en"> <context> <name>CmdRobotAddToolShape</name> <message> <location filename="../../CommandInsertRobot.cpp" line="215"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandInsertRobot.cpp" line="216"/> <source>Add tool</source> <translation>Додаj алат</translation> </message> <message> <location filename="../../CommandInsertRobot.cpp" line="217"/> <source>Add a tool shape to the robot</source> <translation>Додај алат за облик роботу</translation> </message> </context> <context> <name>CmdRobotConstraintAxle</name> <message> <location filename="../../Command.cpp" line="158"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../Command.cpp" line="159"/> <source>Place robot...</source> <translation>Поcтави робота...</translation> </message> <message> <location filename="../../Command.cpp" line="160"/> <source>Place a robot (experimental!)</source> <translation>Поcтави робота (екcпериментално)</translation> </message> </context> <context> <name>CmdRobotCreateTrajectory</name> <message> <location filename="../../CommandTrajectory.cpp" line="62"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="63"/> <source>Create trajectory</source> <translation>Направи путању</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="64"/> <source>Create a new empty trajectory </source> <translation>Направи нову празну путању </translation> </message> </context> <context> <name>CmdRobotEdge2Trac</name> <message> <location filename="../../CommandTrajectory.cpp" line="320"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="321"/> <source>Edge to Trajectory...</source> <translation>Руб у Путању...</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="322"/> <source>Generate a Trajectory from a set of edges</source> <translation>Створи путању од више ивица</translation> </message> </context> <context> <name>CmdRobotExportKukaCompact</name> <message> <location filename="../../CommandExport.cpp" line="50"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandExport.cpp" line="51"/> <source>Kuka compact subroutine...</source> <translation>Kuka компактни подпрограм...</translation> </message> <message> <location filename="../../CommandExport.cpp" line="52"/> <source>Export the trajectory as a compact KRL subroutine.</source> <translation>Извези путању као компактни KRL подпрограм.</translation> </message> </context> <context> <name>CmdRobotExportKukaFull</name> <message> <location filename="../../CommandExport.cpp" line="112"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandExport.cpp" line="113"/> <source>Kuka full subroutine...</source> <translation>Kuka цео подпрограм...</translation> </message> <message> <location filename="../../CommandExport.cpp" line="114"/> <source>Export the trajectory as a full KRL subroutine.</source> <translation>Извези путању као потпун KRL подпрограм.</translation> </message> </context> <context> <name>CmdRobotInsertKukaIR125</name> <message> <location filename="../../CommandInsertRobot.cpp" line="174"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandInsertRobot.cpp" line="175"/> <source>Kuka IR125</source> <translation>Kuka IR125</translation> </message> <message> <location filename="../../CommandInsertRobot.cpp" line="176"/> <source>Insert a Kuka IR125 into the document.</source> <translation>Уметни Kuka IR125 у документ.</translation> </message> </context> <context> <name>CmdRobotInsertKukaIR16</name> <message> <location filename="../../CommandInsertRobot.cpp" line="93"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandInsertRobot.cpp" line="94"/> <source>Kuka IR16</source> <translation>Kuka IR16</translation> </message> <message> <location filename="../../CommandInsertRobot.cpp" line="95"/> <source>Insert a Kuka IR16 into the document.</source> <translation>Уметни Kuka IR16 у документ.</translation> </message> </context> <context> <name>CmdRobotInsertKukaIR210</name> <message> <location filename="../../CommandInsertRobot.cpp" line="134"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandInsertRobot.cpp" line="135"/> <source>Kuka IR210</source> <translation>Kuka IR210</translation> </message> <message> <location filename="../../CommandInsertRobot.cpp" line="136"/> <source>Insert a Kuka IR210 into the document.</source> <translation>Уметни Kuka IR210 у документ.</translation> </message> </context> <context> <name>CmdRobotInsertKukaIR500</name> <message> <location filename="../../CommandInsertRobot.cpp" line="51"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandInsertRobot.cpp" line="52"/> <source>Kuka IR500</source> <translation>Kuka IR500</translation> </message> <message> <location filename="../../CommandInsertRobot.cpp" line="53"/> <source>Insert a Kuka IR500 into the document.</source> <translation>Уметни Kuka IR500 у документ.</translation> </message> </context> <context> <name>CmdRobotInsertWaypoint</name> <message> <location filename="../../CommandTrajectory.cpp" line="95"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="96"/> <source>Insert in trajectory</source> <translation>Уметни путању</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="97"/> <source>Insert robot Tool location into trajectory</source> <translation>Уметни локацију Алата робота у путању</translation> </message> </context> <context> <name>CmdRobotInsertWaypointPreselect</name> <message> <location filename="../../CommandTrajectory.cpp" line="152"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="153"/> <source>Insert in trajectory</source> <translation>Уметни путању</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="154"/> <source>Insert preselection position into trajectory (W)</source> <translation>Уметни претходно изабрану позицију у путању (W)</translation> </message> </context> <context> <name>CmdRobotRestoreHomePos</name> <message> <location filename="../../Command.cpp" line="104"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../Command.cpp" line="105"/> <location filename="../../Command.cpp" line="106"/> <source>Move to home</source> <translation>Помери на почетну позицију</translation> </message> </context> <context> <name>CmdRobotSetDefaultOrientation</name> <message> <location filename="../../CommandTrajectory.cpp" line="216"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="217"/> <source>Set default orientation</source> <translation>Подеcи подразумевану оријентацију</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="218"/> <source>Set the default orientation for subsequent commands for waypoint creation</source> <translation>Постави подразумевану оријентацију за пратеће команде стварања тачака путање</translation> </message> </context> <context> <name>CmdRobotSetDefaultValues</name> <message> <location filename="../../CommandTrajectory.cpp" line="254"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="255"/> <source>Set default values</source> <translation>Постави подразумеване вредности</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="256"/> <source>Set the default values for speed, acceleration and continuity for subsequent commands of waypoint creation</source> <translation>Подеcи подразумеване вредноcти за брзину, убрзање и континуитет за пратеће команде стварања тачака путање</translation> </message> </context> <context> <name>CmdRobotSetHomePos</name> <message> <location filename="../../Command.cpp" line="55"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../Command.cpp" line="56"/> <location filename="../../Command.cpp" line="57"/> <source>Set the home position</source> <translation>Постави почетну позицију</translation> </message> </context> <context> <name>CmdRobotSimulate</name> <message> <location filename="../../Command.cpp" line="199"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../Command.cpp" line="200"/> <source>Simulate a trajectory</source> <translation>Cимулирај путању</translation> </message> <message> <location filename="../../Command.cpp" line="201"/> <source>Run a simulation on a trajectory</source> <translation>Покрени cимулацију на путањи</translation> </message> </context> <context> <name>CmdRobotTrajectoryCompound</name> <message> <location filename="../../CommandTrajectory.cpp" line="431"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="432"/> <source>Trajectory compound...</source> <translation>Cпој путање...</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="433"/> <source>Group and connect some trajectories to one</source> <translation>Групиши и cпоји неке путање у једну</translation> </message> </context> <context> <name>CmdRobotTrajectoryDressUp</name> <message> <location filename="../../CommandTrajectory.cpp" line="384"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="385"/> <source>Dress-up trajectory...</source> <translation>Опреми путању...</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="386"/> <source>Create a dress-up object which overrides some aspects of a trajectory</source> <translation>Направи опремљен објекат који ће надглаcати неке аcпекте путање</translation> </message> </context> <context> <name>Gui::TaskView::TaskWatcherCommands</name> <message> <location filename="../../Workbench.cpp" line="53"/> <source>Trajectory tools</source> <translation>Алати путање</translation> </message> <message> <location filename="../../Workbench.cpp" line="54"/> <source>Robot tools</source> <translation>Алати робота</translation> </message> <message> <location filename="../../Workbench.cpp" line="55"/> <source>Insert Robot</source> <translation>Уметни Робота</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../../Command.cpp" line="75"/> <location filename="../../Command.cpp" line="124"/> <location filename="../../Command.cpp" line="224"/> <location filename="../../Command.cpp" line="253"/> <location filename="../../CommandExport.cpp" line="65"/> <location filename="../../CommandExport.cpp" line="127"/> <location filename="../../CommandInsertRobot.cpp" line="234"/> <location filename="../../CommandTrajectory.cpp" line="111"/> <location filename="../../CommandTrajectory.cpp" line="167"/> <location filename="../../CommandTrajectory.cpp" line="184"/> <location filename="../../CommandTrajectory.cpp" line="412"/> <source>Wrong selection</source> <translation>Погрешан избор</translation> </message> <message> <location filename="../../Command.cpp" line="76"/> <source>Select one Robot to set home position</source> <translation>Изабери једног Робота да поcтавиш почетну позицију</translation> </message> <message> <location filename="../../Command.cpp" line="125"/> <source>Select one Robot</source> <translation>Изабери једног Робота</translation> </message> <message> <location filename="../../Command.cpp" line="225"/> <location filename="../../Command.cpp" line="254"/> <location filename="../../CommandExport.cpp" line="66"/> <location filename="../../CommandExport.cpp" line="128"/> <location filename="../../CommandTrajectory.cpp" line="112"/> <source>Select one Robot and one Trajectory object.</source> <translation>Одабери једног Робота и један објекат Путање.</translation> </message> <message> <location filename="../../Command.cpp" line="230"/> <source>Trajectory not valid</source> <translation>Путања је неважећа</translation> </message> <message> <location filename="../../Command.cpp" line="231"/> <source>You need at least two waypoints in a trajectory to simulate.</source> <translation>Потребне cу бар две тачке путање за cимулацију.</translation> </message> <message> <location filename="../../CommandExport.cpp" line="88"/> <location filename="../../CommandExport.cpp" line="150"/> <source>KRL file</source> <translation>KRL датотека</translation> </message> <message> <location filename="../../CommandExport.cpp" line="89"/> <location filename="../../CommandExport.cpp" line="151"/> <source>All Files</source> <translation>Све датотеке</translation> </message> <message> <location filename="../../CommandExport.cpp" line="90"/> <location filename="../../CommandExport.cpp" line="152"/> <source>Export program</source> <translation>Извези програм</translation> </message> <message> <location filename="../../CommandInsertRobot.cpp" line="235"/> <source>Select one robot and one shape or VRML object.</source> <translation>Изабери једног робота и један облик, или VRML објекат.</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="168"/> <location filename="../../CommandTrajectory.cpp" line="185"/> <source>Select one Trajectory object.</source> <translation>Одабери један објекат Путање.</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="191"/> <source>No preselection</source> <translation>Нема предизбора</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="192"/> <source>You have to hover above a geometry (Preselection) with the mouse to use this command. See documentation for details.</source> <translation>Морате прелазити преко геометрије (предизбора) cа мишем,да би кориcтили ову команду.Погледајте документацију за детаље.</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="268"/> <source>Set default speed</source> <translation>Подеси подразумевану брзину</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="269"/> <source>speed: (e.g. 1 m/s or 3 cm/s)</source> <translation>брзина: (e.g. 1 m/s or 3 cm/s)</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="278"/> <source>Set default continuity</source> <translation>Подеси подразумевани континуитет</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="279"/> <source>continuous ?</source> <translation>непрекидно ?</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="285"/> <source>Set default acceleration</source> <translation>Подеcи подразумевано убрзање</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="286"/> <source>acceleration: (e.g. 1 m/s^2 or 3 cm/s^2)</source> <translation>убрзање: (e.g. 1 m/s^2 or 3 cm/s^2)</translation> </message> <message> <location filename="../../CommandTrajectory.cpp" line="413"/> <source>Select the Trajectory which you want to dress up.</source> <translation>Одабери Путању коју желиш да опремиш.</translation> </message> <message> <location filename="../../ViewProviderTrajectory.cpp" line="164"/> <source>Modify</source> <translation>Измени</translation> </message> <message> <location filename="../../Workbench.cpp" line="81"/> <source>No robot files installed</source> <translation>Нема инсталираних робот датотека</translation> </message> <message> <location filename="../../Workbench.cpp" line="82"/> <source>Please visit %1 and copy the files to %2</source> <translation>Молимо, посетите %1 и копирајте датотеке у %2</translation> </message> </context> <context> <name>RobotGui::DlgTrajectorySimulate</name> <message> <location filename="../../TrajectorySimulate.ui" line="20"/> <source>Simulation</source> <translation>Симулација</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="58"/> <source>|&lt;</source> <translation>|&lt;</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="89"/> <source>&lt;</source> <translation>&lt;</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="120"/> <source>||</source> <translation>||</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="151"/> <source>|&gt;</source> <translation>|&gt;</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="182"/> <source>&gt;</source> <translation>&gt;</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="213"/> <source>&gt;|</source> <translation>&gt;|</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="237"/> <source>%</source> <translation>%</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="272"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="277"/> <source>Name</source> <translation>Име</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="282"/> <source>C</source> <translation>C</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="287"/> <source>V</source> <translation>V</translation> </message> <message> <location filename="../../TrajectorySimulate.ui" line="292"/> <source>A</source> <translation>A</translation> </message> </context> <context> <name>RobotGui::TaskEdge2TracParameter</name> <message> <location filename="../../TaskEdge2TracParameter.cpp" line="47"/> <source>TaskEdge2TracParameter</source> <translation type="unfinished">TaskEdge2TracParameter</translation> </message> </context> <context> <name>RobotGui::TaskRobot6Axis</name> <message> <location filename="../../TaskRobot6Axis.ui" line="14"/> <source>Form</source> <translation>Образац</translation> </message> <message> <location filename="../../TaskRobot6Axis.ui" line="22"/> <source>A1</source> <translation>A1</translation> </message> <message> <location filename="../../TaskRobot6Axis.ui" line="69"/> <source>A2</source> <translation>A2</translation> </message> <message> <location filename="../../TaskRobot6Axis.ui" line="116"/> <source>A3</source> <translation>A3</translation> </message> <message> <location filename="../../TaskRobot6Axis.ui" line="163"/> <source>A4</source> <translation>A4</translation> </message> <message> <location filename="../../TaskRobot6Axis.ui" line="210"/> <source>A5</source> <translation>A5</translation> </message> <message> <location filename="../../TaskRobot6Axis.ui" line="257"/> <source>A6</source> <translation>A6</translation> </message> <message> <location filename="../../TaskRobot6Axis.ui" line="313"/> <source>TCP: (200.23,300.23,400.23,234,343,343)</source> <translation>TCP: (200.23,300.23,400.23,234,343,343)</translation> </message> <message> <location filename="../../TaskRobot6Axis.ui" line="329"/> <source>Tool: (0,0,400,0,0,0)</source> <translation>Алатка: (0,0,400,0,0,0)</translation> </message> <message> <location filename="../../TaskRobot6Axis.ui" line="345"/> <source>...</source> <translation>...</translation> </message> <message> <location filename="../../TaskRobot6Axis.cpp" line="52"/> <source>TaskRobot6Axis</source> <translation type="unfinished">TaskRobot6Axis</translation> </message> </context> <context> <name>RobotGui::TaskRobotControl</name> <message> <location filename="../../TaskRobotControl.cpp" line="46"/> <source>TaskRobotControl</source> <translation type="unfinished">TaskRobotControl</translation> </message> </context> <context> <name>RobotGui::TaskRobotMessages</name> <message> <location filename="../../TaskRobotMessages.cpp" line="46"/> <source>TaskRobotMessages</source> <translation type="unfinished">TaskRobotMessages</translation> </message> </context> <context> <name>RobotGui::TaskTrajectory</name> <message> <location filename="../../TaskTrajectory.ui" line="20"/> <source>Form</source> <translation>Образац</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="58"/> <source>|&lt;</source> <translation>|&lt;</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="89"/> <source>&lt;</source> <translation>&lt;</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="120"/> <source>||</source> <translation>||</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="151"/> <source>|&gt;</source> <translation>|&gt;</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="182"/> <source>&gt;</source> <translation>&gt;</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="213"/> <source>&gt;|</source> <translation>&gt;|</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="237"/> <source>%</source> <translation>%</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="254"/> <source>10 ms</source> <translation>10 мс</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="259"/> <source>50 ms</source> <translation>50 мс</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="264"/> <source>100 ms</source> <translation>100 мс</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="269"/> <source>500 ms</source> <translation>500 мс</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="274"/> <source>1 s</source> <translation>1 с</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="291"/> <source>Pos: (200.23, 300.23, 400.23, 234, 343 ,343)</source> <translation>Поз: (200.23, 300.23, 400.23, 234, 343 ,343)</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="317"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="322"/> <source>Name</source> <translation>Име</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="327"/> <source>C</source> <translation>C</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="332"/> <source>V</source> <translation>V</translation> </message> <message> <location filename="../../TaskTrajectory.ui" line="337"/> <source>A</source> <translation>A</translation> </message> <message> <location filename="../../TaskTrajectory.cpp" line="44"/> <source>Trajectory</source> <translation type="unfinished">Trajectory</translation> </message> </context> <context> <name>RobotGui::TaskTrajectoryDressUpParameter</name> <message> <location filename="../../TaskTrajectoryDressUpParameter.cpp" line="48"/> <source>Dress Up Parameter</source> <translation type="unfinished">Dress Up Parameter</translation> </message> </context> <context> <name>TaskEdge2TracParameter</name> <message> <location filename="../../TaskEdge2TracParameter.ui" line="14"/> <source>Form</source> <translation>Образац</translation> </message> <message> <location filename="../../TaskEdge2TracParameter.ui" line="29"/> <source>Hide / Show</source> <translation>Сакриј / Прикажи</translation> </message> <message> <location filename="../../TaskEdge2TracParameter.ui" line="47"/> <source>Edges: 0</source> <translation>Ивице: 0</translation> </message> <message> <location filename="../../TaskEdge2TracParameter.ui" line="61"/> <source>Cluster: 0</source> <translation>Јато: 0</translation> </message> <message> <location filename="../../TaskEdge2TracParameter.ui" line="72"/> <source>Sizing Value:</source> <translation>Калибриcање Вредноcти:</translation> </message> <message> <location filename="../../TaskEdge2TracParameter.ui" line="103"/> <source>Use orientation of edge</source> <translation>Користи оријентацију ивице</translation> </message> </context> <context> <name>TaskRobotControl</name> <message> <location filename="../../TaskRobotControl.ui" line="14"/> <source>Form</source> <translation>Образац</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="37"/> <source>X+</source> <translation>X+</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="56"/> <source>Y+</source> <translation>Y+</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="75"/> <source>Z+</source> <translation>Z+</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="94"/> <source>A+</source> <translation>A+</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="113"/> <source>B+</source> <translation>B+</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="132"/> <source>C+</source> <translation>C+</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="151"/> <source>X-</source> <translation>X-</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="170"/> <source>Y-</source> <translation>Y-</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="189"/> <source>Z-</source> <translation>Z-</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="208"/> <source>A-</source> <translation>A-</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="227"/> <source>B-</source> <translation>B-</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="246"/> <source>C-</source> <translation>C-</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="258"/> <source>Tool 0</source> <translation>Алатка 0</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="263"/> <source>Tool</source> <translation>Алатка</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="268"/> <source>Base 0</source> <translation>База 0</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="273"/> <source>Base</source> <translation>База</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="278"/> <source>World</source> <translation>Свет</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="287"/> <source>50mm / 5°</source> <translation>50мм / 5°</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="292"/> <source>20mm / 2°</source> <translation>20мм / 2°</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="297"/> <source>10mm / 1°</source> <translation>10мм / 1°</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="302"/> <source>5mm / 0.5°</source> <translation>5mm / 0.5°</translation> </message> <message> <location filename="../../TaskRobotControl.ui" line="307"/> <source>1mm / 0.1°</source> <translation>1mm / 0.1°</translation> </message> </context> <context> <name>TaskRobotMessages</name> <message> <location filename="../../TaskRobotMessages.ui" line="14"/> <source>Form</source> <translation>Образац</translation> </message> <message> <location filename="../../TaskRobotMessages.ui" line="20"/> <source>clear</source> <translation>очиcти</translation> </message> </context> <context> <name>TaskTrajectoryDressUpParameter</name> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="14"/> <source>Form</source> <translation>Образац</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="20"/> <source>Speed &amp; Acceleration:</source> <translation>Брзина &amp; Убрзање:</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="29"/> <source>Speed:</source> <translation>Брзина:</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="55"/> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="92"/> <source>Use</source> <translation>Користи</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="66"/> <source>Accel:</source> <translation>Убрз:</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="102"/> <source>Don't change Cont</source> <translation>Не мењај Наставак</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="107"/> <source>Continues</source> <translation>Непрекидно</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="112"/> <source>Discontinues</source> <translation>Испрекидано</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="127"/> <source>Position and Orientation:</source> <translation>Позиција и Оријентација:</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="136"/> <source>(0,0,0),(0,0,0)</source> <translation>(0,0,0),(0,0,0)</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="149"/> <source>...</source> <translation>...</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="159"/> <source>Don't change Position &amp; Orientation</source> <translation>Не мењај Позицију &amp; Оријентацију</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="164"/> <source>Use Orientation</source> <translation>Користи Оријентацију</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="169"/> <source>Add Position</source> <translation>Додај Позицију</translation> </message> <message> <location filename="../../TaskTrajectoryDressUpParameter.ui" line="174"/> <source>Add Orientation</source> <translation>Додај Оријентацију</translation> </message> </context> <context> <name>Workbench</name> <message> <location filename="../../Workbench.cpp" line="49"/> <source>Robot</source> <translation>Робот</translation> </message> <message> <location filename="../../Workbench.cpp" line="50"/> <source>Insert Robots</source> <translation>Уметни Робота</translation> </message> <message> <location filename="../../Workbench.cpp" line="51"/> <source>&amp;Robot</source> <translation>&amp;Робот</translation> </message> <message> <location filename="../../Workbench.cpp" line="52"/> <source>Export trajectory</source> <translation>Извези путању</translation> </message> </context> </TS>
Fat-Zer/FreeCAD_sf_master
src/Mod/Robot/Gui/Resources/translations/Robot_sr.ts
TypeScript
lgpl-2.1
38,531
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * import shutil class Libiconv(AutotoolsPackage): """GNU libiconv provides an implementation of the iconv() function and the iconv program for character set conversion.""" homepage = "https://www.gnu.org/software/libiconv/" url = "http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.15.tar.gz" version('1.15', 'ace8b5f2db42f7b3b3057585e80d9808') version('1.14', 'e34509b1623cec449dfeb73d7ce9c6c6') # We cannot set up a warning for gets(), since gets() is not part # of C11 any more and thus might not exist. patch('gets.patch', when='@1.14') conflicts('@1.14', when='%gcc@5:') def configure_args(self): args = ['--enable-extra-encodings'] # A hack to patch config.guess in the libcharset sub directory shutil.copyfile('./build-aux/config.guess', 'libcharset/build-aux/config.guess') return args
EmreAtes/spack
var/spack/repos/builtin/packages/libiconv/package.py
Python
lgpl-2.1
2,156
/* RMNLIB - Library of useful routines for C and FORTRAN programming * Copyright (C) 1975-2001 Division de Recherche en Prevision Numerique * Environnement Canada * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include <stdio.h> #include <stdlib.h> #include <rmnlib.h> #include <rpnmacros.h> #define elementCount 2000 #define elementCount_4 8000 #define maxBit 64 ftnfloat f77name(second)(); static double powerOf2s[maxBit]; void f77name(mainrle)() { word bits[maxBit]; word i, k, j; int arrayOfInt1[elementCount_4], arrayOfInt2[elementCount_4]; int arrayOfInt3[elementCount_4], arrayOfInt4[elementCount_4]; int numOfBitPerToken; int tempInteger; int packedElementCount; int isError; ftnfloat startTime, switchTime, endTime; int repeatTestTimes = 100; int stride; int maxStride = 4; int minTokenBit = 3, maxTokenBit = 31; int maxInteger=1, minInteger=1; /****************************************** * * * generate number pool * * * *****************************************/ k = 1; bits[0] = k; for( i = 1; i < maxBit; i++) { k += k; bits[i] = k; }; /****************************************** * * * generate 2's power * * * *****************************************/ powerOf2s[0] = 1.0; for ( i = 1; i < maxBit; i++) { powerOf2s[i] = 2.0 *powerOf2s[i-1]; }; /******************************************* * * * body of test * * * ******************************************/ for (stride = 1; stride <= maxStride; stride++) { printf("\n\n ============== \n\n"); printf(" stride is : %d ", stride ); printf("\n\n ============== \n\n"); for ( numOfBitPerToken = minTokenBit; numOfBitPerToken <= maxTokenBit; numOfBitPerToken++) { for ( i = 0; i < elementCount*stride ; i++) { arrayOfInt1[i] = -1; arrayOfInt2[i] = -1; arrayOfInt3[i] = -1; arrayOfInt4[i] = -1; };/* for */ /********************************* * * * initialize integer arrays * * * ********************************/ i = 0; j = 0; while ( i < elementCount*stride ) { arrayOfInt1[i] = bits[j%(numOfBitPerToken-1)]; if ( ( arrayOfInt1[i] <= 32 ) && ( arrayOfInt1[i]*stride+i < elementCount*stride ) ) { for ( k= i; k <= i+arrayOfInt1[i]*stride; k+=stride) { arrayOfInt1[k] = arrayOfInt1[i]; }; i+=arrayOfInt1[i]*stride; };/* if */ i+=stride; j++; };/* while */ arrayOfInt1[5*stride] = 0; arrayOfInt1[6*stride] = powerOf2s[numOfBitPerToken] - 1 - 3; minInteger = 0; maxInteger = powerOf2s[numOfBitPerToken] - 1 - 3; for ( i = 0; i < elementCount*stride ; i+=stride) { arrayOfInt3[i] = arrayOfInt1[i]; };/* for */ /************************************* * * * pack and unpack * * * ************************************/ startTime = f77name(second)(); for ( i = 1; i <= repeatTestTimes; i++) { packedElementCount = compact_rle( arrayOfInt1, arrayOfInt2, arrayOfInt2, maxInteger, minInteger, elementCount, numOfBitPerToken, 128, stride, 1); }; switchTime = f77name(second)(); for ( i = 1; i <= repeatTestTimes; i++) { unpackWrapper(arrayOfInt4, arrayOfInt2, arrayOfInt2, stride, &stride ); /* packedElementCount = compact_rle( arrayOfInt4, arrayOfInt2, arrayOfInt2, maxInteger, minInteger, elementCount, numOfBitPerToken, 128, stride, 2); */ }; endTime = f77name(second)(); /***************************************** * * * check for error and report result * * * ****************************************/ isError = 0; for ( i = 0; i < elementCount*stride; i+=stride) { if (arrayOfInt1[i] != arrayOfInt4[i] ) { isError = 1; }; }; if ( isError ) { printf("\n NBITS: %d \t RLE_PACK : %f \t\t RLE_UNPACK : %f \t\t ERROR", numOfBitPerToken, (switchTime-startTime)/repeatTestTimes, (endTime-switchTime)/repeatTestTimes); } else { printf("\n NBITS: %d \t RLE_PACK : %6e \t\t RLE_UNPACK : %6e ", numOfBitPerToken, (switchTime-startTime)/repeatTestTimes, (endTime-switchTime)/repeatTestTimes); }; };/* for, numOfBitPerToken */ };/*for, stride*/ printf("\n"); }
mfvalin/rmnlib
packers/cmainRLE.c
C
lgpl-2.1
6,335
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** Author: Milian Wolff, KDAB (milian.wolff@kdab.com) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #ifndef ANALYZER_INTERNAL_ANALYZERRUNCONFIGWIDGET_H #define ANALYZER_INTERNAL_ANALYZERRUNCONFIGWIDGET_H #include "analyzersettings.h" #include <utils/detailswidget.h> QT_BEGIN_NAMESPACE class QComboBox; class QPushButton; QT_END_NAMESPACE namespace Utils { class DetailsWidget; } namespace Analyzer { class AnalyzerSettings; class AbstractAnalyzerSubConfig; namespace Internal { class AnalyzerToolDetailWidget : public Utils::DetailsWidget { Q_OBJECT public: explicit AnalyzerToolDetailWidget(AbstractAnalyzerSubConfig *config, QWidget *parent=0); }; class AnalyzerRunConfigWidget : public ProjectExplorer::RunConfigWidget { Q_OBJECT public: AnalyzerRunConfigWidget(); virtual QString displayName() const; void setRunConfigurationAspect(AnalyzerRunConfigurationAspect *aspect); private: void setDetailEnabled(bool value); private slots: void chooseSettings(int setting); void restoreGlobal(); private: QWidget *m_subConfigWidget; AnalyzerRunConfigurationAspect *m_aspect; QComboBox *m_settingsCombo; QPushButton *m_restoreButton; }; } // namespace Internal } // namespace Analyzer #endif // ANALYZER_INTERNAL_ANALYZERRUNCONFIGWIDGET_H
duythanhphan/qt-creator
src/plugins/analyzerbase/analyzerrunconfigwidget.h
C
lgpl-2.1
2,713
/* * libjingle * Copyright 2010, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TALK_SESSION_PHONE_FAKEWEBRTCVOICEENGINE_H_ #define TALK_SESSION_PHONE_FAKEWEBRTCVOICEENGINE_H_ #include <list> #include <map> #include <vector> #include "talk/base/basictypes.h" #include "talk/base/stringutils.h" #include "talk/session/phone/codec.h" #include "talk/session/phone/fakewebrtccommon.h" #include "talk/session/phone/voiceprocessor.h" #include "talk/session/phone/webrtcvoe.h" namespace cricket { static const char kFakeDefaultDeviceName[] = "Fake Default"; static const int kFakeDefaultDeviceId = -1; static const char kFakeDeviceName[] = "Fake Device"; #ifdef WIN32 static const int kFakeDeviceId = 0; #else static const int kFakeDeviceId = 1; #endif class FakeWebRtcVoiceEngine : public webrtc::VoEAudioProcessing, public webrtc::VoEBase, public webrtc::VoECodec, public webrtc::VoEDtmf, public webrtc::VoEFile, public webrtc::VoEHardware, public webrtc::VoEExternalMedia, public webrtc::VoENetEqStats, public webrtc::VoENetwork, public webrtc::VoERTP_RTCP, public webrtc::VoEVideoSync, public webrtc::VoEVolumeControl { public: struct Channel { Channel() : external_transport(false), send(false), playout(false), file(false), vad(false), fec(false), media_processor_registered(false), cn8_type(13), cn16_type(105), dtmf_type(106), fec_type(117), send_ssrc(0), level_header_ext_(-1) { memset(&send_codec, 0, sizeof(send_codec)); } bool external_transport; bool send; bool playout; bool file; bool vad; bool fec; bool media_processor_registered; int cn8_type; int cn16_type; int dtmf_type; int fec_type; uint32 send_ssrc; int level_header_ext_; std::vector<webrtc::CodecInst> recv_codecs; webrtc::CodecInst send_codec; std::list<std::string> packets; }; FakeWebRtcVoiceEngine(const cricket::AudioCodec* const* codecs, int num_codecs) : inited_(false), last_channel_(-1), fail_create_channel_(false), codecs_(codecs), num_codecs_(num_codecs), ec_enabled_(false), ns_enabled_(false), ec_mode_(webrtc::kEcDefault), ns_mode_(webrtc::kNsDefault), observer_(NULL), playout_fail_channel_(-1), send_fail_channel_(-1), fail_start_recording_microphone_(false), recording_microphone_(false), media_processor_(NULL) { memset(&agc_config_, 0, sizeof(agc_config_)); } ~FakeWebRtcVoiceEngine() { // Ought to have all been deleted by the WebRtcVoiceMediaChannel // destructors, but just in case ... for (std::map<int, Channel*>::const_iterator i = channels_.begin(); i != channels_.end(); ++i) { delete i->second; } } bool IsExternalMediaProcessorRegistered() const { return media_processor_ != NULL; } bool IsInited() const { return inited_; } int GetLastChannel() const { return last_channel_; } int GetNumChannels() const { return channels_.size(); } bool GetPlayout(int channel) { return channels_[channel]->playout; } bool GetSend(int channel) { return channels_[channel]->send; } bool GetRecordingMicrophone() { return recording_microphone_; } bool GetVAD(int channel) { return channels_[channel]->vad; } bool GetFEC(int channel) { return channels_[channel]->fec; } int GetSendCNPayloadType(int channel, bool wideband) { return (wideband) ? channels_[channel]->cn16_type : channels_[channel]->cn8_type; } int GetSendTelephoneEventPayloadType(int channel) { return channels_[channel]->dtmf_type; } int GetSendFECPayloadType(int channel) { return channels_[channel]->fec_type; } bool CheckPacket(int channel, const void* data, size_t len) { bool result = !CheckNoPacket(channel); if (result) { std::string packet = channels_[channel]->packets.front(); result = (packet == std::string(static_cast<const char*>(data), len)); channels_[channel]->packets.pop_front(); } return result; } bool CheckNoPacket(int channel) { return channels_[channel]->packets.empty(); } void TriggerCallbackOnError(int channel_num, int err_code) { ASSERT(observer_ != NULL); observer_->CallbackOnError(channel_num, err_code); } void set_playout_fail_channel(int channel) { playout_fail_channel_ = channel; } void set_send_fail_channel(int channel) { send_fail_channel_ = channel; } void set_fail_start_recording_microphone( bool fail_start_recording_microphone) { fail_start_recording_microphone_ = fail_start_recording_microphone; } void set_fail_create_channel(bool fail_create_channel) { fail_create_channel_ = fail_create_channel; } void TriggerProcessPacket(MediaProcessorDirection direction) { webrtc::ProcessingTypes pt = (direction == cricket::MPD_TX) ? webrtc::kRecordingPerChannel : webrtc::kPlaybackPerChannel; if (media_processor_ != NULL) { media_processor_->Process(0, pt, NULL, 0, 0, true); } } WEBRTC_STUB(Release, ()); // webrtc::VoEBase WEBRTC_FUNC(RegisterVoiceEngineObserver, ( webrtc::VoiceEngineObserver& observer)) { observer_ = &observer; return 0; } WEBRTC_STUB(DeRegisterVoiceEngineObserver, ()); WEBRTC_STUB(RegisterAudioDeviceModule, (webrtc::AudioDeviceModule& adm)); WEBRTC_STUB(DeRegisterAudioDeviceModule, ()); WEBRTC_FUNC(Init, (webrtc::AudioDeviceModule* adm)) { inited_ = true; return 0; } WEBRTC_FUNC(Terminate, ()) { inited_ = false; return 0; } WEBRTC_STUB(MaxNumOfChannels, ()); WEBRTC_FUNC(CreateChannel, ()) { if (fail_create_channel_) { return -1; } Channel* ch = new Channel(); for (int i = 0; i < NumOfCodecs(); ++i) { webrtc::CodecInst codec; GetCodec(i, codec); ch->recv_codecs.push_back(codec); } channels_[++last_channel_] = ch; return last_channel_; } WEBRTC_FUNC(DeleteChannel, (int channel)) { WEBRTC_CHECK_CHANNEL(channel); delete channels_[channel]; channels_.erase(channel); return 0; } WEBRTC_STUB(SetLocalReceiver, (int channel, int port, int RTCPport, const char ipaddr[64], const char multiCastAddr[64])); WEBRTC_STUB(GetLocalReceiver, (int channel, int& port, int& RTCPport, char ipaddr[64])); WEBRTC_STUB(SetSendDestination, (int channel, int port, const char ipaddr[64], int sourcePort, int RTCPport)); WEBRTC_STUB(GetSendDestination, (int channel, int& port, char ipaddr[64], int& sourcePort, int& RTCPport)); WEBRTC_STUB(StartReceive, (int channel)); WEBRTC_FUNC(StartPlayout, (int channel)) { if (playout_fail_channel_ != channel) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->playout = true; return 0; } else { // When playout_fail_channel_ == channel, fail the StartPlayout on this // channel. return -1; } } WEBRTC_FUNC(StartSend, (int channel)) { if (send_fail_channel_ != channel) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->send = true; return 0; } else { // When send_fail_channel_ == channel, fail the StartSend on this // channel. return -1; } } WEBRTC_STUB(StopReceive, (int channel)); WEBRTC_FUNC(StopPlayout, (int channel)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->playout = false; return 0; } WEBRTC_FUNC(StopSend, (int channel)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->send = false; return 0; } WEBRTC_STUB(GetVersion, (char version[1024])); WEBRTC_STUB(LastError, ()); WEBRTC_STUB(SetOnHoldStatus, (int, bool, webrtc::OnHoldModes)); WEBRTC_STUB(GetOnHoldStatus, (int, bool&, webrtc::OnHoldModes&)); WEBRTC_STUB(SetNetEQPlayoutMode, (int, webrtc::NetEqModes)); WEBRTC_STUB(GetNetEQPlayoutMode, (int, webrtc::NetEqModes&)); WEBRTC_STUB(SetNetEQBGNMode, (int, webrtc::NetEqBgnModes)); WEBRTC_STUB(GetNetEQBGNMode, (int, webrtc::NetEqBgnModes&)); // webrtc::VoECodec WEBRTC_FUNC(NumOfCodecs, ()) { return num_codecs_; } WEBRTC_FUNC(GetCodec, (int index, webrtc::CodecInst& codec)) { if (index < 0 || index >= NumOfCodecs()) { return -1; } const cricket::AudioCodec& c(*codecs_[index]); codec.pltype = c.id; talk_base::strcpyn(codec.plname, sizeof(codec.plname), c.name.c_str()); codec.plfreq = c.clockrate; codec.pacsize = 0; codec.channels = c.channels; codec.rate = c.bitrate; return 0; } WEBRTC_FUNC(SetSendCodec, (int channel, const webrtc::CodecInst& codec)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->send_codec = codec; return 0; } WEBRTC_FUNC(GetSendCodec, (int channel, webrtc::CodecInst& codec)) { WEBRTC_CHECK_CHANNEL(channel); codec = channels_[channel]->send_codec; return 0; } WEBRTC_STUB(GetRecCodec, (int channel, webrtc::CodecInst& codec)); WEBRTC_STUB(SetAMREncFormat, (int channel, webrtc::AmrMode mode)); WEBRTC_STUB(SetAMRDecFormat, (int channel, webrtc::AmrMode mode)); WEBRTC_STUB(SetAMRWbEncFormat, (int channel, webrtc::AmrMode mode)); WEBRTC_STUB(SetAMRWbDecFormat, (int channel, webrtc::AmrMode mode)); WEBRTC_STUB(SetISACInitTargetRate, (int channel, int rateBps, bool useFixedFrameSize)); WEBRTC_STUB(SetISACMaxRate, (int channel, int rateBps)); WEBRTC_STUB(SetISACMaxPayloadSize, (int channel, int sizeBytes)); WEBRTC_FUNC(SetRecPayloadType, (int channel, const webrtc::CodecInst& codec)) { WEBRTC_CHECK_CHANNEL(channel); Channel* ch = channels_[channel]; // Check if something else already has this slot. if (codec.pltype != -1) { for (std::vector<webrtc::CodecInst>::iterator it = ch->recv_codecs.begin(); it != ch->recv_codecs.end(); ++it) { if (it->pltype == codec.pltype) { return -1; } } } // Otherwise try to find this codec and update its payload type. for (std::vector<webrtc::CodecInst>::iterator it = ch->recv_codecs.begin(); it != ch->recv_codecs.end(); ++it) { if (strcmp(it->plname, codec.plname) == 0 && it->plfreq == codec.plfreq) { it->pltype = codec.pltype; return 0; } } return -1; // not found } WEBRTC_FUNC(SetSendCNPayloadType, (int channel, int type, webrtc::PayloadFrequencies frequency)) { WEBRTC_CHECK_CHANNEL(channel); if (frequency == webrtc::kFreq8000Hz) { channels_[channel]->cn8_type = type; } else if (frequency == webrtc::kFreq16000Hz) { channels_[channel]->cn16_type = type; } return 0; } WEBRTC_FUNC(GetRecPayloadType, (int channel, webrtc::CodecInst& codec)) { WEBRTC_CHECK_CHANNEL(channel); Channel* ch = channels_[channel]; for (std::vector<webrtc::CodecInst>::iterator it = ch->recv_codecs.begin(); it != ch->recv_codecs.end(); ++it) { if (strcmp(it->plname, codec.plname) == 0 && it->plfreq == codec.plfreq && it->pltype != -1) { codec.pltype = it->pltype; return 0; } } return -1; // not found } WEBRTC_FUNC(SetVADStatus, (int channel, bool enable, webrtc::VadModes mode, bool disableDTX)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->vad = enable; return 0; } WEBRTC_STUB(GetVADStatus, (int channel, bool& enabled, webrtc::VadModes& mode, bool& disabledDTX)); // webrtc::VoEDtmf WEBRTC_STUB(SendTelephoneEvent, (int channel, int eventCode, bool outOfBand = true, int lengthMs = 160, int attenuationDb = 10)); WEBRTC_FUNC(SetSendTelephoneEventPayloadType, (int channel, unsigned char type)) { channels_[channel]->dtmf_type = type; return 0; }; WEBRTC_STUB(GetSendTelephoneEventPayloadType, (int channel, unsigned char& type)); WEBRTC_STUB(SetDtmfFeedbackStatus, (bool enable, bool directFeedback)); WEBRTC_STUB(GetDtmfFeedbackStatus, (bool& enabled, bool& directFeedback)); WEBRTC_STUB(RegisterTelephoneEventDetection, (int channel, webrtc::TelephoneEventDetectionMethods detectionMethod, webrtc::VoETelephoneEventObserver& observer)); WEBRTC_STUB(DeRegisterTelephoneEventDetection, (int channel)); WEBRTC_STUB(SetDtmfPlayoutStatus, (int channel, bool enable)); WEBRTC_STUB(GetDtmfPlayoutStatus, (int channel, bool& enabled)); WEBRTC_STUB(PlayDtmfTone, (int eventCode, int lengthMs = 200, int attenuationDb = 10)); WEBRTC_STUB(StartPlayingDtmfTone, (int eventCode, int attenuationDb = 10)); WEBRTC_STUB(StopPlayingDtmfTone, ()); WEBRTC_STUB(GetTelephoneEventDetectionStatus, (int channel, bool& enabled, webrtc::TelephoneEventDetectionMethods& detectionMethod)); // webrtc::VoEFile WEBRTC_FUNC(StartPlayingFileLocally, (int channel, const char* fileNameUTF8, bool loop, webrtc::FileFormats format, float volumeScaling, int startPointMs, int stopPointMs)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->file = true; return 0; } WEBRTC_FUNC(StartPlayingFileLocally, (int channel, webrtc::InStream* stream, webrtc::FileFormats format, float volumeScaling, int startPointMs, int stopPointMs)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->file = true; return 0; } WEBRTC_FUNC(StopPlayingFileLocally, (int channel)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->file = false; return 0; } WEBRTC_FUNC(IsPlayingFileLocally, (int channel)) { WEBRTC_CHECK_CHANNEL(channel); return (channels_[channel]->file) ? 1 : 0; } WEBRTC_STUB(ScaleLocalFilePlayout, (int channel, float scale)); WEBRTC_STUB(StartPlayingFileAsMicrophone, (int channel, const char* fileNameUTF8, bool loop, bool mixWithMicrophone, webrtc::FileFormats format, float volumeScaling)); WEBRTC_STUB(StartPlayingFileAsMicrophone, (int channel, webrtc::InStream* stream, bool mixWithMicrophone, webrtc::FileFormats format, float volumeScaling)); WEBRTC_STUB(StopPlayingFileAsMicrophone, (int channel)); WEBRTC_STUB(IsPlayingFileAsMicrophone, (int channel)); WEBRTC_STUB(ScaleFileAsMicrophonePlayout, (int channel, float scale)); WEBRTC_STUB(StartRecordingPlayout, (int channel, const char* fileNameUTF8, webrtc::CodecInst* compression, int maxSizeBytes)); WEBRTC_STUB(StartRecordingPlayout, (int channel, webrtc::OutStream* stream, webrtc::CodecInst* compression)); WEBRTC_STUB(StopRecordingPlayout, (int channel)); WEBRTC_FUNC(StartRecordingMicrophone, (const char* fileNameUTF8, webrtc::CodecInst* compression, int maxSizeBytes)) { if (fail_start_recording_microphone_) { return -1; } recording_microphone_ = true; return 0; } WEBRTC_FUNC(StartRecordingMicrophone, (webrtc::OutStream* stream, webrtc::CodecInst* compression)) { if (fail_start_recording_microphone_) { return -1; } recording_microphone_ = true; return 0; } WEBRTC_FUNC(StopRecordingMicrophone, ()) { if (!recording_microphone_) { return -1; } recording_microphone_ = false; return 0; } WEBRTC_STUB(ConvertPCMToWAV, (const char* fileNameInUTF8, const char* fileNameOutUTF8)); WEBRTC_STUB(ConvertPCMToWAV, (webrtc::InStream* streamIn, webrtc::OutStream* streamOut)); WEBRTC_STUB(ConvertWAVToPCM, (const char* fileNameInUTF8, const char* fileNameOutUTF8)); WEBRTC_STUB(ConvertWAVToPCM, (webrtc::InStream* streamIn, webrtc::OutStream* streamOut)); WEBRTC_STUB(ConvertPCMToCompressed, (const char* fileNameInUTF8, const char* fileNameOutUTF8, webrtc::CodecInst* compression)); WEBRTC_STUB(ConvertPCMToCompressed, (webrtc::InStream* streamIn, webrtc::OutStream* streamOut, webrtc::CodecInst* compression)); WEBRTC_STUB(ConvertCompressedToPCM, (const char* fileNameInUTF8, const char* fileNameOutUTF8)); WEBRTC_STUB(ConvertCompressedToPCM, (webrtc::InStream* streamIn, webrtc::OutStream* streamOut)); WEBRTC_STUB(GetFileDuration, (const char* fileNameUTF8, int& durationMs, webrtc::FileFormats format)); WEBRTC_STUB(GetPlaybackPosition, (int channel, int& positionMs)); // webrtc::VoEHardware WEBRTC_STUB(GetCPULoad, (int&)); WEBRTC_STUB(GetSystemCPULoad, (int&)); WEBRTC_FUNC(GetNumOfRecordingDevices, (int& num)) { return GetNumDevices(num); } WEBRTC_FUNC(GetNumOfPlayoutDevices, (int& num)) { return GetNumDevices(num); } WEBRTC_FUNC(GetRecordingDeviceName, (int i, char* name, char* guid)) { return GetDeviceName(i, name, guid); } WEBRTC_FUNC(GetPlayoutDeviceName, (int i, char* name, char* guid)) { return GetDeviceName(i, name, guid); } WEBRTC_STUB(SetRecordingDevice, (int, webrtc::StereoChannel)); WEBRTC_STUB(SetPlayoutDevice, (int)); WEBRTC_STUB(SetAudioDeviceLayer, (webrtc::AudioLayers)); WEBRTC_STUB(GetAudioDeviceLayer, (webrtc::AudioLayers&)); WEBRTC_STUB(GetPlayoutDeviceStatus, (bool&)); WEBRTC_STUB(GetRecordingDeviceStatus, (bool&)); WEBRTC_STUB(ResetAudioDevice, ()); WEBRTC_STUB(AudioDeviceControl, (unsigned int, unsigned int, unsigned int)); WEBRTC_STUB(NeedMorePlayData, (short int*, int, int, int, int&)); WEBRTC_STUB(RecordedDataIsAvailable, (short int*, int, int, int, int&)); WEBRTC_STUB(GetDevice, (char*, unsigned int)); WEBRTC_STUB(GetPlatform, (char*, unsigned int)); WEBRTC_STUB(GetOS, (char*, unsigned int)); WEBRTC_STUB(SetGrabPlayout, (bool)); WEBRTC_STUB(SetGrabRecording, (bool)); WEBRTC_STUB(SetLoudspeakerStatus, (bool enable)); WEBRTC_STUB(GetLoudspeakerStatus, (bool& enabled)); WEBRTC_STUB(EnableBuiltInAEC, (bool enable)); virtual bool BuiltInAECIsEnabled() const { return true; } WEBRTC_STUB(SetSamplingRate, (int)); WEBRTC_STUB(GetSamplingRate, (int&)); // webrtc::VoENetEqStats WEBRTC_STUB(GetNetworkStatistics, (int, webrtc::NetworkStatistics&)); WEBRTC_STUB(GetPreferredBufferSize, (int, short unsigned int&)); WEBRTC_STUB(ResetJitterStatistics, (int)); // webrtc::VoENetwork WEBRTC_FUNC(RegisterExternalTransport, (int channel, webrtc::Transport& transport)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->external_transport = true; return 0; } WEBRTC_FUNC(DeRegisterExternalTransport, (int channel)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->external_transport = false; return 0; } WEBRTC_FUNC(ReceivedRTPPacket, (int channel, const void* data, unsigned int length)) { WEBRTC_CHECK_CHANNEL(channel); if (!channels_[channel]->external_transport) return -1; channels_[channel]->packets.push_back( std::string(static_cast<const char*>(data), length)); return 0; } WEBRTC_STUB(ReceivedRTCPPacket, (int channel, const void* data, unsigned int length)); WEBRTC_STUB(GetSourceInfo, (int channel, int& rtpPort, int& rtcpPort, char ipaddr[64])); WEBRTC_STUB(GetLocalIP, (char ipaddr[64], bool ipv6)); WEBRTC_STUB(EnableIPv6, (int channel)); // Not using WEBRTC_STUB due to bool return value virtual bool IPv6IsEnabled(int channel) { return true; } WEBRTC_STUB(SetSourceFilter, (int channel, int rtpPort, int rtcpPort, const char ipaddr[64])); WEBRTC_STUB(GetSourceFilter, (int channel, int& rtpPort, int& rtcpPort, char ipaddr[64])); WEBRTC_STUB(SetSendTOS, (int channel, int priority, int DSCP, bool useSetSockopt)); WEBRTC_STUB(GetSendTOS, (int channel, int& priority, int& DSCP, bool& useSetSockopt)); WEBRTC_STUB(SetSendGQoS, (int channel, bool enable, int serviceType, int overrideDSCP)); WEBRTC_STUB(GetSendGQoS, (int channel, bool& enabled, int& serviceType, int& overrideDSCP)); WEBRTC_STUB(SetPacketTimeoutNotification, (int channel, bool enable, int timeoutSeconds)); WEBRTC_STUB(GetPacketTimeoutNotification, (int channel, bool& enable, int& timeoutSeconds)); WEBRTC_STUB(RegisterDeadOrAliveObserver, (int channel, webrtc::VoEConnectionObserver& observer)); WEBRTC_STUB(DeRegisterDeadOrAliveObserver, (int channel)); WEBRTC_STUB(GetPeriodicDeadOrAliveStatus, (int channel, bool& enabled, int& sampleTimeSeconds)); WEBRTC_STUB(SetPeriodicDeadOrAliveStatus, (int channel, bool enable, int sampleTimeSeconds)); WEBRTC_STUB(SendUDPPacket, (int channel, const void* data, unsigned int length, int& transmittedBytes, bool useRtcpSocket)); // webrtc::VoERTP_RTCP WEBRTC_STUB(RegisterRTPObserver, (int channel, webrtc::VoERTPObserver& observer)); WEBRTC_STUB(DeRegisterRTPObserver, (int channel)); WEBRTC_STUB(RegisterRTCPObserver, (int channel, webrtc::VoERTCPObserver& observer)); WEBRTC_STUB(DeRegisterRTCPObserver, (int channel)); WEBRTC_FUNC(SetLocalSSRC, (int channel, unsigned int ssrc)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->send_ssrc = ssrc; return 0; } WEBRTC_FUNC(GetLocalSSRC, (int channel, unsigned int& ssrc)) { WEBRTC_CHECK_CHANNEL(channel); ssrc = channels_[channel]->send_ssrc; return 0; } WEBRTC_STUB(GetRemoteSSRC, (int channel, unsigned int& ssrc)); WEBRTC_FUNC(SetRTPAudioLevelIndicationStatus, (int channel, bool enable, unsigned char ID)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->level_header_ext_ = (enable) ? ID : -1; return 0; } WEBRTC_FUNC(GetRTPAudioLevelIndicationStatus, (int channel, bool& enabled, unsigned char& ID)) { WEBRTC_CHECK_CHANNEL(channel); enabled = (channels_[channel]->level_header_ext_ != -1); ID = channels_[channel]->level_header_ext_; return 0; } WEBRTC_STUB(GetRemoteCSRCs, (int channel, unsigned int arrCSRC[15])); WEBRTC_STUB(GetRemoteEnergy, (int channel, unsigned char arrEnergy[15])); WEBRTC_STUB(SetRTCPStatus, (int channel, bool enable)); WEBRTC_STUB(GetRTCPStatus, (int channel, bool& enabled)); WEBRTC_STUB(SetRTCP_CNAME, (int channel, const char cname[256])); WEBRTC_STUB(GetRTCP_CNAME, (int channel, char cname[256])); WEBRTC_STUB(GetRemoteRTCP_CNAME, (int channel, char* cname)); WEBRTC_STUB(GetRemoteRTCPData, (int channel, unsigned int& NTPHigh, unsigned int& NTPLow, unsigned int& timestamp, unsigned int& playoutTimestamp, unsigned int* jitter, unsigned short* fractionLost)); WEBRTC_STUB(SendApplicationDefinedRTCPPacket, (int channel, const unsigned char subType, unsigned int name, const char* data, unsigned short dataLength)); WEBRTC_STUB(GetRTPStatistics, (int channel, unsigned int& averageJitterMs, unsigned int& maxJitterMs, unsigned int& discardedPackets)); WEBRTC_STUB(GetRTCPStatistics, (int channel, unsigned short& fractionLost, unsigned int& cumulativeLost, unsigned int& extendedMax, unsigned int& jitterSamples, int& rttMs)); WEBRTC_STUB(GetRTCPStatistics, (int channel, webrtc::CallStatistics& stats)); WEBRTC_FUNC(SetFECStatus, (int channel, bool enable, int redPayloadtype)) { WEBRTC_CHECK_CHANNEL(channel); channels_[channel]->fec = enable; channels_[channel]->fec_type = redPayloadtype; return 0; } WEBRTC_FUNC(GetFECStatus, (int channel, bool& enable, int& redPayloadtype)) { WEBRTC_CHECK_CHANNEL(channel); enable = channels_[channel]->fec; redPayloadtype = channels_[channel]->fec_type; return 0; } WEBRTC_STUB(SetRTPKeepaliveStatus, (int channel, bool enable, int unknownPayloadType, int deltaTransmitTimeSeconds)); WEBRTC_STUB(GetRTPKeepaliveStatus, (int channel, bool& enabled, int& unknownPayloadType, int& deltaTransmitTimeSeconds)); WEBRTC_STUB(StartRTPDump, (int channel, const char* fileNameUTF8, webrtc::RTPDirections direction)); WEBRTC_STUB(StopRTPDump, (int channel, webrtc::RTPDirections direction)); WEBRTC_STUB(RTPDumpIsActive, (int channel, webrtc::RTPDirections direction)); WEBRTC_STUB(InsertExtraRTPPacket, (int channel, unsigned char payloadType, bool markerBit, const char* payloadData, unsigned short payloadSize)); // webrtc::VoEVideoSync WEBRTC_STUB(GetPlayoutBufferSize, (int& bufferMs)); WEBRTC_STUB(GetPlayoutTimestamp, (int channel, unsigned int& timestamp)); WEBRTC_STUB(GetRtpRtcp, (int, webrtc::RtpRtcp*&)); WEBRTC_STUB(SetInitTimestamp, (int channel, unsigned int timestamp)); WEBRTC_STUB(SetInitSequenceNumber, (int channel, short sequenceNumber)); WEBRTC_STUB(SetMinimumPlayoutDelay, (int channel, int delayMs)); WEBRTC_STUB(GetDelayEstimate, (int channel, int& delayMs)); WEBRTC_STUB(GetSoundcardBufferSize, (int& bufferMs)); // webrtc::VoEVolumeControl WEBRTC_STUB(SetSpeakerVolume, (unsigned int)); WEBRTC_STUB(GetSpeakerVolume, (unsigned int&)); WEBRTC_STUB(SetSystemOutputMute, (bool)); WEBRTC_STUB(GetSystemOutputMute, (bool&)); WEBRTC_STUB(SetMicVolume, (unsigned int)); WEBRTC_STUB(GetMicVolume, (unsigned int&)); WEBRTC_STUB(SetInputMute, (int, bool)); WEBRTC_STUB(GetInputMute, (int, bool&)); WEBRTC_STUB(SetSystemInputMute, (bool)); WEBRTC_STUB(GetSystemInputMute, (bool&)); WEBRTC_STUB(GetSpeechInputLevel, (unsigned int&)); WEBRTC_STUB(GetSpeechOutputLevel, (int, unsigned int&)); WEBRTC_STUB(GetSpeechInputLevelFullRange, (unsigned int&)); WEBRTC_STUB(GetSpeechOutputLevelFullRange, (int, unsigned int&)); WEBRTC_STUB(SetChannelOutputVolumeScaling, (int, float)); WEBRTC_STUB(GetChannelOutputVolumeScaling, (int, float&)); WEBRTC_STUB(SetOutputVolumePan, (int, float, float)); WEBRTC_STUB(GetOutputVolumePan, (int, float&, float&)); // webrtc::VoEAudioProcessing WEBRTC_FUNC(SetNsStatus, (bool enable, webrtc::NsModes mode)) { ns_enabled_ = enable; ns_mode_ = mode; return 0; } WEBRTC_FUNC(GetNsStatus, (bool& enabled, webrtc::NsModes& mode)) { enabled = ns_enabled_; mode = ns_mode_; return 0; } WEBRTC_STUB(SetAgcStatus, (bool enable, webrtc::AgcModes mode)); WEBRTC_STUB(GetAgcStatus, (bool& enabled, webrtc::AgcModes& mode)); WEBRTC_FUNC(SetAgcConfig, (const webrtc::AgcConfig config)) { agc_config_ = config; return 0; } WEBRTC_FUNC(GetAgcConfig, (webrtc::AgcConfig& config)) { config = agc_config_; return 0; } WEBRTC_FUNC(SetEcStatus, (bool enable, webrtc::EcModes mode)) { ec_enabled_ = enable; ec_mode_ = mode; return 0; } WEBRTC_FUNC(GetEcStatus, (bool& enabled, webrtc::EcModes& mode)) { enabled = ec_enabled_; mode = ec_mode_; return 0; } virtual void SetDelayOffsetMs(int offset) {} WEBRTC_STUB(DelayOffsetMs, ()); WEBRTC_STUB(SetAecmMode, (webrtc::AecmModes mode, bool enableCNG)); WEBRTC_STUB(GetAecmMode, (webrtc::AecmModes& mode, bool& enabledCNG)); WEBRTC_STUB(SetRxNsStatus, (int channel, bool enable, webrtc::NsModes mode)); WEBRTC_STUB(GetRxNsStatus, (int channel, bool& enabled, webrtc::NsModes& mode)); WEBRTC_STUB(SetRxAgcStatus, (int channel, bool enable, webrtc::AgcModes mode)); WEBRTC_STUB(GetRxAgcStatus, (int channel, bool& enabled, webrtc::AgcModes& mode)); WEBRTC_STUB(SetRxAgcConfig, (int channel, const webrtc::AgcConfig config)); WEBRTC_STUB(GetRxAgcConfig, (int channel, webrtc::AgcConfig& config)); WEBRTC_STUB(RegisterRxVadObserver, (int, webrtc::VoERxVadCallback&)); WEBRTC_STUB(DeRegisterRxVadObserver, (int channel)); WEBRTC_STUB(VoiceActivityIndicator, (int channel)); WEBRTC_STUB(SetEcMetricsStatus, (bool enable)); WEBRTC_STUB(GetEcMetricsStatus, (bool& enable)); WEBRTC_STUB(GetEchoMetrics, (int& ERL, int& ERLE, int& RERL, int& A_NLP)); WEBRTC_STUB(GetEcDelayMetrics, (int& delay_median, int& delay_std)); WEBRTC_STUB(StartDebugRecording, (const char* fileNameUTF8)); WEBRTC_STUB(StopDebugRecording, ()); WEBRTC_STUB(SetTypingDetectionStatus, (bool enable)); WEBRTC_STUB(GetTypingDetectionStatus, (bool& enabled)); // webrtc::VoEExternalMedia WEBRTC_FUNC(RegisterExternalMediaProcessing, (int channel, webrtc::ProcessingTypes type, webrtc::VoEMediaProcess& processObject)) { WEBRTC_CHECK_CHANNEL(channel); if (channels_[channel]->media_processor_registered) { return -1; } channels_[channel]->media_processor_registered = true; media_processor_ = &processObject; return 0; } WEBRTC_FUNC(DeRegisterExternalMediaProcessing, (int channel, webrtc::ProcessingTypes type)) { WEBRTC_CHECK_CHANNEL(channel); if (!channels_[channel]->media_processor_registered) { return -1; } channels_[channel]->media_processor_registered = false; media_processor_ = NULL; return 0; } WEBRTC_STUB(SetExternalRecordingStatus, (bool enable)); WEBRTC_STUB(SetExternalPlayoutStatus, (bool enable)); WEBRTC_STUB(ExternalRecordingInsertData, (const WebRtc_Word16 speechData10ms[], int lengthSamples, int samplingFreqHz, int current_delay_ms)); WEBRTC_STUB(ExternalPlayoutGetData, (WebRtc_Word16 speechData10ms[], int samplingFreqHz, int current_delay_ms, int& lengthSamples)); private: int GetNumDevices(int& num) { #ifdef WIN32 num = 1; #else // On non-Windows platforms VE adds a special entry for the default device, // so if there is one physical device then there are two entries in the // list. num = 2; #endif return 0; } int GetDeviceName(int i, char* name, char* guid) { const char *s; #ifdef WIN32 if (0 == i) { s = kFakeDeviceName; } else { return -1; } #else // See comment above. if (0 == i) { s = kFakeDefaultDeviceName; } else if (1 == i) { s = kFakeDeviceName; } else { return -1; } #endif strcpy(name, s); guid[0] = '\0'; return 0; } bool inited_; int last_channel_; std::map<int, Channel*> channels_; bool fail_create_channel_; const cricket::AudioCodec* const* codecs_; int num_codecs_; bool ec_enabled_; bool ns_enabled_; webrtc::EcModes ec_mode_; webrtc::NsModes ns_mode_; webrtc::AgcConfig agc_config_; webrtc::VoiceEngineObserver* observer_; int playout_fail_channel_; int send_fail_channel_; bool fail_start_recording_microphone_; bool recording_microphone_; webrtc::VoEMediaProcess* media_processor_; }; } // namespace cricket #endif // TALK_SESSION_PHONE_FAKEWEBRTCVOICEENGINE_H_
Jtalk/kopete-fork-xep0136
protocols/jabber/libjingle/talk/session/phone/fakewebrtcvoiceengine.h
C
lgpl-2.1
34,763
/* * 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 Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * FtdiDmxDevice.cpp * The FTDI usb chipset DMX plugin for ola * Copyright (C) 2011 Rui Barreiros * * Additional modifications to enable support for multiple outputs and * additional device ids did change the original structure. * * by E.S. Rosenberg a.k.a. Keeper of the Keys 5774/2014 */ #include <string> #include <memory> #include "ola/Logging.h" #include "plugins/ftdidmx/FtdiDmxDevice.h" #include "plugins/ftdidmx/FtdiDmxPort.h" namespace ola { namespace plugin { namespace ftdidmx { using std::string; FtdiDmxDevice::FtdiDmxDevice(AbstractPlugin *owner, const FtdiWidgetInfo &widget_info, unsigned int frequency) : Device(owner, widget_info.Description()), m_widget_info(widget_info), m_frequency(frequency) { m_widget = new FtdiWidget(widget_info.Serial(), widget_info.Name(), widget_info.Id(), widget_info.Vid(), widget_info.Pid()); } FtdiDmxDevice::~FtdiDmxDevice() { DeleteAllPorts(); delete m_widget; } bool FtdiDmxDevice::StartHook() { unsigned int interface_count = m_widget->GetInterfaceCount(); unsigned int successfully_added = 0; OLA_INFO << "Widget " << m_widget->Name() << " has " << interface_count << " interfaces."; for (unsigned int i = 1; i <= interface_count; i++) { FtdiInterface *port = new FtdiInterface(m_widget, static_cast<ftdi_interface>(i)); if (port->SetupOutput()) { AddPort(new FtdiDmxOutputPort(this, port, i, m_frequency)); successfully_added += 1; } else { OLA_WARN << "Failed to add interface: " << i; delete port; } } if (successfully_added > 0) { OLA_INFO << "Successfully added " << successfully_added << "/" << interface_count << " interfaces."; } else { OLA_INFO << "Removing widget since no ports were added."; return false; } return true; } } // namespace ftdidmx } // namespace plugin } // namespace ola
nightrune/ola
plugins/ftdidmx/FtdiDmxDevice.cpp
C++
lgpl-2.1
2,834
// Copyright © 2004-2006 University of Helsinki, Department of Computer Science // Copyright © 2012 various contributors // This software is released under GNU Lesser General Public License 2.1. // The license text is at http://www.gnu.org/licenses/lgpl-2.1.html /* * Created on Feb 24, 2004 */ package fi.helsinki.cs.ttk91; import java.util.HashMap; /* * See separate documentation in yhteisapi.pdf in the javadoc root. */ public interface TTK91Memory { /** * @return the size of the memory. */ public int getSize(); /** * First usable index is 0, last is getSize()-1 * * @param memoryslot memory address where required data is * @return data from requested address */ public int getValue(int memoryslot); /** * @return HashMap with symbol name as a key, and Integer as value. * Integer describes the memory slot where the value is stored. */ public HashMap<String, Integer> getSymbolTable(); /** * @return whole memory as a dump */ public int[] getMemory(); /** * @return a code area dump. assumed to be located from * offset 0 to "codeAreaSize" */ public int[] getCodeArea(); /** * @return a data area dump. Assumed to be located beginning * from the end of codeAreaSize to codeAreaSize+dataAreaSize */ public int[] getDataArea(); }
titokone/titokone
src/main/java/fi/helsinki/cs/ttk91/TTK91Memory.java
Java
lgpl-2.1
1,412
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Sam Lantinga slouken@libsdl.org */ #include "SDL_config.h" #ifndef _SDL_os2fslib_h #define _SDL_os2fslib_h // OS2 specific includes #define INCL_TYPES #define INCL_DOS #define INCL_DOSERRORS #define INCL_DOSPROCESS #define INCL_WIN #define INCL_GPI #include <os2.h> #include <FSLib.h> /* Hidden "this" pointer for the video functions */ #define _THIS SDL_VideoDevice *_this /* Private display data */ struct SDL_PrivateVideoData { FSLib_VideoMode_p pAvailableFSLibVideoModes; SDL_Rect **pListModesResult; // Allocated memory to return list of modes for os2fslib_ListModes() API FSLib_VideoMode SrcBufferDesc; // Description of current source image buffer char *pchSrcBuffer; // The source image buffer itself SDL_Surface *pSDLSurface; // The SDL surface describing the buffer HMTX hmtxUseSrcBuffer; // Mutex semaphore to manipulate src buffer HWND hwndFrame, hwndClient; // Window handle of frame and client int iPMThreadStatus; // 0: Not running // 1: Running // Other: Not running, had an error int tidPMThread; // Thread ID of PM Thread int fInFocus; // True if we're in focus! int iSkipWMMOUSEMOVE; // Number of WM_MOUSEMOVE messages to skip! int iMouseVisible; // PFNWP pfnOldFrameProc; // Old window frame procedure int bProportionalResize; // 0: No proportional resizing // 1: Do proportional resizing ULONG ulResizingFlag; // First resizing flag value }; /* OS/2 specific backdoor function to be able to set FrameControlFlags of */ /* the SDL window before creating it. */ extern DECLSPEC void SDLCALL SDL_OS2FSLIB_SetFCFToUse(ULONG ulFCF); #endif /* _SDL_os2fslib_h */ /* vi: set ts=4 sw=4 expandtab: */
Cpasjuste/SDL-13
src/video/os2fslib/SDL_os2fslib.h
C
lgpl-2.1
2,607
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Class template direct_event_type_mapping</title> <link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../../index.html" title="Chapter 1. Boost.Log v2"> <link rel="up" href="../../../../sinks.html#header.boost.log.sinks.event_log_backend_hpp" title="Header &lt;boost/log/sinks/event_log_backend.hpp&gt;"> <link rel="prev" href="direct_event_id_mapping.html" title="Class template direct_event_id_mapping"> <link rel="next" href="../basic_event_log_backend.html" title="Class template basic_event_log_backend"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr><td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../../boost.png"></td></tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="direct_event_id_mapping.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../../sinks.html#header.boost.log.sinks.event_log_backend_hpp"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../basic_event_log_backend.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.log.sinks.event_log.direct_event_type_mapping"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Class template direct_event_type_mapping</span></h2> <p>boost::log::sinks::event_log::direct_event_type_mapping — Straightforward event type mapping. </p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../../../sinks.html#header.boost.log.sinks.event_log_backend_hpp" title="Header &lt;boost/log/sinks/event_log_backend.hpp&gt;">boost/log/sinks/event_log_backend.hpp</a>&gt; </span><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> AttributeValueT <span class="special">=</span> <span class="keyword">int</span><span class="special">&gt;</span> <span class="keyword">class</span> <a class="link" href="direct_event_type_mapping.html" title="Class template direct_event_type_mapping">direct_event_type_mapping</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">basic_direct_mapping</span><span class="special">&lt;</span> <span class="identifier">event_type</span><span class="special">,</span> <span class="identifier">AttributeValueT</span> <span class="special">&gt;</span> <span class="special">{</span> <span class="keyword">public</span><span class="special">:</span> <span class="comment">// <a class="link" href="direct_event_type_mapping.html#boost.log.sinks.event_log.direct_event_type_mappingconstruct-copy-destruct">construct/copy/destruct</a></span> <span class="keyword">explicit</span> <a class="link" href="direct_event_type_mapping.html#idm32937-bb"><span class="identifier">direct_event_type_mapping</span></a><span class="special">(</span><span class="identifier">attribute_name</span> <span class="keyword">const</span> <span class="special">&amp;</span><span class="special">)</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idm66866"></a><h2>Description</h2> <p>This type of mapping assumes that attribute with a particular name always provides values that map directly onto the native event types. The mapping simply returns the extracted attribute value converted to the native event type. </p> <div class="refsect2"> <a name="idm66869"></a><h3> <a name="boost.log.sinks.event_log.direct_event_type_mappingconstruct-copy-destruct"></a><code class="computeroutput">direct_event_type_mapping</code> public construct/copy/destruct</h3> <div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"> <pre class="literallayout"><span class="keyword">explicit</span> <a name="idm32937-bb"></a><span class="identifier">direct_event_type_mapping</span><span class="special">(</span><span class="identifier">attribute_name</span> <span class="keyword">const</span> <span class="special">&amp;</span> name<span class="special">)</span><span class="special">;</span></pre> <p>Constructor</p> <p> </p> <div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody><tr> <td><p><span class="term">Parameters:</span></p></td> <td><div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody><tr> <td><p><span class="term"><code class="computeroutput">name</code></span></p></td> <td><p>Attribute name </p></td> </tr></tbody> </table></div></td> </tr></tbody> </table></div> </li></ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright © 2007-2021 Andrey Semashev<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>). </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="direct_event_id_mapping.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../../sinks.html#header.boost.log.sinks.event_log_backend_hpp"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../basic_event_log_backend.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
qianqians/abelkhan
cpp_component/3rdparty/boost/libs/log/doc/html/boost/log/sinks/event_log/direct_event_type_mapping.html
HTML
lgpl-2.1
6,494
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------------- * ClosestFirstIteratorTest.java * ----------------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: ClosestFirstIteratorTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 03-Sep-2003 : Initial revision (JVS); * 29-May-2005 : Test radius support (JVS); * */ package org.jgrapht.traverse; import org.jgrapht.*; import org.jgrapht.graph.*; /** * Tests for ClosestFirstIterator. * * @author John V. Sichi * @since Sep 3, 2003 */ public class ClosestFirstIteratorTest extends AbstractGraphIteratorTest { //~ Methods ---------------------------------------------------------------- /** * . */ public void testRadius() { result = new StringBuffer(); DirectedGraph<String, DefaultEdge> graph = createDirectedGraph(); // NOTE: pick 301 as the radius because it discriminates // the boundary case edge between v7 and v9 AbstractGraphIterator<String, ?> iterator = new ClosestFirstIterator<String, DefaultEdge>(graph, "1", 301); while (iterator.hasNext()) { result.append(iterator.next()); if (iterator.hasNext()) { result.append(','); } } assertEquals("1,2,3,5,6,7", result.toString()); } /** * . */ public void testNoStart() { result = new StringBuffer(); DirectedGraph<String, DefaultEdge> graph = createDirectedGraph(); AbstractGraphIterator<String, ?> iterator = new ClosestFirstIterator<String, DefaultEdge>(graph); while (iterator.hasNext()) { result.append(iterator.next()); if (iterator.hasNext()) { result.append(','); } } assertEquals("1,2,3,5,6,7,9,4,8,orphan", result.toString()); } // NOTE: the edge weights make the result deterministic String getExpectedStr1() { return "1,2,3,5,6,7,9,4,8"; } String getExpectedStr2() { return getExpectedStr1() + ",orphan"; } AbstractGraphIterator<String, DefaultEdge> createIterator( DirectedGraph<String, DefaultEdge> g, String vertex) { AbstractGraphIterator<String, DefaultEdge> i = new ClosestFirstIterator<String, DefaultEdge>(g, vertex); i.setCrossComponentTraversal(true); return i; } } // End ClosestFirstIteratorTest.java
redvox/gka
testsrc/org/jgrapht/traverse/ClosestFirstIteratorTest.java
Java
lgpl-2.1
3,645
define([ './templates' ], function () { var $ = jQuery; Handlebars.registerHelper('issuesHomeLink', function (property, value) { return baseUrl + '/issues/search#resolved=false|createdInLast=1w|' + property + '=' + (encodeURIComponent(value)); }); Handlebars.registerHelper('myIssuesHomeLink', function (property, value) { return baseUrl + '/issues/search#resolved=false|createdInLast=1w|assignees=__me__|' + property + '=' + (encodeURIComponent(value)); }); Handlebars.registerHelper('issueFilterHomeLink', function (id) { return baseUrl + '/issues/search#id=' + id; }); return Marionette.ItemView.extend({ template: Templates['issues-workspace-home'], modelEvents: { 'change': 'render' }, events: { 'click .js-barchart rect': 'selectBar', 'click .js-my-barchart rect': 'selectMyBar' }, initialize: function () { this.model = new Backbone.Model(); this.requestIssues(); this.requestMyIssues(); }, _getProjects: function (r) { var projectFacet = _.findWhere(r.facets, { property: 'projectUuids' }); if (projectFacet != null) { var values = _.head(projectFacet.values, 3); values.forEach(function (v) { var project = _.findWhere(r.components, { uuid: v.val }); v.label = project.longName; }); return values; } }, _getAuthors: function (r) { var authorFacet = _.findWhere(r.facets, { property: 'authors' }); if (authorFacet != null) { return _.head(authorFacet.values, 3); } }, _getTags: function (r) { var MIN_SIZE = 10, MAX_SIZE = 24, tagFacet = _.findWhere(r.facets, { property: 'tags' }); if (tagFacet != null) { var values = _.head(tagFacet.values, 10), minCount = _.min(values, function (v) { return v.count; }).count, maxCount = _.max(values, function (v) { return v.count; }).count, scale = d3.scale.linear().domain([minCount, maxCount]).range([MIN_SIZE, MAX_SIZE]); values.forEach(function (v) { v.size = scale(v.count); }); return values; } }, requestIssues: function () { var that = this; var url = baseUrl + '/api/issues/search', options = { resolved: false, createdInLast: '1w', ps: 1, facets: 'createdAt,projectUuids,authors,tags' }; return $.get(url, options).done(function (r) { var createdAt = _.findWhere(r.facets, { property: 'createdAt' }); that.model.set({ createdAt: createdAt != null ? createdAt.values : null, projects: that._getProjects(r), authors: that._getAuthors(r), tags: that._getTags(r) }); }); }, requestMyIssues: function () { var that = this; var url = baseUrl + '/api/issues/search', options = { resolved: false, createdInLast: '1w', assignees: '__me__', ps: 1, facets: 'createdAt,projectUuids,authors,tags' }; return $.get(url, options).done(function (r) { var createdAt = _.findWhere(r.facets, { property: 'createdAt' }); return that.model.set({ myCreatedAt: createdAt != null ? createdAt.values : null, myProjects: that._getProjects(r), myTags: that._getTags(r) }); }); }, _addFormattedValues: function (values) { return values.map(function (v) { var text = window.formatMeasure(v.count, 'SHORT_INT'); return _.extend(v, { text: text }); }); }, onRender: function () { var values = this.model.get('createdAt'), myValues = this.model.get('myCreatedAt'); if (values != null) { this.$('.js-barchart').barchart(this._addFormattedValues(values)); } if (myValues != null) { this.$('.js-my-barchart').barchart(this._addFormattedValues(myValues)); } this.$('[data-toggle="tooltip"]').tooltip({ container: 'body' }); }, onDestroy: function () { this.$('[data-toggle="tooltip"]').tooltip('destroy'); }, selectBar: function (e) { var periodStart = $(e.currentTarget).data('period-start'), periodEnd = $(e.currentTarget).data('period-end'); this.options.app.state.setQuery({ resolved: false, createdAfter: periodStart, createdBefore: periodEnd }); }, selectMyBar: function (e) { var periodStart = $(e.currentTarget).data('period-start'), periodEnd = $(e.currentTarget).data('period-end'); this.options.app.state.setQuery({ resolved: false, assignees: '__me__', createdAfter: periodStart, createdBefore: periodEnd }); }, serializeData: function () { return _.extend(Marionette.ItemView.prototype.serializeData.apply(this, arguments), { user: window.SS.user, filters: _.sortBy(this.options.app.filters.toJSON(), 'name') }); } }); });
julien-sobczak/sonarqube
server/sonar-web/src/main/js/apps/issues/workspace-home-view.js
JavaScript
lgpl-3.0
5,191
using System; using NUnit.Framework; namespace NetMQ.Tests { [TestFixture] public class EventDelegatorTests { private class Args<T> : EventArgs { public Args(T value) { Value = value; } public T Value { get; } } private event EventHandler<Args<int>> Source; [Test] public void Basics() { EventHandler<Args<int>> sourceHandler = null; var delegator = new EventDelegator<Args<double>>( () => Source += sourceHandler, () => Source -= sourceHandler); sourceHandler = (sender, args) => delegator.Fire(this, new Args<double>(args.Value / 2.0)); Assert.IsNull(Source); var value = 0.0; var callCount = 0; EventHandler<Args<double>> delegatorHandler = (sender, args) => { value = args.Value; callCount++; }; delegator.Event += delegatorHandler; Assert.IsNotNull(Source); Assert.AreEqual(0, callCount); Source(this, new Args<int>(5)); Assert.AreEqual(2.5, value); Assert.AreEqual(1, callCount); Source(this, new Args<int>(12)); Assert.AreEqual(6.0, value); Assert.AreEqual(2, callCount); delegator.Event -= delegatorHandler; Assert.IsNull(Source); } } }
buybackoff/netmq
src/NetMQ.Tests/EventDelegatorTests.cs
C#
lgpl-3.0
1,543
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package android.support.v7.appcompat; public final class R { public static final class anim { public static final int abc_fade_in = 0x7f040000; public static final int abc_fade_out = 0x7f040001; public static final int abc_slide_in_bottom = 0x7f040002; public static final int abc_slide_in_top = 0x7f040003; public static final int abc_slide_out_bottom = 0x7f040004; public static final int abc_slide_out_top = 0x7f040005; } public static final class attr { public static final int actionBarDivider = 0x7f01000f; public static final int actionBarItemBackground = 0x7f010010; public static final int actionBarSize = 0x7f01000e; public static final int actionBarSplitStyle = 0x7f01000c; public static final int actionBarStyle = 0x7f01000b; public static final int actionBarTabBarStyle = 0x7f010008; public static final int actionBarTabStyle = 0x7f010007; public static final int actionBarTabTextStyle = 0x7f010009; public static final int actionBarWidgetTheme = 0x7f01000d; public static final int actionButtonStyle = 0x7f010016; public static final int actionDropDownStyle = 0x7f010047; public static final int actionLayout = 0x7f01004e; public static final int actionMenuTextAppearance = 0x7f010011; public static final int actionMenuTextColor = 0x7f010012; public static final int actionModeBackground = 0x7f01003c; public static final int actionModeCloseButtonStyle = 0x7f01003b; public static final int actionModeCloseDrawable = 0x7f01003e; public static final int actionModeCopyDrawable = 0x7f010040; public static final int actionModeCutDrawable = 0x7f01003f; public static final int actionModeFindDrawable = 0x7f010044; public static final int actionModePasteDrawable = 0x7f010041; public static final int actionModePopupWindowStyle = 0x7f010046; public static final int actionModeSelectAllDrawable = 0x7f010042; public static final int actionModeShareDrawable = 0x7f010043; public static final int actionModeSplitBackground = 0x7f01003d; public static final int actionModeStyle = 0x7f01003a; public static final int actionModeWebSearchDrawable = 0x7f010045; public static final int actionOverflowButtonStyle = 0x7f01000a; public static final int actionProviderClass = 0x7f010050; public static final int actionViewClass = 0x7f01004f; public static final int activityChooserViewStyle = 0x7f01006c; public static final int background = 0x7f01002f; public static final int backgroundSplit = 0x7f010031; public static final int backgroundStacked = 0x7f010030; public static final int buttonBarButtonStyle = 0x7f010018; public static final int buttonBarStyle = 0x7f010017; public static final int customNavigationLayout = 0x7f010032; public static final int disableChildrenWhenDisabled = 0x7f010054; public static final int displayOptions = 0x7f010028; public static final int divider = 0x7f01002e; public static final int dividerHorizontal = 0x7f01001b; public static final int dividerPadding = 0x7f010056; public static final int dividerVertical = 0x7f01001a; public static final int dropDownListViewStyle = 0x7f010021; public static final int dropdownListPreferredItemHeight = 0x7f010048; public static final int expandActivityOverflowButtonDrawable = 0x7f01006b; public static final int height = 0x7f010026; public static final int homeAsUpIndicator = 0x7f010013; public static final int homeLayout = 0x7f010033; public static final int icon = 0x7f01002c; public static final int iconifiedByDefault = 0x7f01005a; public static final int indeterminateProgressStyle = 0x7f010035; public static final int initialActivityCount = 0x7f01006a; public static final int isLightTheme = 0x7f010059; public static final int itemPadding = 0x7f010037; public static final int listChoiceBackgroundIndicator = 0x7f01004c; public static final int listPopupWindowStyle = 0x7f010022; public static final int listPreferredItemHeight = 0x7f01001c; public static final int listPreferredItemHeightLarge = 0x7f01001e; public static final int listPreferredItemHeightSmall = 0x7f01001d; public static final int listPreferredItemPaddingLeft = 0x7f01001f; public static final int listPreferredItemPaddingRight = 0x7f010020; public static final int logo = 0x7f01002d; public static final int navigationMode = 0x7f010027; public static final int paddingEnd = 0x7f010039; public static final int paddingStart = 0x7f010038; public static final int panelMenuListTheme = 0x7f01004b; public static final int panelMenuListWidth = 0x7f01004a; public static final int popupMenuStyle = 0x7f010049; public static final int popupPromptView = 0x7f010053; public static final int progressBarPadding = 0x7f010036; public static final int progressBarStyle = 0x7f010034; public static final int prompt = 0x7f010051; public static final int queryHint = 0x7f01005b; public static final int searchDropdownBackground = 0x7f01005c; public static final int searchResultListItemHeight = 0x7f010065; public static final int searchViewAutoCompleteTextView = 0x7f010069; public static final int searchViewCloseIcon = 0x7f01005d; public static final int searchViewEditQuery = 0x7f010061; public static final int searchViewEditQueryBackground = 0x7f010062; public static final int searchViewGoIcon = 0x7f01005e; public static final int searchViewSearchIcon = 0x7f01005f; public static final int searchViewTextField = 0x7f010063; public static final int searchViewTextFieldRight = 0x7f010064; public static final int searchViewVoiceIcon = 0x7f010060; public static final int selectableItemBackground = 0x7f010019; public static final int showAsAction = 0x7f01004d; public static final int showDividers = 0x7f010055; public static final int spinnerDropDownItemStyle = 0x7f010058; public static final int spinnerMode = 0x7f010052; public static final int spinnerStyle = 0x7f010057; public static final int subtitle = 0x7f010029; public static final int subtitleTextStyle = 0x7f01002b; public static final int textAllCaps = 0x7f01006d; public static final int textAppearanceLargePopupMenu = 0x7f010014; public static final int textAppearanceListItem = 0x7f010023; public static final int textAppearanceListItemSmall = 0x7f010024; public static final int textAppearanceSearchResultSubtitle = 0x7f010067; public static final int textAppearanceSearchResultTitle = 0x7f010066; public static final int textAppearanceSmallPopupMenu = 0x7f010015; public static final int textColorSearchUrl = 0x7f010068; public static final int title = 0x7f010025; public static final int titleTextStyle = 0x7f01002a; public static final int windowActionBar = 0x7f010000; public static final int windowActionBarOverlay = 0x7f010001; public static final int windowFixedHeightMajor = 0x7f010006; public static final int windowFixedHeightMinor = 0x7f010004; public static final int windowFixedWidthMajor = 0x7f010003; public static final int windowFixedWidthMinor = 0x7f010005; public static final int windowSplitActionBar = 0x7f010002; } public static final class bool { public static final int abc_action_bar_embed_tabs_pre_jb = 0x7f060000; public static final int abc_action_bar_expanded_action_views_exclusive = 0x7f060001; public static final int abc_config_actionMenuItemAllCaps = 0x7f060005; public static final int abc_config_allowActionMenuItemTextWithIcon = 0x7f060004; public static final int abc_config_showMenuShortcutsWhenKeyboardPresent = 0x7f060003; public static final int abc_split_action_bar_is_narrow = 0x7f060002; } public static final class color { public static final int abc_search_url_text_holo = 0x7f070003; public static final int abc_search_url_text_normal = 0x7f070000; public static final int abc_search_url_text_pressed = 0x7f070002; public static final int abc_search_url_text_selected = 0x7f070001; } public static final class dimen { public static final int abc_action_bar_default_height = 0x7f080002; public static final int abc_action_bar_icon_vertical_padding = 0x7f080003; public static final int abc_action_bar_progress_bar_size = 0x7f08000a; public static final int abc_action_bar_stacked_max_height = 0x7f080009; public static final int abc_action_bar_stacked_tab_max_width = 0x7f080001; public static final int abc_action_bar_subtitle_bottom_margin = 0x7f080007; public static final int abc_action_bar_subtitle_text_size = 0x7f080005; public static final int abc_action_bar_subtitle_top_margin = 0x7f080006; public static final int abc_action_bar_title_text_size = 0x7f080004; public static final int abc_action_button_min_width = 0x7f080008; public static final int abc_config_prefDialogWidth = 0x7f080000; public static final int abc_dropdownitem_icon_width = 0x7f080010; public static final int abc_dropdownitem_text_padding_left = 0x7f08000e; public static final int abc_dropdownitem_text_padding_right = 0x7f08000f; public static final int abc_panel_menu_list_width = 0x7f08000b; public static final int abc_search_view_preferred_width = 0x7f08000d; public static final int abc_search_view_text_min_width = 0x7f08000c; public static final int dialog_fixed_height_major = 0x7f080013; public static final int dialog_fixed_height_minor = 0x7f080014; public static final int dialog_fixed_width_major = 0x7f080011; public static final int dialog_fixed_width_minor = 0x7f080012; } public static final class drawable { public static final int abc_ab_bottom_solid_dark_holo = 0x7f020000; public static final int abc_ab_bottom_solid_light_holo = 0x7f020001; public static final int abc_ab_bottom_transparent_dark_holo = 0x7f020002; public static final int abc_ab_bottom_transparent_light_holo = 0x7f020003; public static final int abc_ab_share_pack_holo_dark = 0x7f020004; public static final int abc_ab_share_pack_holo_light = 0x7f020005; public static final int abc_ab_solid_dark_holo = 0x7f020006; public static final int abc_ab_solid_light_holo = 0x7f020007; public static final int abc_ab_stacked_solid_dark_holo = 0x7f020008; public static final int abc_ab_stacked_solid_light_holo = 0x7f020009; public static final int abc_ab_stacked_transparent_dark_holo = 0x7f02000a; public static final int abc_ab_stacked_transparent_light_holo = 0x7f02000b; public static final int abc_ab_transparent_dark_holo = 0x7f02000c; public static final int abc_ab_transparent_light_holo = 0x7f02000d; public static final int abc_cab_background_bottom_holo_dark = 0x7f02000e; public static final int abc_cab_background_bottom_holo_light = 0x7f02000f; public static final int abc_cab_background_top_holo_dark = 0x7f020010; public static final int abc_cab_background_top_holo_light = 0x7f020011; public static final int abc_ic_ab_back_holo_dark = 0x7f020012; public static final int abc_ic_ab_back_holo_light = 0x7f020013; public static final int abc_ic_cab_done_holo_dark = 0x7f020014; public static final int abc_ic_cab_done_holo_light = 0x7f020015; public static final int abc_ic_clear = 0x7f020016; public static final int abc_ic_clear_disabled = 0x7f020017; public static final int abc_ic_clear_holo_light = 0x7f020018; public static final int abc_ic_clear_normal = 0x7f020019; public static final int abc_ic_clear_search_api_disabled_holo_light = 0x7f02001a; public static final int abc_ic_clear_search_api_holo_light = 0x7f02001b; public static final int abc_ic_commit_search_api_holo_dark = 0x7f02001c; public static final int abc_ic_commit_search_api_holo_light = 0x7f02001d; public static final int abc_ic_go = 0x7f02001e; public static final int abc_ic_go_search_api_holo_light = 0x7f02001f; public static final int abc_ic_menu_moreoverflow_normal_holo_dark = 0x7f020020; public static final int abc_ic_menu_moreoverflow_normal_holo_light = 0x7f020021; public static final int abc_ic_menu_share_holo_dark = 0x7f020022; public static final int abc_ic_menu_share_holo_light = 0x7f020023; public static final int abc_ic_search = 0x7f020024; public static final int abc_ic_search_api_holo_light = 0x7f020025; public static final int abc_ic_voice_search = 0x7f020026; public static final int abc_ic_voice_search_api_holo_light = 0x7f020027; public static final int abc_item_background_holo_dark = 0x7f020028; public static final int abc_item_background_holo_light = 0x7f020029; public static final int abc_list_divider_holo_dark = 0x7f02002a; public static final int abc_list_divider_holo_light = 0x7f02002b; public static final int abc_list_focused_holo = 0x7f02002c; public static final int abc_list_longpressed_holo = 0x7f02002d; public static final int abc_list_pressed_holo_dark = 0x7f02002e; public static final int abc_list_pressed_holo_light = 0x7f02002f; public static final int abc_list_selector_background_transition_holo_dark = 0x7f020030; public static final int abc_list_selector_background_transition_holo_light = 0x7f020031; public static final int abc_list_selector_disabled_holo_dark = 0x7f020032; public static final int abc_list_selector_disabled_holo_light = 0x7f020033; public static final int abc_list_selector_holo_dark = 0x7f020034; public static final int abc_list_selector_holo_light = 0x7f020035; public static final int abc_menu_dropdown_panel_holo_dark = 0x7f020036; public static final int abc_menu_dropdown_panel_holo_light = 0x7f020037; public static final int abc_menu_hardkey_panel_holo_dark = 0x7f020038; public static final int abc_menu_hardkey_panel_holo_light = 0x7f020039; public static final int abc_search_dropdown_dark = 0x7f02003a; public static final int abc_search_dropdown_light = 0x7f02003b; public static final int abc_spinner_ab_default_holo_dark = 0x7f02003c; public static final int abc_spinner_ab_default_holo_light = 0x7f02003d; public static final int abc_spinner_ab_disabled_holo_dark = 0x7f02003e; public static final int abc_spinner_ab_disabled_holo_light = 0x7f02003f; public static final int abc_spinner_ab_focused_holo_dark = 0x7f020040; public static final int abc_spinner_ab_focused_holo_light = 0x7f020041; public static final int abc_spinner_ab_holo_dark = 0x7f020042; public static final int abc_spinner_ab_holo_light = 0x7f020043; public static final int abc_spinner_ab_pressed_holo_dark = 0x7f020044; public static final int abc_spinner_ab_pressed_holo_light = 0x7f020045; public static final int abc_tab_indicator_ab_holo = 0x7f020046; public static final int abc_tab_selected_focused_holo = 0x7f020047; public static final int abc_tab_selected_holo = 0x7f020048; public static final int abc_tab_selected_pressed_holo = 0x7f020049; public static final int abc_tab_unselected_pressed_holo = 0x7f02004a; public static final int abc_textfield_search_default_holo_dark = 0x7f02004b; public static final int abc_textfield_search_default_holo_light = 0x7f02004c; public static final int abc_textfield_search_right_default_holo_dark = 0x7f02004d; public static final int abc_textfield_search_right_default_holo_light = 0x7f02004e; public static final int abc_textfield_search_right_selected_holo_dark = 0x7f02004f; public static final int abc_textfield_search_right_selected_holo_light = 0x7f020050; public static final int abc_textfield_search_selected_holo_dark = 0x7f020051; public static final int abc_textfield_search_selected_holo_light = 0x7f020052; public static final int abc_textfield_searchview_holo_dark = 0x7f020053; public static final int abc_textfield_searchview_holo_light = 0x7f020054; public static final int abc_textfield_searchview_right_holo_dark = 0x7f020055; public static final int abc_textfield_searchview_right_holo_light = 0x7f020056; } public static final class id { public static final int action_bar = 0x7f05001c; public static final int action_bar_activity_content = 0x7f050015; public static final int action_bar_container = 0x7f05001b; public static final int action_bar_overlay_layout = 0x7f05001f; public static final int action_bar_root = 0x7f05001a; public static final int action_bar_subtitle = 0x7f050023; public static final int action_bar_title = 0x7f050022; public static final int action_context_bar = 0x7f05001d; public static final int action_menu_divider = 0x7f050016; public static final int action_menu_presenter = 0x7f050017; public static final int action_mode_close_button = 0x7f050024; public static final int activity_chooser_view_content = 0x7f050025; public static final int always = 0x7f05000b; public static final int beginning = 0x7f050011; public static final int checkbox = 0x7f05002d; public static final int collapseActionView = 0x7f05000d; public static final int default_activity_button = 0x7f050028; public static final int dialog = 0x7f05000e; public static final int disableHome = 0x7f050008; public static final int dropdown = 0x7f05000f; public static final int edit_query = 0x7f050030; public static final int end = 0x7f050013; public static final int expand_activities_button = 0x7f050026; public static final int expanded_menu = 0x7f05002c; public static final int home = 0x7f050014; public static final int homeAsUp = 0x7f050005; public static final int icon = 0x7f05002a; public static final int ifRoom = 0x7f05000a; public static final int image = 0x7f050027; public static final int listMode = 0x7f050001; public static final int list_item = 0x7f050029; public static final int middle = 0x7f050012; public static final int never = 0x7f050009; public static final int none = 0x7f050010; public static final int normal = 0x7f050000; public static final int progress_circular = 0x7f050018; public static final int progress_horizontal = 0x7f050019; public static final int radio = 0x7f05002f; public static final int search_badge = 0x7f050032; public static final int search_bar = 0x7f050031; public static final int search_button = 0x7f050033; public static final int search_close_btn = 0x7f050038; public static final int search_edit_frame = 0x7f050034; public static final int search_go_btn = 0x7f05003a; public static final int search_mag_icon = 0x7f050035; public static final int search_plate = 0x7f050036; public static final int search_src_text = 0x7f050037; public static final int search_voice_btn = 0x7f05003b; public static final int shortcut = 0x7f05002e; public static final int showCustom = 0x7f050007; public static final int showHome = 0x7f050004; public static final int showTitle = 0x7f050006; public static final int split_action_bar = 0x7f05001e; public static final int submit_area = 0x7f050039; public static final int tabMode = 0x7f050002; public static final int title = 0x7f05002b; public static final int top_action_bar = 0x7f050020; public static final int up = 0x7f050021; public static final int useLogo = 0x7f050003; public static final int withText = 0x7f05000c; } public static final class integer { public static final int abc_max_action_buttons = 0x7f090000; } public static final class layout { public static final int abc_action_bar_decor = 0x7f030000; public static final int abc_action_bar_decor_include = 0x7f030001; public static final int abc_action_bar_decor_overlay = 0x7f030002; public static final int abc_action_bar_home = 0x7f030003; public static final int abc_action_bar_tab = 0x7f030004; public static final int abc_action_bar_tabbar = 0x7f030005; public static final int abc_action_bar_title_item = 0x7f030006; public static final int abc_action_bar_view_list_nav_layout = 0x7f030007; public static final int abc_action_menu_item_layout = 0x7f030008; public static final int abc_action_menu_layout = 0x7f030009; public static final int abc_action_mode_bar = 0x7f03000a; public static final int abc_action_mode_close_item = 0x7f03000b; public static final int abc_activity_chooser_view = 0x7f03000c; public static final int abc_activity_chooser_view_include = 0x7f03000d; public static final int abc_activity_chooser_view_list_item = 0x7f03000e; public static final int abc_expanded_menu_layout = 0x7f03000f; public static final int abc_list_menu_item_checkbox = 0x7f030010; public static final int abc_list_menu_item_icon = 0x7f030011; public static final int abc_list_menu_item_layout = 0x7f030012; public static final int abc_list_menu_item_radio = 0x7f030013; public static final int abc_popup_menu_item_layout = 0x7f030014; public static final int abc_search_dropdown_item_icons_2line = 0x7f030015; public static final int abc_search_view = 0x7f030016; public static final int abc_simple_decor = 0x7f030017; public static final int support_simple_spinner_dropdown_item = 0x7f03001b; } public static final class string { public static final int abc_action_bar_home_description = 0x7f0a0001; public static final int abc_action_bar_up_description = 0x7f0a0002; public static final int abc_action_menu_overflow_description = 0x7f0a0003; public static final int abc_action_mode_done = 0x7f0a0000; public static final int abc_activity_chooser_view_see_all = 0x7f0a000a; public static final int abc_activitychooserview_choose_application = 0x7f0a0009; public static final int abc_searchview_description_clear = 0x7f0a0006; public static final int abc_searchview_description_query = 0x7f0a0005; public static final int abc_searchview_description_search = 0x7f0a0004; public static final int abc_searchview_description_submit = 0x7f0a0007; public static final int abc_searchview_description_voice = 0x7f0a0008; public static final int abc_shareactionprovider_share_with = 0x7f0a000c; public static final int abc_shareactionprovider_share_with_application = 0x7f0a000b; } public static final class style { public static final int TextAppearance_AppCompat_Base_CompactMenu_Dialog = 0x7f0b0063; public static final int TextAppearance_AppCompat_Base_SearchResult = 0x7f0b006d; public static final int TextAppearance_AppCompat_Base_SearchResult_Subtitle = 0x7f0b006f; public static final int TextAppearance_AppCompat_Base_SearchResult_Title = 0x7f0b006e; public static final int TextAppearance_AppCompat_Base_Widget_PopupMenu_Large = 0x7f0b0069; public static final int TextAppearance_AppCompat_Base_Widget_PopupMenu_Small = 0x7f0b006a; public static final int TextAppearance_AppCompat_Light_Base_SearchResult = 0x7f0b0070; public static final int TextAppearance_AppCompat_Light_Base_SearchResult_Subtitle = 0x7f0b0072; public static final int TextAppearance_AppCompat_Light_Base_SearchResult_Title = 0x7f0b0071; public static final int TextAppearance_AppCompat_Light_Base_Widget_PopupMenu_Large = 0x7f0b006b; public static final int TextAppearance_AppCompat_Light_Base_Widget_PopupMenu_Small = 0x7f0b006c; public static final int TextAppearance_AppCompat_Light_SearchResult_Subtitle = 0x7f0b0035; public static final int TextAppearance_AppCompat_Light_SearchResult_Title = 0x7f0b0034; public static final int TextAppearance_AppCompat_Light_Widget_PopupMenu_Large = 0x7f0b0030; public static final int TextAppearance_AppCompat_Light_Widget_PopupMenu_Small = 0x7f0b0031; public static final int TextAppearance_AppCompat_SearchResult_Subtitle = 0x7f0b0033; public static final int TextAppearance_AppCompat_SearchResult_Title = 0x7f0b0032; public static final int TextAppearance_AppCompat_Widget_ActionBar_Menu = 0x7f0b001a; public static final int TextAppearance_AppCompat_Widget_ActionBar_Subtitle = 0x7f0b0006; public static final int TextAppearance_AppCompat_Widget_ActionBar_Subtitle_Inverse = 0x7f0b0008; public static final int TextAppearance_AppCompat_Widget_ActionBar_Title = 0x7f0b0005; public static final int TextAppearance_AppCompat_Widget_ActionBar_Title_Inverse = 0x7f0b0007; public static final int TextAppearance_AppCompat_Widget_ActionMode_Subtitle = 0x7f0b001e; public static final int TextAppearance_AppCompat_Widget_ActionMode_Subtitle_Inverse = 0x7f0b0020; public static final int TextAppearance_AppCompat_Widget_ActionMode_Title = 0x7f0b001d; public static final int TextAppearance_AppCompat_Widget_ActionMode_Title_Inverse = 0x7f0b001f; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Menu = 0x7f0b0054; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Subtitle = 0x7f0b0056; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Subtitle_Inverse = 0x7f0b0058; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Title = 0x7f0b0055; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Title_Inverse = 0x7f0b0057; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Subtitle = 0x7f0b0051; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Subtitle_Inverse = 0x7f0b0053; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Title = 0x7f0b0050; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Title_Inverse = 0x7f0b0052; public static final int TextAppearance_AppCompat_Widget_Base_DropDownItem = 0x7f0b0061; public static final int TextAppearance_AppCompat_Widget_DropDownItem = 0x7f0b0021; public static final int TextAppearance_AppCompat_Widget_PopupMenu_Large = 0x7f0b002e; public static final int TextAppearance_AppCompat_Widget_PopupMenu_Small = 0x7f0b002f; public static final int TextAppearance_Widget_AppCompat_Base_ExpandedMenu_Item = 0x7f0b0062; public static final int TextAppearance_Widget_AppCompat_ExpandedMenu_Item = 0x7f0b0028; public static final int Theme_AppCompat = 0x7f0b0077; public static final int Theme_AppCompat_Base_CompactMenu = 0x7f0b0083; public static final int Theme_AppCompat_Base_CompactMenu_Dialog = 0x7f0b0084; public static final int Theme_AppCompat_CompactMenu = 0x7f0b007c; public static final int Theme_AppCompat_CompactMenu_Dialog = 0x7f0b007d; public static final int Theme_AppCompat_DialogWhenLarge = 0x7f0b007a; public static final int Theme_AppCompat_Light = 0x7f0b0078; public static final int Theme_AppCompat_Light_DarkActionBar = 0x7f0b0079; public static final int Theme_AppCompat_Light_DialogWhenLarge = 0x7f0b007b; public static final int Theme_Base = 0x7f0b007e; public static final int Theme_Base_AppCompat = 0x7f0b0080; public static final int Theme_Base_AppCompat_DialogWhenLarge = 0x7f0b0085; public static final int Theme_Base_AppCompat_DialogWhenLarge_Base = 0x7f0b0089; public static final int Theme_Base_AppCompat_Dialog_FixedSize = 0x7f0b0087; public static final int Theme_Base_AppCompat_Dialog_Light_FixedSize = 0x7f0b0088; public static final int Theme_Base_AppCompat_Light = 0x7f0b0081; public static final int Theme_Base_AppCompat_Light_DarkActionBar = 0x7f0b0082; public static final int Theme_Base_AppCompat_Light_DialogWhenLarge = 0x7f0b0086; public static final int Theme_Base_AppCompat_Light_DialogWhenLarge_Base = 0x7f0b008a; public static final int Theme_Base_Light = 0x7f0b007f; public static final int Widget_AppCompat_ActionBar = 0x7f0b0000; public static final int Widget_AppCompat_ActionBar_Solid = 0x7f0b0002; public static final int Widget_AppCompat_ActionBar_TabBar = 0x7f0b0011; public static final int Widget_AppCompat_ActionBar_TabText = 0x7f0b0017; public static final int Widget_AppCompat_ActionBar_TabView = 0x7f0b0014; public static final int Widget_AppCompat_ActionButton = 0x7f0b000b; public static final int Widget_AppCompat_ActionButton_CloseMode = 0x7f0b000d; public static final int Widget_AppCompat_ActionButton_Overflow = 0x7f0b000f; public static final int Widget_AppCompat_ActionMode = 0x7f0b001b; public static final int Widget_AppCompat_ActivityChooserView = 0x7f0b0038; public static final int Widget_AppCompat_AutoCompleteTextView = 0x7f0b0036; public static final int Widget_AppCompat_Base_ActionBar = 0x7f0b003a; public static final int Widget_AppCompat_Base_ActionBar_Solid = 0x7f0b003c; public static final int Widget_AppCompat_Base_ActionBar_TabBar = 0x7f0b0045; public static final int Widget_AppCompat_Base_ActionBar_TabText = 0x7f0b004b; public static final int Widget_AppCompat_Base_ActionBar_TabView = 0x7f0b0048; public static final int Widget_AppCompat_Base_ActionButton = 0x7f0b003f; public static final int Widget_AppCompat_Base_ActionButton_CloseMode = 0x7f0b0041; public static final int Widget_AppCompat_Base_ActionButton_Overflow = 0x7f0b0043; public static final int Widget_AppCompat_Base_ActionMode = 0x7f0b004e; public static final int Widget_AppCompat_Base_ActivityChooserView = 0x7f0b0075; public static final int Widget_AppCompat_Base_AutoCompleteTextView = 0x7f0b0073; public static final int Widget_AppCompat_Base_DropDownItem_Spinner = 0x7f0b005d; public static final int Widget_AppCompat_Base_ListPopupWindow = 0x7f0b0065; public static final int Widget_AppCompat_Base_ListView_DropDown = 0x7f0b005f; public static final int Widget_AppCompat_Base_ListView_Menu = 0x7f0b0064; public static final int Widget_AppCompat_Base_PopupMenu = 0x7f0b0067; public static final int Widget_AppCompat_Base_ProgressBar = 0x7f0b005a; public static final int Widget_AppCompat_Base_ProgressBar_Horizontal = 0x7f0b0059; public static final int Widget_AppCompat_Base_Spinner = 0x7f0b005b; public static final int Widget_AppCompat_DropDownItem_Spinner = 0x7f0b0024; public static final int Widget_AppCompat_Light_ActionBar = 0x7f0b0001; public static final int Widget_AppCompat_Light_ActionBar_Solid = 0x7f0b0003; public static final int Widget_AppCompat_Light_ActionBar_Solid_Inverse = 0x7f0b0004; public static final int Widget_AppCompat_Light_ActionBar_TabBar = 0x7f0b0012; public static final int Widget_AppCompat_Light_ActionBar_TabBar_Inverse = 0x7f0b0013; public static final int Widget_AppCompat_Light_ActionBar_TabText = 0x7f0b0018; public static final int Widget_AppCompat_Light_ActionBar_TabText_Inverse = 0x7f0b0019; public static final int Widget_AppCompat_Light_ActionBar_TabView = 0x7f0b0015; public static final int Widget_AppCompat_Light_ActionBar_TabView_Inverse = 0x7f0b0016; public static final int Widget_AppCompat_Light_ActionButton = 0x7f0b000c; public static final int Widget_AppCompat_Light_ActionButton_CloseMode = 0x7f0b000e; public static final int Widget_AppCompat_Light_ActionButton_Overflow = 0x7f0b0010; public static final int Widget_AppCompat_Light_ActionMode_Inverse = 0x7f0b001c; public static final int Widget_AppCompat_Light_ActivityChooserView = 0x7f0b0039; public static final int Widget_AppCompat_Light_AutoCompleteTextView = 0x7f0b0037; public static final int Widget_AppCompat_Light_Base_ActionBar = 0x7f0b003b; public static final int Widget_AppCompat_Light_Base_ActionBar_Solid = 0x7f0b003d; public static final int Widget_AppCompat_Light_Base_ActionBar_Solid_Inverse = 0x7f0b003e; public static final int Widget_AppCompat_Light_Base_ActionBar_TabBar = 0x7f0b0046; public static final int Widget_AppCompat_Light_Base_ActionBar_TabBar_Inverse = 0x7f0b0047; public static final int Widget_AppCompat_Light_Base_ActionBar_TabText = 0x7f0b004c; public static final int Widget_AppCompat_Light_Base_ActionBar_TabText_Inverse = 0x7f0b004d; public static final int Widget_AppCompat_Light_Base_ActionBar_TabView = 0x7f0b0049; public static final int Widget_AppCompat_Light_Base_ActionBar_TabView_Inverse = 0x7f0b004a; public static final int Widget_AppCompat_Light_Base_ActionButton = 0x7f0b0040; public static final int Widget_AppCompat_Light_Base_ActionButton_CloseMode = 0x7f0b0042; public static final int Widget_AppCompat_Light_Base_ActionButton_Overflow = 0x7f0b0044; public static final int Widget_AppCompat_Light_Base_ActionMode_Inverse = 0x7f0b004f; public static final int Widget_AppCompat_Light_Base_ActivityChooserView = 0x7f0b0076; public static final int Widget_AppCompat_Light_Base_AutoCompleteTextView = 0x7f0b0074; public static final int Widget_AppCompat_Light_Base_DropDownItem_Spinner = 0x7f0b005e; public static final int Widget_AppCompat_Light_Base_ListPopupWindow = 0x7f0b0066; public static final int Widget_AppCompat_Light_Base_ListView_DropDown = 0x7f0b0060; public static final int Widget_AppCompat_Light_Base_PopupMenu = 0x7f0b0068; public static final int Widget_AppCompat_Light_Base_Spinner = 0x7f0b005c; public static final int Widget_AppCompat_Light_DropDownItem_Spinner = 0x7f0b0025; public static final int Widget_AppCompat_Light_ListPopupWindow = 0x7f0b002a; public static final int Widget_AppCompat_Light_ListView_DropDown = 0x7f0b0027; public static final int Widget_AppCompat_Light_PopupMenu = 0x7f0b002c; public static final int Widget_AppCompat_Light_Spinner_DropDown_ActionBar = 0x7f0b0023; public static final int Widget_AppCompat_ListPopupWindow = 0x7f0b0029; public static final int Widget_AppCompat_ListView_DropDown = 0x7f0b0026; public static final int Widget_AppCompat_ListView_Menu = 0x7f0b002d; public static final int Widget_AppCompat_PopupMenu = 0x7f0b002b; public static final int Widget_AppCompat_ProgressBar = 0x7f0b000a; public static final int Widget_AppCompat_ProgressBar_Horizontal = 0x7f0b0009; public static final int Widget_AppCompat_Spinner_DropDown_ActionBar = 0x7f0b0022; } public static final class styleable { public static final int[] ActionBar = { 0x7f010025, 0x7f010026, 0x7f010027, 0x7f010028, 0x7f010029, 0x7f01002a, 0x7f01002b, 0x7f01002c, 0x7f01002d, 0x7f01002e, 0x7f01002f, 0x7f010030, 0x7f010031, 0x7f010032, 0x7f010033, 0x7f010034, 0x7f010035, 0x7f010036, 0x7f010037 }; public static final int[] ActionBarLayout = { 0x010100b3 }; public static final int ActionBarLayout_android_layout_gravity = 0; public static final int[] ActionBarWindow = { 0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003, 0x7f010004, 0x7f010005, 0x7f010006 }; public static final int ActionBarWindow_windowActionBar = 0; public static final int ActionBarWindow_windowActionBarOverlay = 1; public static final int ActionBarWindow_windowFixedHeightMajor = 6; public static final int ActionBarWindow_windowFixedHeightMinor = 4; public static final int ActionBarWindow_windowFixedWidthMajor = 3; public static final int ActionBarWindow_windowFixedWidthMinor = 5; public static final int ActionBarWindow_windowSplitActionBar = 2; public static final int ActionBar_background = 10; public static final int ActionBar_backgroundSplit = 12; public static final int ActionBar_backgroundStacked = 11; public static final int ActionBar_customNavigationLayout = 13; public static final int ActionBar_displayOptions = 3; public static final int ActionBar_divider = 9; public static final int ActionBar_height = 1; public static final int ActionBar_homeLayout = 14; public static final int ActionBar_icon = 7; public static final int ActionBar_indeterminateProgressStyle = 16; public static final int ActionBar_itemPadding = 18; public static final int ActionBar_logo = 8; public static final int ActionBar_navigationMode = 2; public static final int ActionBar_progressBarPadding = 17; public static final int ActionBar_progressBarStyle = 15; public static final int ActionBar_subtitle = 4; public static final int ActionBar_subtitleTextStyle = 6; public static final int ActionBar_title = 0; public static final int ActionBar_titleTextStyle = 5; public static final int[] ActionMenuItemView = { 0x0101013f }; public static final int ActionMenuItemView_android_minWidth = 0; public static final int[] ActionMenuView = { }; public static final int[] ActionMode = { 0x7f010026, 0x7f01002a, 0x7f01002b, 0x7f01002f, 0x7f010031 }; public static final int ActionMode_background = 3; public static final int ActionMode_backgroundSplit = 4; public static final int ActionMode_height = 0; public static final int ActionMode_subtitleTextStyle = 2; public static final int ActionMode_titleTextStyle = 1; public static final int[] ActivityChooserView = { 0x7f01006a, 0x7f01006b }; public static final int ActivityChooserView_expandActivityOverflowButtonDrawable = 1; public static final int ActivityChooserView_initialActivityCount = 0; public static final int[] CompatTextView = { 0x7f01006d }; public static final int CompatTextView_textAllCaps = 0; public static final int[] LinearLayoutICS = { 0x7f01002e, 0x7f010055, 0x7f010056 }; public static final int LinearLayoutICS_divider = 0; public static final int LinearLayoutICS_dividerPadding = 2; public static final int LinearLayoutICS_showDividers = 1; public static final int[] MenuGroup = { 0x0101000e, 0x010100d0, 0x01010194, 0x010101de, 0x010101df, 0x010101e0 }; public static final int MenuGroup_android_checkableBehavior = 5; public static final int MenuGroup_android_enabled = 0; public static final int MenuGroup_android_id = 1; public static final int MenuGroup_android_menuCategory = 3; public static final int MenuGroup_android_orderInCategory = 4; public static final int MenuGroup_android_visible = 2; public static final int[] MenuItem = { 0x01010002, 0x0101000e, 0x010100d0, 0x01010106, 0x01010194, 0x010101de, 0x010101df, 0x010101e1, 0x010101e2, 0x010101e3, 0x010101e4, 0x010101e5, 0x0101026f, 0x7f01004d, 0x7f01004e, 0x7f01004f, 0x7f010050 }; public static final int MenuItem_actionLayout = 14; public static final int MenuItem_actionProviderClass = 16; public static final int MenuItem_actionViewClass = 15; public static final int MenuItem_android_alphabeticShortcut = 9; public static final int MenuItem_android_checkable = 11; public static final int MenuItem_android_checked = 3; public static final int MenuItem_android_enabled = 1; public static final int MenuItem_android_icon = 0; public static final int MenuItem_android_id = 2; public static final int MenuItem_android_menuCategory = 5; public static final int MenuItem_android_numericShortcut = 10; public static final int MenuItem_android_onClick = 12; public static final int MenuItem_android_orderInCategory = 6; public static final int MenuItem_android_title = 7; public static final int MenuItem_android_titleCondensed = 8; public static final int MenuItem_android_visible = 4; public static final int MenuItem_showAsAction = 13; public static final int[] MenuView = { 0x010100ae, 0x0101012c, 0x0101012d, 0x0101012e, 0x0101012f, 0x01010130, 0x01010131, 0x01010438 }; public static final int MenuView_android_headerBackground = 4; public static final int MenuView_android_horizontalDivider = 2; public static final int MenuView_android_itemBackground = 5; public static final int MenuView_android_itemIconDisabledAlpha = 6; public static final int MenuView_android_itemTextAppearance = 1; public static final int MenuView_android_preserveIconSpacing = 7; public static final int MenuView_android_verticalDivider = 3; public static final int MenuView_android_windowAnimationStyle = 0; public static final int[] SearchView = { 0x0101011f, 0x01010220, 0x01010264, 0x7f01005a, 0x7f01005b }; public static final int SearchView_android_imeOptions = 2; public static final int SearchView_android_inputType = 1; public static final int SearchView_android_maxWidth = 0; public static final int SearchView_iconifiedByDefault = 3; public static final int SearchView_queryHint = 4; public static final int[] Spinner = { 0x010100af, 0x01010175, 0x01010176, 0x01010262, 0x010102ac, 0x010102ad, 0x7f010051, 0x7f010052, 0x7f010053, 0x7f010054 }; public static final int Spinner_android_dropDownHorizontalOffset = 4; public static final int Spinner_android_dropDownSelector = 1; public static final int Spinner_android_dropDownVerticalOffset = 5; public static final int Spinner_android_dropDownWidth = 3; public static final int Spinner_android_gravity = 0; public static final int Spinner_android_popupBackground = 2; public static final int Spinner_disableChildrenWhenDisabled = 9; public static final int Spinner_popupPromptView = 8; public static final int Spinner_prompt = 6; public static final int Spinner_spinnerMode = 7; public static final int[] Theme = { 0x7f010047, 0x7f010048, 0x7f010049, 0x7f01004a, 0x7f01004b, 0x7f01004c }; public static final int Theme_actionDropDownStyle = 0; public static final int Theme_dropdownListPreferredItemHeight = 1; public static final int Theme_listChoiceBackgroundIndicator = 5; public static final int Theme_panelMenuListTheme = 4; public static final int Theme_panelMenuListWidth = 3; public static final int Theme_popupMenuStyle = 2; public static final int[] View = { 0x010100da, 0x7f010038, 0x7f010039 }; public static final int View_android_focusable = 0; public static final int View_paddingEnd = 2; public static final int View_paddingStart = 1; } }
asrob-uc3m/rpc_robot_colony
src/android/teleoperation/gen/android/support/v7/appcompat/R.java
Java
lgpl-3.0
41,086
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_creature_npc_droid_crafted_bomarr_monk_spider_droid = object_creature_npc_droid_crafted_shared_bomarr_monk_spider_droid:new { } ObjectTemplates:addTemplate(object_creature_npc_droid_crafted_bomarr_monk_spider_droid, "object/creature/npc/droid/crafted/bomarr_monk_spider_droid.iff")
kidaa/Awakening-Core3
bin/scripts/object/creature/npc/droid/crafted/bomarr_monk_spider_droid.lua
Lua
lgpl-3.0
2,292
/* * ----------------------------------------------------------------- * $Revision: 1.11 $ * $Date: 2011/03/23 23:37:59 $ * ----------------------------------------------------------------- * Programmer(s): Radu Serban @ LLNL * ----------------------------------------------------------------- * Copyright (c) 2002, The Regents of the University of California. * Produced at the Lawrence Livermore National Laboratory. * All rights reserved. * For details, see the LICENSE file. * ----------------------------------------------------------------- * This is the implementation file for the KINBAND linear solver. * ----------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <kinsol/kinsol_band.h> #include "kinsol_direct_impl.h" #include "kinsol_impl.h" #include <sundials/sundials_math.h> /* Constants */ #define ZERO RCONST(0.0) #define ONE RCONST(1.0) #define TWO RCONST(2.0) /* * ================================================================= * PROTOTYPES FOR PRIVATE FUNCTIONS * ================================================================= */ /* KINBAND linit, lsetup, lsolve, and lfree routines */ static int kinBandInit(KINMem kin_mem); static int kinBandSetup(KINMem kin_mem); static int kinBandsolve(KINMem kin_mem, N_Vector x, N_Vector b, realtype *res_norm); static void kinBandFree(KINMem kin_mem); /* * ================================================================= * READIBILITY REPLACEMENTS * ================================================================= */ #define lrw1 (kin_mem->kin_lrw1) #define liw1 (kin_mem->kin_liw1) #define func (kin_mem->kin_func) #define printfl (kin_mem->kin_printfl) #define linit (kin_mem->kin_linit) #define lsetup (kin_mem->kin_lsetup) #define lsolve (kin_mem->kin_lsolve) #define lfree (kin_mem->kin_lfree) #define lmem (kin_mem->kin_lmem) #define inexact_ls (kin_mem->kin_inexact_ls) #define uu (kin_mem->kin_uu) #define fval (kin_mem->kin_fval) #define uscale (kin_mem->kin_uscale) #define fscale (kin_mem->kin_fscale) #define sqrt_relfunc (kin_mem->kin_sqrt_relfunc) #define sJpnorm (kin_mem->kin_sJpnorm) #define sfdotJp (kin_mem->kin_sfdotJp) #define errfp (kin_mem->kin_errfp) #define infofp (kin_mem->kin_infofp) #define setupNonNull (kin_mem->kin_setupNonNull) #define vtemp1 (kin_mem->kin_vtemp1) #define vec_tmpl (kin_mem->kin_vtemp1) #define vtemp2 (kin_mem->kin_vtemp2) #define mtype (kindls_mem->d_type) #define n (kindls_mem->d_n) #define ml (kindls_mem->d_ml) #define mu (kindls_mem->d_mu) #define smu (kindls_mem->d_smu) #define jacDQ (kindls_mem->d_jacDQ) #define bjac (kindls_mem->d_bjac) #define J (kindls_mem->d_J) #define lpivots (kindls_mem->d_lpivots) #define nje (kindls_mem->d_nje) #define nfeDQ (kindls_mem->d_nfeDQ) #define J_data (kindls_mem->d_J_data) #define last_flag (kindls_mem->d_last_flag) /* * ================================================================= * EXPORTED FUNCTIONS * ================================================================= */ /* * ----------------------------------------------------------------- * KINBand * ----------------------------------------------------------------- * This routine initializes the memory record and sets various function * fields specific to the band linear solver module. KINBand first calls * the existing lfree routine if this is not NULL. It then sets the * cv_linit, cv_lsetup, cv_lsolve, and cv_lfree fields in (*cvode_mem) * to be kinBandInit, kinBandSetup, kinBandsolve, and kinBandFree, * respectively. It allocates memory for a structure of type * KINDlsMemRec and sets the cv_lmem field in (*cvode_mem) to the * address of this structure. It sets setupNonNull in (*cvode_mem) to be * TRUE, b_mu to be mupper, b_ml to be mlower, and the bjac field to be * kinDlsBandDQJac. * Finally, it allocates memory for M, savedJ, and pivot. * * NOTE: The band linear solver assumes a serial implementation * of the NVECTOR package. Therefore, KINBand will first * test for compatible a compatible N_Vector internal * representation by checking that the function * N_VGetArrayPointer exists. * ----------------------------------------------------------------- */ int KINBand(void *kinmem, long int N, long int mupper, long int mlower) { KINMem kin_mem; KINDlsMem kindls_mem; /* Return immediately if kinmem is NULL */ if (kinmem == NULL) { KINProcessError(NULL, KINDLS_MEM_NULL, "KINBAND", "KINBand", MSGD_KINMEM_NULL); return(KINDLS_MEM_NULL); } kin_mem = (KINMem) kinmem; /* Test if the NVECTOR package is compatible with the BAND solver */ if (vec_tmpl->ops->nvgetarraypointer == NULL) { KINProcessError(kin_mem, KINDLS_ILL_INPUT, "KINBAND", "KINBand", MSGD_BAD_NVECTOR); return(KINDLS_ILL_INPUT); } if (lfree != NULL) lfree(kin_mem); /* Set four main function fields in kin_mem */ linit = kinBandInit; lsetup = kinBandSetup; lsolve = kinBandsolve; lfree = kinBandFree; /* Get memory for KINDlsMemRec */ kindls_mem = NULL; kindls_mem = (KINDlsMem) malloc(sizeof(struct KINDlsMemRec)); if (kindls_mem == NULL) { KINProcessError(kin_mem, KINDLS_MEM_FAIL, "KINBAND", "KINBand", MSGD_MEM_FAIL); return(KINDLS_MEM_FAIL); } /* Set matrix type */ mtype = SUNDIALS_BAND; /* Set default Jacobian routine and Jacobian data */ jacDQ = TRUE; bjac = NULL; J_data = NULL; last_flag = KINDLS_SUCCESS; setupNonNull = TRUE; /* Load problem dimension */ n = N; /* Load half-bandwiths in kindls_mem */ ml = mlower; mu = mupper; /* Test ml and mu for legality */ if ((ml < 0) || (mu < 0) || (ml >= N) || (mu >= N)) { KINProcessError(kin_mem, KINDLS_MEM_FAIL, "KINBAND", "KINBand", MSGD_MEM_FAIL); free(kindls_mem); kindls_mem = NULL; return(KINDLS_ILL_INPUT); } /* Set extended upper half-bandwith for M (required for pivoting) */ smu = MIN(N-1, mu + ml); /* Allocate memory for J and pivot array */ J = NULL; J = NewBandMat(N, mu, ml, smu); if (J == NULL) { KINProcessError(kin_mem, KINDLS_MEM_FAIL, "KINBAND", "KINBand", MSGD_MEM_FAIL); free(kindls_mem); kindls_mem = NULL; return(KINDLS_MEM_FAIL); } lpivots = NULL; lpivots = NewLintArray(N); if (lpivots == NULL) { KINProcessError(kin_mem, KINDLS_MEM_FAIL, "KINBAND", "KINBand", MSGD_MEM_FAIL); DestroyMat(J); free(kindls_mem); kindls_mem = NULL; return(KINDLS_MEM_FAIL); } /* This is a direct linear solver */ inexact_ls = FALSE; /* Attach linear solver memory to integrator memory */ lmem = kindls_mem; return(KINDLS_SUCCESS); } /* * ================================================================= * PRIVATE FUNCTIONS * ================================================================= */ /* * ----------------------------------------------------------------- * kinBandInit * ----------------------------------------------------------------- * This routine does remaining initializations specific to the band * linear solver. * ----------------------------------------------------------------- */ static int kinBandInit(KINMem kin_mem) { KINDlsMem kindls_mem; kindls_mem = (KINDlsMem) lmem; nje = 0; nfeDQ = 0; if (jacDQ) { bjac = kinDlsBandDQJac; J_data = kin_mem; } else { J_data = kin_mem->kin_user_data; } last_flag = KINDLS_SUCCESS; return(0); } /* * ----------------------------------------------------------------- * kinBandSetup * ----------------------------------------------------------------- * This routine does the setup operations for the band linear solver. * It makes a decision whether or not to call the Jacobian evaluation * routine based on various state variables, and if not it uses the * saved copy. In any case, it constructs the Newton matrix * M = I - gamma*J, updates counters, and calls the band LU * factorization routine. * ----------------------------------------------------------------- */ static int kinBandSetup(KINMem kin_mem) { KINDlsMem kindls_mem; int retval; long int ier; kindls_mem = (KINDlsMem) lmem; nje++; SetToZero(J); retval = bjac(n, mu, ml, uu, fval, J, J_data, vtemp1, vtemp2); if (retval != 0) { last_flag = -1; return(-1); } /* Do LU factorization of J */ ier = BandGBTRF(J, lpivots); /* Return 0 if the LU was complete; otherwise return -1 */ last_flag = ier; if (ier > 0) return(-1); return(0); } /* * ----------------------------------------------------------------- * kinBandsolve * ----------------------------------------------------------------- * This routine handles the solve operation for the band linear solver * by calling the band backsolve routine. The return value is 0. * ----------------------------------------------------------------- */ static int kinBandsolve(KINMem kin_mem, N_Vector x, N_Vector b, realtype *res_norm) { KINDlsMem kindls_mem; realtype *xd; kindls_mem = (KINDlsMem) lmem; /* Copy the right-hand side into x */ N_VScale(ONE, b, x); xd = N_VGetArrayPointer(x); /* Back-solve and get solution in x */ BandGBTRS(J, lpivots, xd); /* Compute the terms Jpnorm and sfdotJp for use in the global strategy routines and in KINForcingTerm. Both of these terms are subsequently corrected if the step is reduced by constraints or the line search. sJpnorm is the norm of the scaled product (scaled by fscale) of the current Jacobian matrix J and the step vector p. sfdotJp is the dot product of the scaled f vector and the scaled vector J*p, where the scaling uses fscale. */ sJpnorm = N_VWL2Norm(b,fscale); N_VProd(b, fscale, b); N_VProd(b, fscale, b); sfdotJp = N_VDotProd(fval, b); last_flag = KINDLS_SUCCESS; return(0); } /* * ----------------------------------------------------------------- * kinBandFree * ----------------------------------------------------------------- * This routine frees memory specific to the band linear solver. * ----------------------------------------------------------------- */ static void kinBandFree(KINMem kin_mem) { KINDlsMem kindls_mem; kindls_mem = (KINDlsMem) lmem; DestroyMat(J); DestroyArray(lpivots); free(kindls_mem); kindls_mem = NULL; }
CFDEMproject/ParScale-PUBLIC
thirdParty/sundials-2.5.0/src/_kinsol/kinsol_band.c
C
lgpl-3.0
10,704
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="it"> <head> <!-- Generated by javadoc (version 1.7.0_04) on Mon Feb 04 16:14:51 CET 2013 --> <title>I-Index</title> <meta name="date" content="2013-02-04"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="I-Index"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../sofia_kp/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../sofia_kp/package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-5.html">Prev Letter</a></li> <li><a href="index-7.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-6.html" target="_top">Frames</a></li> <li><a href="index-6.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">D</a>&nbsp;<a href="index-3.html">E</a>&nbsp;<a href="index-4.html">G</a>&nbsp;<a href="index-5.html">H</a>&nbsp;<a href="index-6.html">I</a>&nbsp;<a href="index-7.html">J</a>&nbsp;<a href="index-8.html">K</a>&nbsp;<a href="index-9.html">L</a>&nbsp;<a href="index-10.html">M</a>&nbsp;<a href="index-11.html">N</a>&nbsp;<a href="index-12.html">P</a>&nbsp;<a href="index-13.html">Q</a>&nbsp;<a href="index-14.html">R</a>&nbsp;<a href="index-15.html">S</a>&nbsp;<a href="index-16.html">T</a>&nbsp;<a href="index-17.html">U</a>&nbsp;<a href="index-18.html">W</a>&nbsp;<a href="index-19.html">X</a>&nbsp;<a name="_I_"> <!-- --> </a> <h2 class="title">I</h2> <dl> <dt><a href="../sofia_kp/iKPIC.html" title="interface in sofia_kp"><span class="strong">iKPIC</span></a> - Interface in <a href="../sofia_kp/package-summary.html">sofia_kp</a></dt> <dd>&nbsp;</dd> <dt><a href="../sofia_kp/iKPIC_subscribeHandler.html" title="interface in sofia_kp"><span class="strong">iKPIC_subscribeHandler</span></a> - Interface in <a href="../sofia_kp/package-summary.html">sofia_kp</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_sparql_response.html#init_from_sparql_response_string(java.lang.String)">init_from_sparql_response_string(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_sparql_response.html" title="class in sofia_kp">SSAP_sparql_response</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../sofia_kp/iKPIC.html#insert(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)">insert(String, String, String, String, String)</a></span> - Method in interface sofia_kp.<a href="../sofia_kp/iKPIC.html" title="interface in sofia_kp">iKPIC</a></dt> <dd> <div class="block">Perform the INSERT procedure Check the error state with the functions: getErrMess, getErrID</div> </dd> <dt><span class="strong"><a href="../sofia_kp/iKPIC.html#insert(java.util.Vector)">insert(Vector&lt;Vector&lt;String&gt;&gt;)</a></span> - Method in interface sofia_kp.<a href="../sofia_kp/iKPIC.html" title="interface in sofia_kp">iKPIC</a></dt> <dd> <div class="block">Perform the INSERT procedure Check the error state with the functions: getErrMess, getErrID</div> </dd> <dt><span class="strong"><a href="../sofia_kp/KPICore.html#insert(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)">insert(String, String, String, String, String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/KPICore.html" title="class in sofia_kp">KPICore</a></dt> <dd> <div class="block">Perform the INSERT procedure Check the error state with the functions: getErrMess, getErrID</div> </dd> <dt><span class="strong"><a href="../sofia_kp/KPICore.html#insert(java.util.Vector)">insert(Vector&lt;Vector&lt;String&gt;&gt;)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/KPICore.html" title="class in sofia_kp">KPICore</a></dt> <dd> <div class="block">Perform the INSERT procedure Check the error state with the functions: getErrMess, getErrID</div> </dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#insert(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)">insert(String, String, String, String, String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Make the INSERT SSAP message</div> </dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#insert(java.util.Vector)">insert(Vector&lt;Vector&lt;String&gt;&gt;)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Make the INSERT SSAP message</div> </dd> <dt><span class="strong"><a href="../sofia_kp/KPICore.html#insert_rdf_xml(java.lang.String)">insert_rdf_xml(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/KPICore.html" title="class in sofia_kp">KPICore</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#insert_rdf_xml(java.lang.String)">insert_rdf_xml(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Make the SSAP message to be sent to the SIB to perform RDF/XML insert in SIBs supporting it</div> </dd> <dt><span class="strong"><a href="../sofia_kp/iKPIC.html#insertProtection(java.lang.String, java.util.Vector)">insertProtection(String, Vector&lt;String&gt;)</a></span> - Method in interface sofia_kp.<a href="../sofia_kp/iKPIC.html" title="interface in sofia_kp">iKPIC</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../sofia_kp/KPICore.html#insertProtection(java.lang.String, java.util.Vector)">insertProtection(String, Vector&lt;String&gt;)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/KPICore.html" title="class in sofia_kp">KPICore</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#isInsertConfirmed(java.lang.String)">isInsertConfirmed(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Looking for the Insert confirmation in the last XML message received from the SIB</div> </dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#isJoinConfirmed(java.lang.String)">isJoinConfirmed(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Looking for the join confirmation in the last XML message received from the SIB</div> </dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#isLeaveConfirmed(java.lang.String)">isLeaveConfirmed(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Looking for the leave confirmation in the last XML message received from the SIB</div> </dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#isQueryConfirmed(java.lang.String)">isQueryConfirmed(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Looking for the Query confirmation in the last XML message received from the SIB</div> </dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_sparql_response.html#isQueryTypeConstruct()">isQueryTypeConstruct()</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_sparql_response.html" title="class in sofia_kp">SSAP_sparql_response</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_sparql_response.html#isQueryTypeSelect()">isQueryTypeSelect()</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_sparql_response.html" title="class in sofia_kp">SSAP_sparql_response</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#isRDFNotification(java.lang.String)">isRDFNotification(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Returns true if the received notification is relative to an RDF-M3 subscription</div> </dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#isRemoveConfirmed(java.lang.String)">isRemoveConfirmed(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Looking for the Remove confirmation in the last XML message received from the SIB</div> </dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#isSubscriptionConfirmed(java.lang.String)">isSubscriptionConfirmed(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Looking for the Subscription confirmation in the last XML message received from the SIB</div> </dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#isUnSubscriptionConfirmed(java.lang.String)">isUnSubscriptionConfirmed(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Looking for the UnSubscription confirmation in the last XML message received from the SIB</div> </dd> <dt><span class="strong"><a href="../sofia_kp/SSAP_XMLTools.html#isUpdateConfirmed(java.lang.String)">isUpdateConfirmed(String)</a></span> - Method in class sofia_kp.<a href="../sofia_kp/SSAP_XMLTools.html" title="class in sofia_kp">SSAP_XMLTools</a></dt> <dd> <div class="block">Looking for the Update confirmation in the last XML message received from the SIB</div> </dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">D</a>&nbsp;<a href="index-3.html">E</a>&nbsp;<a href="index-4.html">G</a>&nbsp;<a href="index-5.html">H</a>&nbsp;<a href="index-6.html">I</a>&nbsp;<a href="index-7.html">J</a>&nbsp;<a href="index-8.html">K</a>&nbsp;<a href="index-9.html">L</a>&nbsp;<a href="index-10.html">M</a>&nbsp;<a href="index-11.html">N</a>&nbsp;<a href="index-12.html">P</a>&nbsp;<a href="index-13.html">Q</a>&nbsp;<a href="index-14.html">R</a>&nbsp;<a href="index-15.html">S</a>&nbsp;<a href="index-16.html">T</a>&nbsp;<a href="index-17.html">U</a>&nbsp;<a href="index-18.html">W</a>&nbsp;<a href="index-19.html">X</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../sofia_kp/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../sofia_kp/package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-5.html">Prev Letter</a></li> <li><a href="index-7.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-6.html" target="_top">Frames</a></li> <li><a href="index-6.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
desmovalvo/virtualsib
tools/Sofia_KPICore_v6.3_(SRC)_+SPARQL/doc/index-files/index-6.html
HTML
lgpl-3.0
13,249
// Authors: // Francis Fisher (frankie@terrorise.me.uk) // // (C) Francis Fisher 2013 // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Drawing; namespace System.Windows.Forms.DataVisualization.Charting { public class LegendItem : ChartNamedElement { public LegendItem () { Cells = new LegendCellCollection (); } public LegendItem (string name,Color color,string image) { this.Name = name; this.Color = color; this.Image = image; Cells = new LegendCellCollection (); } public GradientStyle BackGradientStyle { get; set; } public ChartHatchStyle BackHatchStyle { get; set; } public Color BackImageTransparentColor { get; set; } public Color BackSecondaryColor { get; set; } public Color BorderColor { get; set; } public ChartDashStyle BorderDashStyle { get; set; } public int BorderWidth { get; set; } public LegendCellCollection Cells { get; private set; } public Color Color { get; set; } public bool Enabled { get; set; } public string Image { get; set; } public LegendImageStyle ImageStyle { get; set; } public Legend Legend { get; private set;} public Color MarkerBorderColor { get; set; } public int MarkerBorderWidth { get; set; } public Color MarkerColor { get; set; } public string MarkerImage { get; set; } public Color MarkerImageTransparentColor { get; set; } public int MarkerSize { get; set; } public MarkerStyle MarkerStyle { get; set; } public override string Name { get; set; } public Color SeparatorColor { get; set; } public LegendSeparatorStyle SeparatorType { get; set; } public string SeriesName { get; set; } public int SeriesPointIndex { get; set; } public Color ShadowColor { get; set; } public int ShadowOffset { get; set; } public string ToolTip { get; set; } } }
edwinspire/VSharp
class/System.Windows.Forms.DataVisualization/System.Windows.Forms.DataVisualization.Charting/LegendItem.cs
C#
lgpl-3.0
2,822
package org.molgenis.data.validation.meta; import org.molgenis.data.AbstractRepositoryDecorator; import org.molgenis.data.Repository; import org.molgenis.data.meta.model.Tag; import java.util.stream.Stream; import static java.util.Objects.requireNonNull; /** * Validates {@link Tag tags} before adding or updating the delegated repository */ public class TagRepositoryValidationDecorator extends AbstractRepositoryDecorator<Tag> { private final Repository<Tag> decoratedRepo; private final TagValidator tagValidator; public TagRepositoryValidationDecorator(Repository<Tag> decoratedRepo, TagValidator tagValidator) { this.decoratedRepo = requireNonNull(decoratedRepo); this.tagValidator = requireNonNull(tagValidator); } @Override protected Repository<Tag> delegate() { return decoratedRepo; } @Override public void update(Tag tag) { tagValidator.validate(tag); super.update(tag); } @Override public void add(Tag tag) { tagValidator.validate(tag); super.add(tag); } @Override public Integer add(Stream<Tag> tagStream) { return decoratedRepo.add(tagStream.filter(tag -> { tagValidator.validate(tag); return true; })); } @Override public void update(Stream<Tag> tagStream) { decoratedRepo.update(tagStream.filter(entityType -> { tagValidator.validate(entityType); return true; })); } }
jjettenn/molgenis
molgenis-data-validation/src/main/java/org/molgenis/data/validation/meta/TagRepositoryValidationDecorator.java
Java
lgpl-3.0
1,359
package org.molgenis.data.meta.system; import org.molgenis.data.meta.SystemPackage; import org.molgenis.data.meta.model.Package; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; /** * Registry containing all {@link SystemPackage}. */ @Component public class SystemPackageRegistry { private final Logger LOG = LoggerFactory.getLogger(SystemPackageRegistry.class); // note: a list instead of map is used since system packages might not be initialized when added to the registry private final List<SystemPackage> systemPackages; public SystemPackageRegistry() { systemPackages = new ArrayList<>(32); } void addSystemPackage(SystemPackage systemPackage) { LOG.trace("Registering system package [{}] ...", systemPackage.getId()); systemPackages.add(systemPackage); } public boolean containsPackage(Package package_) { for (SystemPackage systemPackage : systemPackages) { if (systemPackage.getId().equals(package_.getId())) return true; } return false; } Stream<SystemPackage> getSystemPackages() { return systemPackages.stream(); } }
djvanenckevort/molgenis
molgenis-data/src/main/java/org/molgenis/data/meta/system/SystemPackageRegistry.java
Java
lgpl-3.0
1,213
// -*- Mode:C++ -*- /************************************************************************\ * * * This file is part of Avango. * * * * Copyright 1997 - 2008 Fraunhofer-Gesellschaft zur Foerderung der * * angewandten Forschung (FhG), Munich, Germany. * * * * Avango is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, version 3. * * * * Avango 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 Lesser General Public * * License along with Avango. If not, see <http://www.gnu.org/licenses/>. * * * * Avango is a trademark owned by FhG. * * * \************************************************************************/ #include <avango/daemon/LinuxEvent.h> namespace { static const av::daemon::LinuxEvent sEventMap; } av::daemon::LinuxEvent::LinuxEvent() { // own definitions insert(std::make_pair("STATION_BUTTON", 0x00)); insert(std::make_pair("STATION_VALUE", 0x01)); insert(std::make_pair("STATION_LED", 0x02)); // definitions from /usr/include/linux/input.h insert(std::make_pair("EV_SYN", 0x00)); insert(std::make_pair("EV_KEY", 0x01)); insert(std::make_pair("EV_REL", 0x02)); insert(std::make_pair("EV_ABS", 0x03)); insert(std::make_pair("EV_MSC", 0x04)); insert(std::make_pair("EV_SW", 0x05)); insert(std::make_pair("EV_LED", 0x11)); insert(std::make_pair("EV_SND", 0x12)); insert(std::make_pair("EV_REP", 0x14)); insert(std::make_pair("EV_FF", 0x15)); insert(std::make_pair("EV_PWR", 0x16)); insert(std::make_pair("EV_FF_STATUS", 0x17)); insert(std::make_pair("EV_MAX", 0x1f)); insert(std::make_pair("SYN_REPORT", 0)); insert(std::make_pair("SYN_CONFIG", 1)); insert(std::make_pair("KEY_RESERVED", 0)); insert(std::make_pair("KEY_ESC", 1)); insert(std::make_pair("KEY_1", 2)); insert(std::make_pair("KEY_2", 3)); insert(std::make_pair("KEY_3", 4)); insert(std::make_pair("KEY_4", 5)); insert(std::make_pair("KEY_5", 6)); insert(std::make_pair("KEY_6", 7)); insert(std::make_pair("KEY_7", 8)); insert(std::make_pair("KEY_8", 9)); insert(std::make_pair("KEY_9", 10)); insert(std::make_pair("KEY_0", 11)); insert(std::make_pair("KEY_MINUS", 12)); insert(std::make_pair("KEY_EQUAL", 13)); insert(std::make_pair("KEY_BACKSPACE", 14)); insert(std::make_pair("KEY_TAB", 15)); insert(std::make_pair("KEY_Q", 16)); insert(std::make_pair("KEY_W", 17)); insert(std::make_pair("KEY_E", 18)); insert(std::make_pair("KEY_R", 19)); insert(std::make_pair("KEY_T", 20)); insert(std::make_pair("KEY_Y", 21)); insert(std::make_pair("KEY_U", 22)); insert(std::make_pair("KEY_I", 23)); insert(std::make_pair("KEY_O", 24)); insert(std::make_pair("KEY_P", 25)); insert(std::make_pair("KEY_LEFTBRACE", 26)); insert(std::make_pair("KEY_RIGHTBRACE", 27)); insert(std::make_pair("KEY_ENTER", 28)); insert(std::make_pair("KEY_LEFTCTRL", 29)); insert(std::make_pair("KEY_A", 30)); insert(std::make_pair("KEY_S", 31)); insert(std::make_pair("KEY_D", 32)); insert(std::make_pair("KEY_F", 33)); insert(std::make_pair("KEY_G", 34)); insert(std::make_pair("KEY_H", 35)); insert(std::make_pair("KEY_J", 36)); insert(std::make_pair("KEY_K", 37)); insert(std::make_pair("KEY_L", 38)); insert(std::make_pair("KEY_SEMICOLON", 39)); insert(std::make_pair("KEY_APOSTROPHE", 40)); insert(std::make_pair("KEY_GRAVE", 41)); insert(std::make_pair("KEY_LEFTSHIFT", 42)); insert(std::make_pair("KEY_BACKSLASH", 43)); insert(std::make_pair("KEY_Z", 44)); insert(std::make_pair("KEY_X", 45)); insert(std::make_pair("KEY_C", 46)); insert(std::make_pair("KEY_V", 47)); insert(std::make_pair("KEY_B", 48)); insert(std::make_pair("KEY_N", 49)); insert(std::make_pair("KEY_M", 50)); insert(std::make_pair("KEY_COMMA", 51)); insert(std::make_pair("KEY_DOT", 52)); insert(std::make_pair("KEY_SLASH", 53)); insert(std::make_pair("KEY_RIGHTSHIFT", 54)); insert(std::make_pair("KEY_KPASTERISK", 55)); insert(std::make_pair("KEY_LEFTALT", 56)); insert(std::make_pair("KEY_SPACE", 57)); insert(std::make_pair("KEY_CAPSLOCK", 58)); insert(std::make_pair("KEY_F1", 59)); insert(std::make_pair("KEY_F2", 60)); insert(std::make_pair("KEY_F3", 61)); insert(std::make_pair("KEY_F4", 62)); insert(std::make_pair("KEY_F5", 63)); insert(std::make_pair("KEY_F6", 64)); insert(std::make_pair("KEY_F7", 65)); insert(std::make_pair("KEY_F8", 66)); insert(std::make_pair("KEY_F9", 67)); insert(std::make_pair("KEY_F10", 68)); insert(std::make_pair("KEY_NUMLOCK", 69)); insert(std::make_pair("KEY_SCROLLLOCK", 70)); insert(std::make_pair("KEY_KP7", 71)); insert(std::make_pair("KEY_KP8", 72)); insert(std::make_pair("KEY_KP9", 73)); insert(std::make_pair("KEY_KPMINUS", 74)); insert(std::make_pair("KEY_KP4", 75)); insert(std::make_pair("KEY_KP5", 76)); insert(std::make_pair("KEY_KP6", 77)); insert(std::make_pair("KEY_KPPLUS", 78)); insert(std::make_pair("KEY_KP1", 79)); insert(std::make_pair("KEY_KP2", 80)); insert(std::make_pair("KEY_KP3", 81)); insert(std::make_pair("KEY_KP0", 82)); insert(std::make_pair("KEY_KPDOT", 83)); insert(std::make_pair("KEY_ZENKAKUHANKAKU", 85)); insert(std::make_pair("KEY_102ND", 86)); insert(std::make_pair("KEY_F11", 87)); insert(std::make_pair("KEY_F12", 88)); insert(std::make_pair("KEY_RO", 89)); insert(std::make_pair("KEY_KATAKANA", 90)); insert(std::make_pair("KEY_HIRAGANA", 91)); insert(std::make_pair("KEY_HENKAN", 92)); insert(std::make_pair("KEY_KATAKANAHIRAGANA", 93)); insert(std::make_pair("KEY_MUHENKAN", 94)); insert(std::make_pair("KEY_KPJPCOMMA", 95)); insert(std::make_pair("KEY_KPENTER", 96)); insert(std::make_pair("KEY_RIGHTCTRL", 97)); insert(std::make_pair("KEY_KPSLASH", 98)); insert(std::make_pair("KEY_SYSRQ", 99)); insert(std::make_pair("KEY_RIGHTALT", 100)); insert(std::make_pair("KEY_LINEFEED", 101)); insert(std::make_pair("KEY_HOME", 102)); insert(std::make_pair("KEY_UP", 103)); insert(std::make_pair("KEY_PAGEUP", 104)); insert(std::make_pair("KEY_LEFT", 105)); insert(std::make_pair("KEY_RIGHT", 106)); insert(std::make_pair("KEY_END", 107)); insert(std::make_pair("KEY_DOWN", 108)); insert(std::make_pair("KEY_PAGEDOWN", 109)); insert(std::make_pair("KEY_INSERT", 110)); insert(std::make_pair("KEY_DELETE", 111)); insert(std::make_pair("KEY_MACRO", 112)); insert(std::make_pair("KEY_MUTE", 113)); insert(std::make_pair("KEY_VOLUMEDOWN", 114)); insert(std::make_pair("KEY_VOLUMEUP", 115)); insert(std::make_pair("KEY_POWER", 116)); insert(std::make_pair("KEY_KPEQUAL", 117)); insert(std::make_pair("KEY_KPPLUSMINUS", 118)); insert(std::make_pair("KEY_PAUSE", 119)); insert(std::make_pair("KEY_KPCOMMA", 121)); insert(std::make_pair("KEY_HANGEUL", 122)); //insert(std::make_pair("KEY_HANGUEL", KEY_HANGEUL)); insert(std::make_pair("KEY_HANJA", 123)); insert(std::make_pair("KEY_YEN", 124)); insert(std::make_pair("KEY_LEFTMETA", 125)); insert(std::make_pair("KEY_RIGHTMETA", 126)); insert(std::make_pair("KEY_COMPOSE", 127)); insert(std::make_pair("KEY_STOP", 128)); insert(std::make_pair("KEY_AGAIN", 129)); insert(std::make_pair("KEY_PROPS", 130)); insert(std::make_pair("KEY_UNDO", 131)); insert(std::make_pair("KEY_FRONT", 132)); insert(std::make_pair("KEY_COPY", 133)); insert(std::make_pair("KEY_OPEN", 134)); insert(std::make_pair("KEY_PASTE", 135)); insert(std::make_pair("KEY_FIND", 136)); insert(std::make_pair("KEY_CUT", 137)); insert(std::make_pair("KEY_HELP", 138)); insert(std::make_pair("KEY_MENU", 139)); insert(std::make_pair("KEY_CALC", 140)); insert(std::make_pair("KEY_SETUP", 141)); insert(std::make_pair("KEY_SLEEP", 142)); insert(std::make_pair("KEY_WAKEUP", 143)); insert(std::make_pair("KEY_FILE", 144)); insert(std::make_pair("KEY_SENDFILE", 145)); insert(std::make_pair("KEY_DELETEFILE", 146)); insert(std::make_pair("KEY_XFER", 147)); insert(std::make_pair("KEY_PROG1", 148)); insert(std::make_pair("KEY_PROG2", 149)); insert(std::make_pair("KEY_WWW", 150)); insert(std::make_pair("KEY_MSDOS", 151)); insert(std::make_pair("KEY_COFFEE", 152)); insert(std::make_pair("KEY_DIRECTION", 153)); insert(std::make_pair("KEY_CYCLEWINDOWS", 154)); insert(std::make_pair("KEY_MAIL", 155)); insert(std::make_pair("KEY_BOOKMARKS", 156)); insert(std::make_pair("KEY_COMPUTER", 157)); insert(std::make_pair("KEY_BACK", 158)); insert(std::make_pair("KEY_FORWARD", 159)); insert(std::make_pair("KEY_CLOSECD", 160)); insert(std::make_pair("KEY_EJECTCD", 161)); insert(std::make_pair("KEY_EJECTCLOSECD", 162)); insert(std::make_pair("KEY_NEXTSONG", 163)); insert(std::make_pair("KEY_PLAYPAUSE", 164)); insert(std::make_pair("KEY_PREVIOUSSONG", 165)); insert(std::make_pair("KEY_STOPCD", 166)); insert(std::make_pair("KEY_RECORD", 167)); insert(std::make_pair("KEY_REWIND", 168)); insert(std::make_pair("KEY_PHONE", 169)); insert(std::make_pair("KEY_ISO", 170)); insert(std::make_pair("KEY_CONFIG", 171)); insert(std::make_pair("KEY_HOMEPAGE", 172)); insert(std::make_pair("KEY_REFRESH", 173)); insert(std::make_pair("KEY_EXIT", 174)); insert(std::make_pair("KEY_MOVE", 175)); insert(std::make_pair("KEY_EDIT", 176)); insert(std::make_pair("KEY_SCROLLUP", 177)); insert(std::make_pair("KEY_SCROLLDOWN", 178)); insert(std::make_pair("KEY_KPLEFTPAREN", 179)); insert(std::make_pair("KEY_KPRIGHTPAREN", 180)); insert(std::make_pair("KEY_NEW", 181)); insert(std::make_pair("KEY_REDO", 182)); insert(std::make_pair("KEY_F13", 183)); insert(std::make_pair("KEY_F14", 184)); insert(std::make_pair("KEY_F15", 185)); insert(std::make_pair("KEY_F16", 186)); insert(std::make_pair("KEY_F17", 187)); insert(std::make_pair("KEY_F18", 188)); insert(std::make_pair("KEY_F19", 189)); insert(std::make_pair("KEY_F20", 190)); insert(std::make_pair("KEY_F21", 191)); insert(std::make_pair("KEY_F22", 192)); insert(std::make_pair("KEY_F23", 193)); insert(std::make_pair("KEY_F24", 194)); insert(std::make_pair("KEY_PLAYCD", 200)); insert(std::make_pair("KEY_PAUSECD", 201)); insert(std::make_pair("KEY_PROG3", 202)); insert(std::make_pair("KEY_PROG4", 203)); insert(std::make_pair("KEY_SUSPEND", 205)); insert(std::make_pair("KEY_CLOSE", 206)); insert(std::make_pair("KEY_PLAY", 207)); insert(std::make_pair("KEY_FASTFORWARD", 208)); insert(std::make_pair("KEY_BASSBOOST", 209)); insert(std::make_pair("KEY_PRINT", 210)); insert(std::make_pair("KEY_HP", 211)); insert(std::make_pair("KEY_CAMERA", 212)); insert(std::make_pair("KEY_SOUND", 213)); insert(std::make_pair("KEY_QUESTION", 214)); insert(std::make_pair("KEY_EMAIL", 215)); insert(std::make_pair("KEY_CHAT", 216)); insert(std::make_pair("KEY_SEARCH", 217)); insert(std::make_pair("KEY_CONNECT", 218)); insert(std::make_pair("KEY_FINANCE", 219)); insert(std::make_pair("KEY_SPORT", 220)); insert(std::make_pair("KEY_SHOP", 221)); insert(std::make_pair("KEY_ALTERASE", 222)); insert(std::make_pair("KEY_CANCEL", 223)); insert(std::make_pair("KEY_BRIGHTNESSDOWN", 224)); insert(std::make_pair("KEY_BRIGHTNESSUP", 225)); insert(std::make_pair("KEY_MEDIA", 226)); insert(std::make_pair("KEY_SWITCHVIDEOMODE", 227)); insert(std::make_pair("KEY_KBDILLUMTOGGLE", 228)); insert(std::make_pair("KEY_KBDILLUMDOWN", 229)); insert(std::make_pair("KEY_KBDILLUMUP", 230)); insert(std::make_pair("KEY_SEND", 231)); insert(std::make_pair("KEY_REPLY", 232)); insert(std::make_pair("KEY_FORWARDMAIL", 233)); insert(std::make_pair("KEY_SAVE", 234)); insert(std::make_pair("KEY_DOCUMENTS", 235)); insert(std::make_pair("KEY_BATTERY", 236)); insert(std::make_pair("KEY_UNKNOWN", 240)); insert(std::make_pair("BTN_MISC", 0x100)); insert(std::make_pair("BTN_0", 0x100)); insert(std::make_pair("BTN_1", 0x101)); insert(std::make_pair("BTN_2", 0x102)); insert(std::make_pair("BTN_3", 0x103)); insert(std::make_pair("BTN_4", 0x104)); insert(std::make_pair("BTN_5", 0x105)); insert(std::make_pair("BTN_6", 0x106)); insert(std::make_pair("BTN_7", 0x107)); insert(std::make_pair("BTN_8", 0x108)); insert(std::make_pair("BTN_9", 0x109)); insert(std::make_pair("BTN_MOUSE", 0x110)); insert(std::make_pair("BTN_LEFT", 0x110)); insert(std::make_pair("BTN_RIGHT", 0x111)); insert(std::make_pair("BTN_MIDDLE", 0x112)); insert(std::make_pair("BTN_SIDE", 0x113)); insert(std::make_pair("BTN_EXTRA", 0x114)); insert(std::make_pair("BTN_FORWARD", 0x115)); insert(std::make_pair("BTN_BACK", 0x116)); insert(std::make_pair("BTN_TASK", 0x117)); insert(std::make_pair("BTN_JOYSTICK", 0x120)); insert(std::make_pair("BTN_TRIGGER", 0x120)); insert(std::make_pair("BTN_THUMB", 0x121)); insert(std::make_pair("BTN_THUMB2", 0x122)); insert(std::make_pair("BTN_TOP", 0x123)); insert(std::make_pair("BTN_TOP2", 0x124)); insert(std::make_pair("BTN_PINKIE", 0x125)); insert(std::make_pair("BTN_BASE", 0x126)); insert(std::make_pair("BTN_BASE2", 0x127)); insert(std::make_pair("BTN_BASE3", 0x128)); insert(std::make_pair("BTN_BASE4", 0x129)); insert(std::make_pair("BTN_BASE5", 0x12a)); insert(std::make_pair("BTN_BASE6", 0x12b)); insert(std::make_pair("BTN_DEAD", 0x12f)); insert(std::make_pair("BTN_GAMEPAD", 0x130)); insert(std::make_pair("BTN_A", 0x130)); insert(std::make_pair("BTN_B", 0x131)); insert(std::make_pair("BTN_C", 0x132)); insert(std::make_pair("BTN_X", 0x133)); insert(std::make_pair("BTN_Y", 0x134)); insert(std::make_pair("BTN_Z", 0x135)); insert(std::make_pair("BTN_TL", 0x136)); insert(std::make_pair("BTN_TR", 0x137)); insert(std::make_pair("BTN_TL2", 0x138)); insert(std::make_pair("BTN_TR2", 0x139)); insert(std::make_pair("BTN_SELECT", 0x13a)); insert(std::make_pair("BTN_START", 0x13b)); insert(std::make_pair("BTN_MODE", 0x13c)); insert(std::make_pair("BTN_THUMBL", 0x13d)); insert(std::make_pair("BTN_THUMBR", 0x13e)); insert(std::make_pair("BTN_DIGI", 0x140)); insert(std::make_pair("BTN_TOOL_PEN", 0x140)); insert(std::make_pair("BTN_TOOL_RUBBER", 0x141)); insert(std::make_pair("BTN_TOOL_BRUSH", 0x142)); insert(std::make_pair("BTN_TOOL_PENCIL", 0x143)); insert(std::make_pair("BTN_TOOL_AIRBRUSH", 0x144)); insert(std::make_pair("BTN_TOOL_FINGER", 0x145)); insert(std::make_pair("BTN_TOOL_MOUSE", 0x146)); insert(std::make_pair("BTN_TOOL_LENS", 0x147)); insert(std::make_pair("BTN_TOUCH", 0x14a)); insert(std::make_pair("BTN_STYLUS", 0x14b)); insert(std::make_pair("BTN_STYLUS2", 0x14c)); insert(std::make_pair("BTN_TOOL_DOUBLETAP", 0x14d)); insert(std::make_pair("BTN_TOOL_TRIPLETAP", 0x14e)); insert(std::make_pair("BTN_WHEEL", 0x150)); insert(std::make_pair("BTN_GEAR_DOWN", 0x150)); insert(std::make_pair("BTN_GEAR_UP", 0x151)); insert(std::make_pair("KEY_OK", 0x160)); insert(std::make_pair("KEY_SELECT", 0x161)); insert(std::make_pair("KEY_GOTO", 0x162)); insert(std::make_pair("KEY_CLEAR", 0x163)); insert(std::make_pair("KEY_POWER2", 0x164)); insert(std::make_pair("KEY_OPTION", 0x165)); insert(std::make_pair("KEY_INFO", 0x166)); insert(std::make_pair("KEY_TIME", 0x167)); insert(std::make_pair("KEY_VENDOR", 0x168)); insert(std::make_pair("KEY_ARCHIVE", 0x169)); insert(std::make_pair("KEY_PROGRAM", 0x16a)); insert(std::make_pair("KEY_CHANNEL", 0x16b)); insert(std::make_pair("KEY_FAVORITES", 0x16c)); insert(std::make_pair("KEY_EPG", 0x16d)); insert(std::make_pair("KEY_PVR", 0x16e)); insert(std::make_pair("KEY_MHP", 0x16f)); insert(std::make_pair("KEY_LANGUAGE", 0x170)); insert(std::make_pair("KEY_TITLE", 0x171)); insert(std::make_pair("KEY_SUBTITLE", 0x172)); insert(std::make_pair("KEY_ANGLE", 0x173)); insert(std::make_pair("KEY_ZOOM", 0x174)); insert(std::make_pair("KEY_MODE", 0x175)); insert(std::make_pair("KEY_KEYBOARD", 0x176)); insert(std::make_pair("KEY_SCREEN", 0x177)); insert(std::make_pair("KEY_PC", 0x178)); insert(std::make_pair("KEY_TV", 0x179)); insert(std::make_pair("KEY_TV2", 0x17a)); insert(std::make_pair("KEY_VCR", 0x17b)); insert(std::make_pair("KEY_VCR2", 0x17c)); insert(std::make_pair("KEY_SAT", 0x17d)); insert(std::make_pair("KEY_SAT2", 0x17e)); insert(std::make_pair("KEY_CD", 0x17f)); insert(std::make_pair("KEY_TAPE", 0x180)); insert(std::make_pair("KEY_RADIO", 0x181)); insert(std::make_pair("KEY_TUNER", 0x182)); insert(std::make_pair("KEY_PLAYER", 0x183)); insert(std::make_pair("KEY_TEXT", 0x184)); insert(std::make_pair("KEY_DVD", 0x185)); insert(std::make_pair("KEY_AUX", 0x186)); insert(std::make_pair("KEY_MP3", 0x187)); insert(std::make_pair("KEY_AUDIO", 0x188)); insert(std::make_pair("KEY_VIDEO", 0x189)); insert(std::make_pair("KEY_DIRECTORY", 0x18a)); insert(std::make_pair("KEY_LIST", 0x18b)); insert(std::make_pair("KEY_MEMO", 0x18c)); insert(std::make_pair("KEY_CALENDAR", 0x18d)); insert(std::make_pair("KEY_RED", 0x18e)); insert(std::make_pair("KEY_GREEN", 0x18f)); insert(std::make_pair("KEY_YELLOW", 0x190)); insert(std::make_pair("KEY_BLUE", 0x191)); insert(std::make_pair("KEY_CHANNELUP", 0x192)); insert(std::make_pair("KEY_CHANNELDOWN", 0x193)); insert(std::make_pair("KEY_FIRST", 0x194)); insert(std::make_pair("KEY_LAST", 0x195)); insert(std::make_pair("KEY_AB", 0x196)); insert(std::make_pair("KEY_NEXT", 0x197)); insert(std::make_pair("KEY_RESTART", 0x198)); insert(std::make_pair("KEY_SLOW", 0x199)); insert(std::make_pair("KEY_SHUFFLE", 0x19a)); insert(std::make_pair("KEY_BREAK", 0x19b)); insert(std::make_pair("KEY_PREVIOUS", 0x19c)); insert(std::make_pair("KEY_DIGITS", 0x19d)); insert(std::make_pair("KEY_TEEN", 0x19e)); insert(std::make_pair("KEY_TWEN", 0x19f)); insert(std::make_pair("KEY_DEL_EOL", 0x1c0)); insert(std::make_pair("KEY_DEL_EOS", 0x1c1)); insert(std::make_pair("KEY_INS_LINE", 0x1c2)); insert(std::make_pair("KEY_DEL_LINE", 0x1c3)); insert(std::make_pair("KEY_FN", 0x1d0)); insert(std::make_pair("KEY_FN_ESC", 0x1d1)); insert(std::make_pair("KEY_FN_F1", 0x1d2)); insert(std::make_pair("KEY_FN_F2", 0x1d3)); insert(std::make_pair("KEY_FN_F3", 0x1d4)); insert(std::make_pair("KEY_FN_F4", 0x1d5)); insert(std::make_pair("KEY_FN_F5", 0x1d6)); insert(std::make_pair("KEY_FN_F6", 0x1d7)); insert(std::make_pair("KEY_FN_F7", 0x1d8)); insert(std::make_pair("KEY_FN_F8", 0x1d9)); insert(std::make_pair("KEY_FN_F9", 0x1da)); insert(std::make_pair("KEY_FN_F10", 0x1db)); insert(std::make_pair("KEY_FN_F11", 0x1dc)); insert(std::make_pair("KEY_FN_F12", 0x1dd)); insert(std::make_pair("KEY_FN_1", 0x1de)); insert(std::make_pair("KEY_FN_2", 0x1df)); insert(std::make_pair("KEY_FN_D", 0x1e0)); insert(std::make_pair("KEY_FN_E", 0x1e1)); insert(std::make_pair("KEY_FN_F", 0x1e2)); insert(std::make_pair("KEY_FN_S", 0x1e3)); insert(std::make_pair("KEY_FN_B", 0x1e4)); insert(std::make_pair("KEY_BRL_DOT1", 0x1f1)); insert(std::make_pair("KEY_BRL_DOT2", 0x1f2)); insert(std::make_pair("KEY_BRL_DOT3", 0x1f3)); insert(std::make_pair("KEY_BRL_DOT4", 0x1f4)); insert(std::make_pair("KEY_BRL_DOT5", 0x1f5)); insert(std::make_pair("KEY_BRL_DOT6", 0x1f6)); insert(std::make_pair("KEY_BRL_DOT7", 0x1f7)); insert(std::make_pair("KEY_BRL_DOT8", 0x1f8)); //insert(std::make_pair("KEY_MIN_INTERESTING", KEY_MUTE)); insert(std::make_pair("KEY_MAX", 0x1ff)); insert(std::make_pair("REL_X", 0x00)); insert(std::make_pair("REL_Y", 0x01)); insert(std::make_pair("REL_Z", 0x02)); insert(std::make_pair("REL_RX", 0x03)); insert(std::make_pair("REL_RY", 0x04)); insert(std::make_pair("REL_RZ", 0x05)); insert(std::make_pair("REL_HWHEEL", 0x06)); insert(std::make_pair("REL_DIAL", 0x07)); insert(std::make_pair("REL_WHEEL", 0x08)); insert(std::make_pair("REL_MISC", 0x09)); insert(std::make_pair("REL_MAX", 0x0f)); insert(std::make_pair("ABS_X", 0x00)); insert(std::make_pair("ABS_Y", 0x01)); insert(std::make_pair("ABS_Z", 0x02)); insert(std::make_pair("ABS_RX", 0x03)); insert(std::make_pair("ABS_RY", 0x04)); insert(std::make_pair("ABS_RZ", 0x05)); insert(std::make_pair("ABS_THROTTLE", 0x06)); insert(std::make_pair("ABS_RUDDER", 0x07)); insert(std::make_pair("ABS_WHEEL", 0x08)); insert(std::make_pair("ABS_GAS", 0x09)); insert(std::make_pair("ABS_BRAKE", 0x0a)); insert(std::make_pair("ABS_HAT0X", 0x10)); insert(std::make_pair("ABS_HAT0Y", 0x11)); insert(std::make_pair("ABS_HAT1X", 0x12)); insert(std::make_pair("ABS_HAT1Y", 0x13)); insert(std::make_pair("ABS_HAT2X", 0x14)); insert(std::make_pair("ABS_HAT2Y", 0x15)); insert(std::make_pair("ABS_HAT3X", 0x16)); insert(std::make_pair("ABS_HAT3Y", 0x17)); insert(std::make_pair("ABS_PRESSURE", 0x18)); insert(std::make_pair("ABS_DISTANCE", 0x19)); insert(std::make_pair("ABS_TILT_X", 0x1a)); insert(std::make_pair("ABS_TILT_Y", 0x1b)); insert(std::make_pair("ABS_TOOL_WIDTH", 0x1c)); insert(std::make_pair("ABS_VOLUME", 0x20)); insert(std::make_pair("ABS_MISC", 0x28)); insert(std::make_pair("ABS_MAX", 0x3f)); insert(std::make_pair("SW_LID", 0x00)); insert(std::make_pair("SW_TABLET_MODE", 0x01)); insert(std::make_pair("SW_HEADPHONE_INSERT", 0x02)); insert(std::make_pair("SW_MAX", 0x0f)); insert(std::make_pair("MSC_SERIAL", 0x00)); insert(std::make_pair("MSC_PULSELED", 0x01)); insert(std::make_pair("MSC_GESTURE", 0x02)); insert(std::make_pair("MSC_RAW", 0x03)); insert(std::make_pair("MSC_SCAN", 0x04)); insert(std::make_pair("MSC_MAX", 0x07)); insert(std::make_pair("LED_NUML", 0x00)); insert(std::make_pair("LED_CAPSL", 0x01)); insert(std::make_pair("LED_SCROLLL", 0x02)); insert(std::make_pair("LED_COMPOSE", 0x03)); insert(std::make_pair("LED_KANA", 0x04)); insert(std::make_pair("LED_SLEEP", 0x05)); insert(std::make_pair("LED_SUSPEND", 0x06)); insert(std::make_pair("LED_MUTE", 0x07)); insert(std::make_pair("LED_MISC", 0x08)); insert(std::make_pair("LED_MAIL", 0x09)); insert(std::make_pair("LED_CHARGING", 0x0a)); insert(std::make_pair("LED_MAX", 0x0f)); } unsigned long av::daemon::LinuxEvent::getEventCode(const std::string& eventType) { const_iterator return_value = sEventMap.find(eventType); return (return_value != sEventMap.end()) ? return_value->second : 0; }
vrsys/avangong
avango-daemon/src/avango/daemon/LinuxEvent.cpp
C++
lgpl-3.0
23,352
<?php /* * This file is part of the Thelia package. * http://www.thelia.net * * (c) OpenStudio <info@thelia.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Thelia\Core\Event\Loop; use Thelia\Core\Template\Element\BaseLoop; /** * Class LoopExtendsInitializeArgsEvent. * * @author Julien Chanséaume <julien@thelia.net> */ class LoopExtendsInitializeArgsEvent extends LoopExtendsEvent { /** @var array the loop parameters when called. an array of name => value pairs */ protected $loopParameters; /** * LoopExtendsInitializeArgs constructor. */ public function __construct(BaseLoop $loop, array $loopParameters) { parent::__construct($loop); $this->loopParameters = $loopParameters; } /** * The loop parameters when called. an array of name => value pairs. * * @return array the loop parameters when called. an array of name => value pairs */ public function getLoopParameters() { return $this->loopParameters; } /** * @param array $loopParameters */ public function setLoopParameters($loopParameters) { $this->loopParameters = $loopParameters; return $this; } }
thelia/core
lib/Thelia/Core/Event/Loop/LoopExtendsInitializeArgsEvent.php
PHP
lgpl-3.0
1,314
# The LinuxCNC config for milling machine M4 production Dcs<br> Extract sources achives directory ~/linuxcnc/configs <br> Copy the file *.desktop from the directory "./Desktop" on your desktop. <br> Установка основной ветки с помощью git:<br> git clone git://github.com/torvn77/LinuxCNC_Dcs_M4.git ~/linuxcnc/configs/LinuxCNC_Dcs_M4-master <br> Установка дополнительной ветки:<br> git clone --origin branch_name git://github.com/torvn77/LinuxCNC_Dcs_M4.git ~/linuxcnc/configs/LinuxCNC_Dcs_M4-master <br> Обновление с помощью git:<br> cd ~/linuxcnc/configs/LinuxCNC_Dcs_M4-master <br> git pull git://github.com/torvn77/LinuxCNC_Dcs_M4.git <br> Краткая справка по командам git <br> http://www.opennet.ru/tips/info/2179.shtml <br> http://habrahabr.ru/company/mailru/blog/267595/ <br> Хоорошая документация по Git: <br> http://git-scm.com/docs <br> https://githowto.com/ru <br> ssh-keygen -t rsa -C "torvn77@github.com" <br> git clone git@github.com:torvn77/LinuxCNC_SUDA-ST7080.git Git/test <br> cd Git/test <br> echo gggg >test.txt <br> git add . <br> git commit -a -m "test commit" <br> git push <br> exit <br> В папке https://github.com/torvn77/LinuxCNC_SUDA-ST7080/tree/master/src/Devices/Primary есть симлинк Select для выбора используемого устройства. <br> Он не всегда копируется правильно и если linuxcnc не может найти файлы в папке Devices/Primary то вам надо будет его поправить. <br>
torvn77/LinuxCNC_Dcs_M4
README.md
Markdown
lgpl-3.0
1,653
/* file model.c */ #include <R.h> static double parms[14]; #define p parms[0] #define d parms[1] #define e parms[2] #define s parms[3] #define KA parms[4] #define KE parms[5] #define VD parms[6] #define EC50 parms[7] #define n parms[8] #define delta parms[9] #define c parms[10] #define DOSE parms[11] #define TINF parms[12] #define TAU parms[13] /* initializer */ void initmod(void (* odeparms)(int *, double *)) { int N=14; odeparms(&N, parms); } /* Derivatives */ void derivs (int *neq, double *t, double *y, double *ydot, double *yout, int *ip) { double In; if ( fmod(*t,TAU) < TINF ){ In = DOSE/TINF; } else { In = 0; } ydot[0] = -KA*y[0] + In; ydot[1] = KA*y[0] - KE*y[1]; ydot[2] = s - y[2]*(e*y[4]+d); ydot[3] = e*y[2]*y[4]-delta*y[3]; ydot[4] = p*(1-(pow(y[1]/VD,n)/(pow(y[1]/VD,n)+pow(EC50,n))))*y[3]-c*y[4]; } /* END file model.c */
ronkeizer/PopED
inst/examples/HCV_ode.c
C
lgpl-3.0
899
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_ship_components_droid_interface_ddi_rss_imperial_2 = object_tangible_ship_components_droid_interface_shared_ddi_rss_imperial_2:new { } ObjectTemplates:addTemplate(object_tangible_ship_components_droid_interface_ddi_rss_imperial_2, "object/tangible/ship/components/droid_interface/ddi_rss_imperial_2.iff")
kidaa/Awakening-Core3
bin/scripts/object/tangible/ship/components/droid_interface/ddi_rss_imperial_2.lua
Lua
lgpl-3.0
2,324
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_mobile_dressed_mauler_acolyte = object_mobile_shared_dressed_mauler_acolyte:new { } ObjectTemplates:addTemplate(object_mobile_dressed_mauler_acolyte, "object/mobile/dressed_mauler_acolyte.iff")
kidaa/Awakening-Core3
bin/scripts/object/mobile/dressed_mauler_acolyte.lua
Lua
lgpl-3.0
2,204
/*! HTML5 Boilerplate v4.3.0 | MIT License | http://h5bp.com/ */ /* * What follows is the result of much research on cross-browser styling. * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal, * Kroc Camen, and the H5BP dev community and team. */ /* ========================================================================== Base styles: opinionated defaults ========================================================================== */ html { color: #222; font-size: 1em; line-height: 1.4; } /* * Remove text-shadow in selection highlight: * https://twitter.com/miketaylr/status/12228805301 * * These selection rule sets have to be separate. * Customize the background color to match your design. */ ::-moz-selection { background: #b3d4fc; text-shadow: none; } ::selection { background: #b3d4fc; text-shadow: none; } /* * A better looking default horizontal rule */ hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; } /* * Remove the gap between audio, canvas, iframes, * images, videos and the bottom of their containers: * https://github.com/h5bp/html5-boilerplate/issues/440 */ audio, canvas, iframe, img, svg, video { vertical-align: middle; } /* * Remove default fieldset styles. */ fieldset { border: 0; margin: 0; padding: 0; } /* * Allow only vertical resizing of textareas. */ textarea { resize: vertical; } /* ========================================================================== Browser Upgrade Prompt ========================================================================== */ .browserupgrade { margin: 0.2em 0; background: #ccc; color: #000; padding: 0.2em 0; } /* ========================================================================== Author's custom styles ========================================================================== */ /* ========================================================================== Helper classes ========================================================================== */ /* * Hide visually and from screen readers: * http://juicystudio.com/article/screen-readers-display-none.php */ .hidden { display: none !important; visibility: hidden; } /* * Hide only visually, but have it available for screen readers: * http://snook.ca/archives/html_and_css/hiding-content-for-accessibility */ .visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } /* * Extends the .visuallyhidden class to allow the element * to be focusable when navigated to via the keyboard: * https://www.drupal.org/node/897638 */ .visuallyhidden.focusable:active, .visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; } /* * Hide visually and from screen readers, but maintain layout */ .invisible { visibility: hidden; } /* * Clearfix: contain floats * * For modern browsers * 1. The space content is one way to avoid an Opera bug when the * `contenteditable` attribute is included anywhere else in the document. * Otherwise it causes space to appear at the top and bottom of elements * that receive the `clearfix` class. * 2. The use of `table` rather than `block` is only necessary if using * `:before` to contain the top-margins of child elements. */ .clearfix:before, .clearfix:after { content: " "; /* 1 */ display: table; /* 2 */ } .clearfix:after { clear: both; } /* ========================================================================== EXAMPLE Media Queries for Responsive Design. These examples override the primary ('mobile first') styles. Modify as content requires. ========================================================================== */ @media only screen and (min-width: 35em) { /* Style adjustments for viewports that meet the condition */ } @media print, (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { /* Style adjustments for high resolution devices */ } /* ========================================================================== Print styles. Inlined to avoid the additional HTTP request: http://www.phpied.com/delay-loading-your-print-css/ ========================================================================== */ @media print { *, *:before, *:after { background: transparent !important; color: #000 !important; /* Black prints faster: http://www.sanbeiji.com/archives/953 */ box-shadow: none !important; text-shadow: none !important; } a, a:visited { text-decoration: underline; } a[href]:after { content: " (" attr(href) ")"; } abbr[title]:after { content: " (" attr(title) ")"; } /* * Don't show links that are fragment identifiers, * or use the `javascript:` pseudo protocol */ a[href^="#"]:after, a[href^="javascript:"]:after { content: ""; } pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } /* * Printing Tables: * http://css-discuss.incutio.com/wiki/Printing_Tables */ thead { display: table-header-group; } tr, img { page-break-inside: avoid; } img { max-width: 100% !important; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } }
amazingSurge/jquery-asScrollable
examples/css/main.css
CSS
lgpl-3.0
5,810
/* radare - LGPL - Copyright 2017 - pancake */ #include <r_fs.h> #include <r_lib.h> #include <sys/stat.h> static RFSFile *fs_io_open(RFSRoot *root, const char *path) { char *cmd = r_str_newf ("m %s", path); char *res = root->iob.system (root->iob.io, cmd); R_FREE (cmd); if (res) { ut32 size = 0; if (sscanf (res, "%u", &size) != 1) { size = 0; } R_FREE (res); if (size == 0) { return NULL; } RFSFile *file = r_fs_file_new (root, path); if (!file) { return NULL; } file->ptr = NULL; file->p = root->p; file->size = size; return file; } return NULL; } static bool fs_io_read(RFSFile *file, ut64 addr, int len) { RFSRoot *root = file->root; // char *cmd = r_str_newf ("mg %s %"PFMT64x" %d", file->path, addr, len); char *cmd = r_str_newf ("mg %s", file->name); char *res = root->iob.system (root->iob.io, cmd); R_FREE (cmd); if (res) { int encoded_size = strlen (res); if (encoded_size != len * 2) { eprintf ("Wrong size\n"); R_FREE (res); return NULL; } file->data = (ut8 *) calloc (1, len); if (!file->data) { R_FREE (res); return NULL; } int ret = r_hex_str2bin (res, file->data); if (ret != len) { eprintf ("Inconsistent read\n"); R_FREE (file->data); } R_FREE (res); } return NULL; } static void fs_io_close(RFSFile *file) { // fclose (file->ptr); } static void append_file(RList *list, const char *name, int type, int time, ut64 size) { RFSFile *fsf = r_fs_file_new (NULL, name); if (!fsf) { return; } fsf->type = type; fsf->time = time; fsf->size = size; r_list_append (list, fsf); } static RList *fs_io_dir(RFSRoot *root, const char *path, int view /*ignored*/) { RList *list = r_list_new (); if (!list) { return NULL; } char *cmd = r_str_newf ("md %s", path); char *res = root->iob.system (root->iob.io, cmd); if (res) { int i, count = 0; int *lines = r_str_split_lines (res, &count); if (lines) { for (i = 0; i < count; i++) { const char *line = res + lines[i]; if (!*line) { continue; } char type = 'f'; if (line[1] == ' ' && line[0] != ' ') { type = line[0]; line += 2; } append_file (list, line, type, 0, 0); } R_FREE (res); R_FREE (lines); } } R_FREE (cmd); return list; } static int fs_io_mount(RFSRoot *root) { root->ptr = NULL; return true; } static void fs_io_umount(RFSRoot *root) { root->ptr = NULL; } RFSPlugin r_fs_plugin_io = { .name = "io", .desc = "r_io based filesystem", .license = "MIT", .open = fs_io_open, .read = fs_io_read, .close = fs_io_close, .dir = &fs_io_dir, .mount = fs_io_mount, .umount = fs_io_umount, }; #ifndef CORELIB R_API RLibStruct radare_plugin = { .type = R_LIB_TYPE_FS, .data = &r_fs_plugin_io, .version = R2_VERSION }; #endif
l4l/radare2
libr/fs/p/fs_io.c
C
lgpl-3.0
2,774
// // execution/bulk_execute.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_EXECUTION_BULK_EXECUTE_HPP #define ASIO_EXECUTION_BULK_EXECUTE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/execution/bulk_guarantee.hpp" #include "asio/execution/detail/bulk_sender.hpp" #include "asio/execution/executor.hpp" #include "asio/execution/sender.hpp" #include "asio/traits/bulk_execute_member.hpp" #include "asio/traits/bulk_execute_free.hpp" #include "asio/detail/push_options.hpp" #if defined(GENERATING_DOCUMENTATION) namespace asio { namespace execution { /// A customisation point that creates a bulk sender. /** * The name <tt>execution::bulk_execute</tt> denotes a customisation point * object. If <tt>is_convertible_v<N, size_t></tt> is true, then the expression * <tt>execution::bulk_execute(S, F, N)</tt> for some subexpressions * <tt>S</tt>, <tt>F</tt>, and <tt>N</tt> is expression-equivalent to: * * @li <tt>S.bulk_execute(F, N)</tt>, if that expression is valid. If the * function selected does not execute <tt>N</tt> invocations of the function * object <tt>F</tt> on the executor <tt>S</tt> in bulk with forward progress * guarantee <tt>asio::query(S, execution::bulk_guarantee)</tt>, and * the result of that function does not model <tt>sender<void></tt>, the * program is ill-formed with no diagnostic required. * * @li Otherwise, <tt>bulk_execute(S, F, N)</tt>, if that expression is valid, * with overload resolution performed in a context that includes the * declaration <tt>void bulk_execute();</tt> and that does not include a * declaration of <tt>execution::bulk_execute</tt>. If the function selected * by overload resolution does not execute <tt>N</tt> invocations of the * function object <tt>F</tt> on the executor <tt>S</tt> in bulk with forward * progress guarantee <tt>asio::query(E, * execution::bulk_guarantee)</tt>, and the result of that function does not * model <tt>sender<void></tt>, the program is ill-formed with no diagnostic * required. * * @li Otherwise, if the types <tt>F</tt> and * <tt>executor_index_t<remove_cvref_t<S>></tt> model <tt>invocable</tt> and * if <tt>asio::query(S, execution::bulk_guarantee)</tt> equals * <tt>execution::bulk_guarantee.unsequenced</tt>, then * * - Evaluates <tt>DECAY_COPY(std::forward<decltype(F)>(F))</tt> on the * calling thread to create a function object <tt>cf</tt>. [Note: * Additional copies of <tt>cf</tt> may subsequently be created. --end * note.] * * - For each value of <tt>i</tt> in <tt>N</tt>, <tt>cf(i)</tt> (or copy of * <tt>cf</tt>)) will be invoked at most once by an execution agent that is * unique for each value of <tt>i</tt>. * * - May block pending completion of one or more invocations of <tt>cf</tt>. * * - Synchronizes with (C++Std [intro.multithread]) the invocations of * <tt>cf</tt>. * * @li Otherwise, <tt>execution::bulk_execute(S, F, N)</tt> is ill-formed. */ inline constexpr unspecified bulk_execute = unspecified; /// A type trait that determines whether a @c bulk_execute expression is /// well-formed. /** * Class template @c can_bulk_execute is a trait that is derived from @c * true_type if the expression <tt>execution::bulk_execute(std::declval<S>(), * std::declval<F>(), std::declval<N>)</tt> is well formed; otherwise @c * false_type. */ template <typename S, typename F, typename N> struct can_bulk_execute : integral_constant<bool, automatically_determined> { }; } // namespace execution } // namespace asio #else // defined(GENERATING_DOCUMENTATION) namespace asio_execution_bulk_execute_fn { using asio::declval; using asio::enable_if; using asio::execution::bulk_guarantee_t; using asio::execution::detail::bulk_sender; using asio::execution::executor_index; using asio::execution::is_sender; using asio::is_convertible; using asio::is_same; using asio::remove_cvref; using asio::result_of; using asio::traits::bulk_execute_free; using asio::traits::bulk_execute_member; using asio::traits::static_require; void bulk_execute(); enum overload_type { call_member, call_free, adapter, ill_formed }; template <typename S, typename Args, typename = void> struct call_traits { ASIO_STATIC_CONSTEXPR(overload_type, overload = ill_formed); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = false); typedef void result_type; }; template <typename S, typename F, typename N> struct call_traits<S, void(F, N), typename enable_if< ( is_convertible<N, std::size_t>::value && bulk_execute_member<S, F, N>::is_valid && is_sender< typename bulk_execute_member<S, F, N>::result_type >::value ) >::type> : bulk_execute_member<S, F, N> { ASIO_STATIC_CONSTEXPR(overload_type, overload = call_member); }; template <typename S, typename F, typename N> struct call_traits<S, void(F, N), typename enable_if< ( is_convertible<N, std::size_t>::value && !bulk_execute_member<S, F, N>::is_valid && bulk_execute_free<S, F, N>::is_valid && is_sender< typename bulk_execute_free<S, F, N>::result_type >::value ) >::type> : bulk_execute_free<S, F, N> { ASIO_STATIC_CONSTEXPR(overload_type, overload = call_free); }; template <typename S, typename F, typename N> struct call_traits<S, void(F, N), typename enable_if< ( is_convertible<N, std::size_t>::value && !bulk_execute_member<S, F, N>::is_valid && !bulk_execute_free<S, F, N>::is_valid && is_sender<S>::value && is_same< typename result_of< F(typename executor_index<typename remove_cvref<S>::type>::type) >::type, typename result_of< F(typename executor_index<typename remove_cvref<S>::type>::type) >::type >::value && static_require<S, bulk_guarantee_t::unsequenced_t>::is_valid ) >::type> { ASIO_STATIC_CONSTEXPR(overload_type, overload = adapter); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = false); typedef bulk_sender<S, F, N> result_type; }; struct impl { #if defined(ASIO_HAS_MOVE) template <typename S, typename F, typename N> ASIO_CONSTEXPR typename enable_if< call_traits<S, void(F, N)>::overload == call_member, typename call_traits<S, void(F, N)>::result_type >::type operator()(S&& s, F&& f, N&& n) const ASIO_NOEXCEPT_IF(( call_traits<S, void(F, N)>::is_noexcept)) { return ASIO_MOVE_CAST(S)(s).bulk_execute( ASIO_MOVE_CAST(F)(f), ASIO_MOVE_CAST(N)(n)); } template <typename S, typename F, typename N> ASIO_CONSTEXPR typename enable_if< call_traits<S, void(F, N)>::overload == call_free, typename call_traits<S, void(F, N)>::result_type >::type operator()(S&& s, F&& f, N&& n) const ASIO_NOEXCEPT_IF(( call_traits<S, void(F, N)>::is_noexcept)) { return bulk_execute(ASIO_MOVE_CAST(S)(s), ASIO_MOVE_CAST(F)(f), ASIO_MOVE_CAST(N)(n)); } template <typename S, typename F, typename N> ASIO_CONSTEXPR typename enable_if< call_traits<S, void(F, N)>::overload == adapter, typename call_traits<S, void(F, N)>::result_type >::type operator()(S&& s, F&& f, N&& n) const ASIO_NOEXCEPT_IF(( call_traits<S, void(F, N)>::is_noexcept)) { return typename call_traits<S, void(F, N)>::result_type( ASIO_MOVE_CAST(S)(s), ASIO_MOVE_CAST(F)(f), ASIO_MOVE_CAST(N)(n)); } #else // defined(ASIO_HAS_MOVE) template <typename S, typename F, typename N> ASIO_CONSTEXPR typename enable_if< call_traits<S, void(const F&, const N&)>::overload == call_member, typename call_traits<S, void(const F&, const N&)>::result_type >::type operator()(S& s, const F& f, const N& n) const ASIO_NOEXCEPT_IF(( call_traits<S, void(const F&, const N&)>::is_noexcept)) { return s.bulk_execute(ASIO_MOVE_CAST(F)(f), ASIO_MOVE_CAST(N)(n)); } template <typename S, typename F, typename N> ASIO_CONSTEXPR typename enable_if< call_traits<S, void(const F&, const N&)>::overload == call_member, typename call_traits<S, void(const F&, const N&)>::result_type >::type operator()(const S& s, const F& f, const N& n) const ASIO_NOEXCEPT_IF(( call_traits<S, void(const F&, const N&)>::is_noexcept)) { return s.bulk_execute(ASIO_MOVE_CAST(F)(f), ASIO_MOVE_CAST(N)(n)); } template <typename S, typename F, typename N> ASIO_CONSTEXPR typename enable_if< call_traits<S, void(const F&, const N&)>::overload == call_free, typename call_traits<S, void(const F&, const N&)>::result_type >::type operator()(S& s, const F& f, const N& n) const ASIO_NOEXCEPT_IF(( call_traits<S, void(const F&, const N&)>::is_noexcept)) { return bulk_execute(s, ASIO_MOVE_CAST(F)(f), ASIO_MOVE_CAST(N)(n)); } template <typename S, typename F, typename N> ASIO_CONSTEXPR typename enable_if< call_traits<S, void(const F&, const N&)>::overload == call_free, typename call_traits<S, void(const F&, const N&)>::result_type >::type operator()(const S& s, const F& f, const N& n) const ASIO_NOEXCEPT_IF(( call_traits<S, void(const F&, const N&)>::is_noexcept)) { return bulk_execute(s, ASIO_MOVE_CAST(F)(f), ASIO_MOVE_CAST(N)(n)); } template <typename S, typename F, typename N> ASIO_CONSTEXPR typename enable_if< call_traits<S, void(const F&, const N&)>::overload == adapter, typename call_traits<S, void(const F&, const N&)>::result_type >::type operator()(S& s, const F& f, const N& n) const ASIO_NOEXCEPT_IF(( call_traits<S, void(const F&, const N&)>::is_noexcept)) { return typename call_traits<S, void(const F&, const N&)>::result_type( s, ASIO_MOVE_CAST(F)(f), ASIO_MOVE_CAST(N)(n)); } template <typename S, typename F, typename N> ASIO_CONSTEXPR typename enable_if< call_traits<S, void(const F&, const N&)>::overload == adapter, typename call_traits<S, void(const F&, const N&)>::result_type >::type operator()(const S& s, const F& f, const N& n) const ASIO_NOEXCEPT_IF(( call_traits<S, void(const F&, const N&)>::is_noexcept)) { return typename call_traits<S, void(const F&, const N&)>::result_type( s, ASIO_MOVE_CAST(F)(f), ASIO_MOVE_CAST(N)(n)); } #endif // defined(ASIO_HAS_MOVE) }; template <typename T = impl> struct static_instance { static const T instance; }; template <typename T> const T static_instance<T>::instance = {}; } // namespace asio_execution_bulk_execute_fn namespace asio { namespace execution { namespace { static ASIO_CONSTEXPR const asio_execution_bulk_execute_fn::impl& bulk_execute = asio_execution_bulk_execute_fn::static_instance<>::instance; } // namespace template <typename S, typename F, typename N> struct can_bulk_execute : integral_constant<bool, asio_execution_bulk_execute_fn::call_traits<S, void(F, N)>::overload != asio_execution_bulk_execute_fn::ill_formed> { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename S, typename F, typename N> constexpr bool can_bulk_execute_v = can_bulk_execute<S, F, N>::value; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename S, typename F, typename N> struct is_nothrow_bulk_execute : integral_constant<bool, asio_execution_bulk_execute_fn::call_traits<S, void(F, N)>::is_noexcept> { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename S, typename F, typename N> constexpr bool is_nothrow_bulk_execute_v = is_nothrow_bulk_execute<S, F, N>::value; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename S, typename F, typename N> struct bulk_execute_result { typedef typename asio_execution_bulk_execute_fn::call_traits< S, void(F, N)>::result_type type; }; } // namespace execution } // namespace asio #endif // defined(GENERATING_DOCUMENTATION) #include "asio/detail/pop_options.hpp" #endif // ASIO_EXECUTION_BULK_EXECUTE_HPP
tekezo/Karabiner-Elements
src/vendor/cget/cget/pkg/chriskohlhoff__asio/install/include/asio/execution/bulk_execute.hpp
C++
unlicense
12,386
using Photon; using UnityEngine; using System.Collections; using ExitGames.Client.Photon; public class DemoMecanimGUI : PunBehaviour { #region Properties public GUISkin Skin; #endregion #region Members private PhotonAnimatorView m_AnimatorView; // local animatorView. set when we create our character in CreatePlayerObject() private Animator m_RemoteAnimator; // to display the synchronized values on the right side in the GUI. A third player will simply be ignored (until the second player leaves) private float m_SlideIn = 0f; private float m_FoundPlayerSlideIn = 0f; private bool m_IsOpen = false; #endregion #region Unity public void Awake() { } public void Update() { FindRemoteAnimator(); m_SlideIn = Mathf.Lerp( m_SlideIn, m_IsOpen ? 1f : 0f, Time.deltaTime * 9f ); m_FoundPlayerSlideIn = Mathf.Lerp( m_FoundPlayerSlideIn, m_AnimatorView == null ? 0f : 1f, Time.deltaTime * 5f ); } /// <summary>Finds the Animator component of a remote client on a GameObject tagged as Player and sets m_RemoteAnimator.</summary> public void FindRemoteAnimator() { if( m_RemoteAnimator != null ) { return; } // the prefab has to be tagged as Player GameObject[] gos = GameObject.FindGameObjectsWithTag( "Player" ); for( int i = 0; i < gos.Length; ++i ) { PhotonView view = gos[ i ].GetComponent<PhotonView>(); if( view != null && view.isMine == false ) { m_RemoteAnimator = gos[ i ].GetComponent<Animator>(); } } } public void OnGUI() { GUI.skin = Skin; string[] synchronizeTypeContent = new string[] { "Disabled", "Discrete", "Continuous" }; GUILayout.BeginArea( new Rect( Screen.width - 200 * m_FoundPlayerSlideIn - 400 * m_SlideIn, 0, 600, Screen.height ), GUI.skin.box ); { GUILayout.Label( "Mecanim Demo", GUI.skin.customStyles[ 0 ] ); GUI.color = Color.white; string label = "Settings"; if( m_IsOpen == true ) { label = "Close"; } if( GUILayout.Button( label, GUILayout.Width( 110 ) ) ) { m_IsOpen = !m_IsOpen; } string parameters = ""; if( m_AnimatorView != null ) { parameters += "Send Values:\n"; for( int i = 0; i < m_AnimatorView.GetSynchronizedParameters().Count; ++i ) { PhotonAnimatorView.SynchronizedParameter parameter = m_AnimatorView.GetSynchronizedParameters()[ i ]; try { switch( parameter.Type ) { case PhotonAnimatorView.ParameterType.Bool: parameters += parameter.Name + " (" + ( m_AnimatorView.GetComponent<Animator>().GetBool( parameter.Name ) ? "True" : "False" ) + ")\n"; break; case PhotonAnimatorView.ParameterType.Int: parameters += parameter.Name + " (" + m_AnimatorView.GetComponent<Animator>().GetInteger( parameter.Name ) + ")\n"; break; case PhotonAnimatorView.ParameterType.Float: parameters += parameter.Name + " (" + m_AnimatorView.GetComponent<Animator>().GetFloat( parameter.Name ).ToString( "0.00" ) + ")\n"; break; } } catch { Debug.Log( "derrrr for " + parameter.Name ); } } } if( m_RemoteAnimator != null ) { parameters += "\nReceived Values:\n"; for( int i = 0; i < m_AnimatorView.GetSynchronizedParameters().Count; ++i ) { PhotonAnimatorView.SynchronizedParameter parameter = m_AnimatorView.GetSynchronizedParameters()[ i ]; try { switch( parameter.Type ) { case PhotonAnimatorView.ParameterType.Bool: parameters += parameter.Name + " (" + ( m_RemoteAnimator.GetBool( parameter.Name ) ? "True" : "False" ) + ")\n"; break; case PhotonAnimatorView.ParameterType.Int: parameters += parameter.Name + " (" + m_RemoteAnimator.GetInteger( parameter.Name ) + ")\n"; break; case PhotonAnimatorView.ParameterType.Float: parameters += parameter.Name + " (" + m_RemoteAnimator.GetFloat( parameter.Name ).ToString( "0.00" ) + ")\n"; break; } } catch { Debug.Log( "derrrr for " + parameter.Name ); } } } GUIStyle style = new GUIStyle( GUI.skin.label ); style.alignment = TextAnchor.UpperLeft; GUI.color = new Color( 1f, 1f, 1f, 1 - m_SlideIn ); GUI.Label( new Rect( 10, 100, 600, Screen.height ), parameters, style ); if( m_AnimatorView != null ) { GUI.color = new Color( 1f, 1f, 1f, m_SlideIn ); GUILayout.Space( 20 ); GUILayout.Label( "Synchronize Parameters" ); for( int i = 0; i < m_AnimatorView.GetSynchronizedParameters().Count; ++i ) { GUILayout.BeginHorizontal(); { PhotonAnimatorView.SynchronizedParameter parameter = m_AnimatorView.GetSynchronizedParameters()[ i ]; GUILayout.Label( parameter.Name, GUILayout.Width( 100 ), GUILayout.Height( 36 ) ); int selectedValue = (int)parameter.SynchronizeType; int newValue = GUILayout.Toolbar( selectedValue, synchronizeTypeContent ); if( newValue != selectedValue ) { m_AnimatorView.SetParameterSynchronized( parameter.Name, parameter.Type, (PhotonAnimatorView.SynchronizeType)newValue ); } } GUILayout.EndHorizontal(); } } } GUILayout.EndArea(); } #endregion #region Photon public override void OnJoinedRoom() { CreatePlayerObject(); } private void CreatePlayerObject() { Vector3 position = new Vector3( -2, 0, 0 ); position.x += Random.Range( -3f, 3f ); position.z += Random.Range( -4f, 4f ); GameObject newPlayerObject = PhotonNetwork.Instantiate( "Robot Kyle Mecanim", position, Quaternion.identity, 0 ); m_AnimatorView = newPlayerObject.GetComponent<PhotonAnimatorView>(); } #endregion }
pierredepaz/alternate-realities
projects/alejandra/hw_photon - ale, miha and nate/Assets/Photon Unity Networking/Demos/DemoMecanim/Scripts/DemoMecanimGUI.cs
C#
unlicense
7,510
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_30) on Sat Mar 22 15:15:47 EDT 2014 --> <title>StandardXYSeriesLabelGenerator (JFreeChart Class Library (version 1.0.17))</title> <meta name="date" content="2014-03-22"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="StandardXYSeriesLabelGenerator (JFreeChart Class Library (version 1.0.17))"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/StandardXYSeriesLabelGenerator.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/jfree/chart/labels/StandardXYItemLabelGenerator.html" title="class in org.jfree.chart.labels"><span class="strong">PREV CLASS</span></a></li> <li><a href="../../../../org/jfree/chart/labels/StandardXYToolTipGenerator.html" title="class in org.jfree.chart.labels"><span class="strong">NEXT CLASS</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html" target="_top">FRAMES</a></li> <li><a href="StandardXYSeriesLabelGenerator.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>SUMMARY:&nbsp;</li> <li>NESTED&nbsp;|&nbsp;</li> <li><a href="#field_summary">FIELD</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">CONSTR</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">METHOD</a></li> </ul> <ul class="subNavList"> <li>DETAIL:&nbsp;</li> <li><a href="#field_detail">FIELD</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">CONSTR</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">METHOD</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <p class="subTitle">org.jfree.chart.labels</p> <h2 title="Class StandardXYSeriesLabelGenerator" class="title">Class StandardXYSeriesLabelGenerator</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.jfree.chart.labels.StandardXYSeriesLabelGenerator</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable, java.lang.Cloneable, <a href="../../../../org/jfree/chart/labels/XYSeriesLabelGenerator.html" title="interface in org.jfree.chart.labels">XYSeriesLabelGenerator</a>, org.jfree.util.PublicCloneable</dd> </dl> <hr> <br> <pre>public class <a href="../../../../src-html/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#line.62">StandardXYSeriesLabelGenerator</a> extends java.lang.Object implements <a href="../../../../org/jfree/chart/labels/XYSeriesLabelGenerator.html" title="interface in org.jfree.chart.labels">XYSeriesLabelGenerator</a>, java.lang.Cloneable, org.jfree.util.PublicCloneable, java.io.Serializable</pre> <div class="block">A standard series label generator for plots that use data from an <a href="../../../../org/jfree/data/xy/XYDataset.html" title="interface in org.jfree.data.xy"><code>XYDataset</code></a>. <br><br> This class implements <code>PublicCloneable</code> by mistake but we retain this for the sake of backward compatibility.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../serialized-form.html#org.jfree.chart.labels.StandardXYSeriesLabelGenerator">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#DEFAULT_LABEL_FORMAT">DEFAULT_LABEL_FORMAT</a></strong></code> <div class="block">The default item label format.</div> </td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#StandardXYSeriesLabelGenerator()">StandardXYSeriesLabelGenerator</a></strong>()</code> <div class="block">Creates a default series label generator (uses <a href="../../../../org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#DEFAULT_LABEL_FORMAT"><code>DEFAULT_LABEL_FORMAT</code></a>).</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#StandardXYSeriesLabelGenerator(java.lang.String)">StandardXYSeriesLabelGenerator</a></strong>(java.lang.String&nbsp;format)</code> <div class="block">Creates a new series label generator.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.Object</code></td> <td class="colLast"><code><strong><a href="../../../../org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#clone()">clone</a></strong>()</code> <div class="block">Returns an independent copy of the generator.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected java.lang.Object[]</code></td> <td class="colLast"><code><strong><a href="../../../../org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#createItemArray(org.jfree.data.xy.XYDataset, int)">createItemArray</a></strong>(<a href="../../../../org/jfree/data/xy/XYDataset.html" title="interface in org.jfree.data.xy">XYDataset</a>&nbsp;dataset, int&nbsp;series)</code> <div class="block">Creates the array of items that can be passed to the <code>MessageFormat</code> class for creating labels.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#equals(java.lang.Object)">equals</a></strong>(java.lang.Object&nbsp;obj)</code> <div class="block">Tests this object for equality with an arbitrary object.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#generateLabel(org.jfree.data.xy.XYDataset, int)">generateLabel</a></strong>(<a href="../../../../org/jfree/data/xy/XYDataset.html" title="interface in org.jfree.data.xy">XYDataset</a>&nbsp;dataset, int&nbsp;series)</code> <div class="block">Generates a label for the specified series.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../../org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#hashCode()">hashCode</a></strong>()</code> <div class="block">Returns a hash code for this instance.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>finalize, getClass, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="DEFAULT_LABEL_FORMAT"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DEFAULT_LABEL_FORMAT</h4> <pre>public static final&nbsp;java.lang.String <a href="../../../../src-html/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#line.69">DEFAULT_LABEL_FORMAT</a></pre> <div class="block">The default item label format.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#org.jfree.chart.labels.StandardXYSeriesLabelGenerator.DEFAULT_LABEL_FORMAT">Constant Field Values</a></dd></dl> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="StandardXYSeriesLabelGenerator()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>StandardXYSeriesLabelGenerator</h4> <pre>public&nbsp;<a href="../../../../src-html/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#line.78">StandardXYSeriesLabelGenerator</a>()</pre> <div class="block">Creates a default series label generator (uses <a href="../../../../org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#DEFAULT_LABEL_FORMAT"><code>DEFAULT_LABEL_FORMAT</code></a>).</div> </li> </ul> <a name="StandardXYSeriesLabelGenerator(java.lang.String)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>StandardXYSeriesLabelGenerator</h4> <pre>public&nbsp;<a href="../../../../src-html/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#line.87">StandardXYSeriesLabelGenerator</a>(java.lang.String&nbsp;format)</pre> <div class="block">Creates a new series label generator.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>format</code> - the format pattern (<code>null</code> not permitted).</dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="generateLabel(org.jfree.data.xy.XYDataset, int)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>generateLabel</h4> <pre>public&nbsp;java.lang.String&nbsp;<a href="../../../../src-html/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#line.102">generateLabel</a>(<a href="../../../../org/jfree/data/xy/XYDataset.html" title="interface in org.jfree.data.xy">XYDataset</a>&nbsp;dataset, int&nbsp;series)</pre> <div class="block">Generates a label for the specified series. This label will be used for the chart legend.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../org/jfree/chart/labels/XYSeriesLabelGenerator.html#generateLabel(org.jfree.data.xy.XYDataset, int)">generateLabel</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../org/jfree/chart/labels/XYSeriesLabelGenerator.html" title="interface in org.jfree.chart.labels">XYSeriesLabelGenerator</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>dataset</code> - the dataset (<code>null</code> not permitted).</dd><dd><code>series</code> - the series.</dd> <dt><span class="strong">Returns:</span></dt><dd>A series label.</dd></dl> </li> </ul> <a name="createItemArray(org.jfree.data.xy.XYDataset, int)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createItemArray</h4> <pre>protected&nbsp;java.lang.Object[]&nbsp;<a href="../../../../src-html/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#line.119">createItemArray</a>(<a href="../../../../org/jfree/data/xy/XYDataset.html" title="interface in org.jfree.data.xy">XYDataset</a>&nbsp;dataset, int&nbsp;series)</pre> <div class="block">Creates the array of items that can be passed to the <code>MessageFormat</code> class for creating labels.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>dataset</code> - the dataset (<code>null</code> not permitted).</dd><dd><code>series</code> - the series (zero-based index).</dd> <dt><span class="strong">Returns:</span></dt><dd>The items (never <code>null</code>).</dd></dl> </li> </ul> <a name="clone()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>clone</h4> <pre>public&nbsp;java.lang.Object&nbsp;<a href="../../../../src-html/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#line.135">clone</a>() throws java.lang.CloneNotSupportedException</pre> <div class="block">Returns an independent copy of the generator. This is unnecessary, because instances are immutable anyway, but we retain this behaviour for backwards compatibility.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>clone</code>&nbsp;in interface&nbsp;<code>org.jfree.util.PublicCloneable</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>clone</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> <dt><span class="strong">Returns:</span></dt><dd>A clone.</dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.lang.CloneNotSupportedException</code> - if cloning is not supported.</dd></dl> </li> </ul> <a name="equals(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;<a href="../../../../src-html/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#line.147">equals</a>(java.lang.Object&nbsp;obj)</pre> <div class="block">Tests this object for equality with an arbitrary object.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>equals</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>obj</code> - the other object (<code>null</code> permitted).</dd> <dt><span class="strong">Returns:</span></dt><dd>A boolean.</dd></dl> </li> </ul> <a name="hashCode()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>hashCode</h4> <pre>public&nbsp;int&nbsp;<a href="../../../../src-html/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html#line.168">hashCode</a>()</pre> <div class="block">Returns a hash code for this instance.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>hashCode</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> <dt><span class="strong">Returns:</span></dt><dd>A hash code.</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/StandardXYSeriesLabelGenerator.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/jfree/chart/labels/StandardXYItemLabelGenerator.html" title="class in org.jfree.chart.labels"><span class="strong">PREV CLASS</span></a></li> <li><a href="../../../../org/jfree/chart/labels/StandardXYToolTipGenerator.html" title="class in org.jfree.chart.labels"><span class="strong">NEXT CLASS</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html" target="_top">FRAMES</a></li> <li><a href="StandardXYSeriesLabelGenerator.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>SUMMARY:&nbsp;</li> <li>NESTED&nbsp;|&nbsp;</li> <li><a href="#field_summary">FIELD</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">CONSTR</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">METHOD</a></li> </ul> <ul class="subNavList"> <li>DETAIL:&nbsp;</li> <li><a href="#field_detail">FIELD</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">CONSTR</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">METHOD</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
GliderWinchItems/GliderWinchj2
lib/JFreeChart-1.0.17/javadoc/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.html
HTML
unlicense
18,945
'use strict'; //Articles service used for communicating with the articles REST endpoints angular.module('articles').factory('Articles', ['$resource', function ($resource) { return $resource('api/articles/:articleId', { articleId: '@_id' }, { update: { method: 'PUT' } }); } ]);
andresvicente00/job_finder
modules/articles/client/services/articles.client.service.js
JavaScript
unlicense
335
<?php op_mobile_page_title(__('Demotion sub-administrator of this %community%'), $community->getName()) ?> <?php op_include_parts('yesNo', 'removeSubAdminConfirmForm', array( 'body' => __("Do you demotion %0% from this %community%'s sub-administrator?", array('%0%' => $member->getName())), 'yes_form' => new BaseForm(), 'no_url' => url_for('community/memberManage?id='.$community->getId()), 'no_method' => 'get', 'align' => 'center', )) ?>
tejimaya/OpenPNE3
apps/mobile_frontend/modules/community/templates/removeSubAdminInput.php
PHP
apache-2.0
455
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hyracks.algebricks.rewriter.rules; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang3.mutable.Mutable; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator; import org.apache.hyracks.algebricks.core.algebra.base.IOptimizationContext; import org.apache.hyracks.algebricks.core.algebra.base.LogicalOperatorTag; import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable; import org.apache.hyracks.algebricks.core.algebra.operators.logical.AbstractLogicalOperator; import org.apache.hyracks.algebricks.core.algebra.operators.logical.SelectOperator; import org.apache.hyracks.algebricks.core.algebra.operators.logical.visitors.VariableUtilities; import org.apache.hyracks.algebricks.core.algebra.util.OperatorPropertiesUtil; import org.apache.hyracks.algebricks.core.rewriter.base.IAlgebraicRewriteRule; public class PushSelectDownRule implements IAlgebraicRewriteRule { @Override public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context) { return false; } @Override public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException { AbstractLogicalOperator op = (AbstractLogicalOperator) opRef.getValue(); if (op.getOperatorTag() != LogicalOperatorTag.SELECT) { return false; } Mutable<ILogicalOperator> opRef2 = op.getInputs().get(0); AbstractLogicalOperator op2 = (AbstractLogicalOperator) opRef2.getValue(); if (context.checkAndAddToAlreadyCompared(op, op2)) { return false; } LogicalOperatorTag tag2 = op2.getOperatorTag(); if (tag2 == LogicalOperatorTag.INNERJOIN || tag2 == LogicalOperatorTag.LEFTOUTERJOIN || tag2 == LogicalOperatorTag.REPLICATE || tag2 == LogicalOperatorTag.SPLIT) { return false; } else { // not a join boolean res = propagateSelectionRec(opRef, opRef2); if (res) { OperatorPropertiesUtil.typeOpRec(opRef, context); } return res; } } private static boolean propagateSelectionRec(Mutable<ILogicalOperator> sigmaRef, Mutable<ILogicalOperator> opRef2) throws AlgebricksException { AbstractLogicalOperator op2 = (AbstractLogicalOperator) opRef2.getValue(); if (op2.getInputs().size() != 1 || op2.getOperatorTag() == LogicalOperatorTag.DATASOURCESCAN || !OperatorPropertiesUtil.isMovable(op2)) { return false; } SelectOperator sigma = (SelectOperator) sigmaRef.getValue(); LinkedList<LogicalVariable> usedInSigma = new LinkedList<LogicalVariable>(); sigma.getCondition().getValue().getUsedVariables(usedInSigma); LinkedList<LogicalVariable> produced2 = new LinkedList<LogicalVariable>(); VariableUtilities.getProducedVariables(op2, produced2); if (OperatorPropertiesUtil.disjoint(produced2, usedInSigma)) { // just swap opRef2.setValue(sigma); sigmaRef.setValue(op2); List<Mutable<ILogicalOperator>> sigmaInpList = sigma.getInputs(); sigmaInpList.clear(); sigmaInpList.addAll(op2.getInputs()); List<Mutable<ILogicalOperator>> op2InpList = op2.getInputs(); op2InpList.clear(); op2InpList.add(opRef2); propagateSelectionRec(opRef2, sigma.getInputs().get(0)); return true; } return false; } }
heriram/incubator-asterixdb
hyracks-fullstack/algebricks/algebricks-rewriter/src/main/java/org/apache/hyracks/algebricks/rewriter/rules/PushSelectDownRule.java
Java
apache-2.0
4,488
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using NodaTime.Calendars; using NodaTime.Test.TimeZones.IO; using NodaTime.TimeZones; using NUnit.Framework; namespace NodaTime.Test.TimeZones { [TestFixture] public class ZoneRecurrenceTest { [Test] public void Constructor_nullName_exception() { var yearOffset = new ZoneYearOffset(TransitionMode.Utc, 10, 31, (int)IsoDayOfWeek.Wednesday, true, LocalTime.Midnight); Assert.Throws(typeof(ArgumentNullException), () => new ZoneRecurrence(null, Offset.Zero, yearOffset, 1971, 2009), "Null name"); } [Test] public void Constructor_nullYearOffset_exception() { Assert.Throws(typeof(ArgumentNullException), () => new ZoneRecurrence("bob", Offset.Zero, null, 1971, 2009), "Null yearOffset"); } [Test] public void Next_BeforeFirstYear() { var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.Next(Instant.MinValue, Offset.Zero, Offset.Zero); Transition? expected = new Transition(NodaConstants.UnixEpoch, Offset.Zero); Assert.AreEqual(expected, actual); } [Test] public void Next_FirstYear() { var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.Next(NodaConstants.UnixEpoch, Offset.Zero, Offset.Zero); Transition? expected = new Transition(Instant.FromUtc(1971, 1, 1, 0, 0), Offset.Zero); Assert.AreEqual(expected, actual); } [Test] public void NextTwice_FirstYear() { var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.Next(NodaConstants.UnixEpoch, Offset.Zero, Offset.Zero); actual = recurrence.Next(actual.Value.Instant, Offset.Zero, Offset.Zero); Transition? expected = new Transition(Instant.FromUtc(1972, 1, 1, 0, 0), Offset.Zero); Assert.AreEqual(expected, actual); } [Test] public void Next_BeyondLastYear_null() { var afterRecurrenceEnd = Instant.FromUtc(1980, 1, 1, 0, 0); var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.Next(afterRecurrenceEnd, Offset.Zero, Offset.Zero); Transition? expected = null; Assert.AreEqual(expected, actual); } [Test] public void PreviousOrSame_AfterLastYear() { var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.PreviousOrSame(Instant.MaxValue, Offset.Zero, Offset.Zero); Transition? expected = new Transition(Instant.FromUtc(1972, 1, 1, 0, 0), Offset.Zero); Assert.AreEqual(expected, actual); } [Test] public void PreviousOrSame_LastYear() { var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.PreviousOrSame(Instant.FromUtc(1971, 1, 1, 0, 0) - Duration.Epsilon, Offset.Zero, Offset.Zero); Transition? expected = new Transition(NodaConstants.UnixEpoch, Offset.Zero); Assert.AreEqual(expected, actual); } [Test] public void PreviousOrSameTwice_LastYear() { var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1973); Transition? actual = recurrence.PreviousOrSame(Instant.FromUtc(1972, 1, 1, 0, 0) - Duration.Epsilon, Offset.Zero, Offset.Zero); actual = recurrence.PreviousOrSame(actual.Value.Instant - Duration.Epsilon, Offset.Zero, Offset.Zero); Transition? expected = new Transition(NodaConstants.UnixEpoch, Offset.Zero); Assert.AreEqual(expected, actual); } [Test] public void PreviousOrSame_OnFirstYear_null() { // Transition is on January 2nd, but we're asking for January 1st. var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 2, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.PreviousOrSame(NodaConstants.UnixEpoch, Offset.Zero, Offset.Zero); Transition? expected = null; Assert.AreEqual(expected, actual); } [Test] public void PreviousOrSame_BeforeFirstYear_null() { var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.PreviousOrSame(NodaConstants.UnixEpoch - Duration.Epsilon, Offset.Zero, Offset.Zero); Transition? expected = null; Assert.AreEqual(expected, actual); } [Test] public void Next_ExcludesGivenInstant() { var january10thMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 10, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("x", Offset.Zero, january10thMidnight, 2000, 3000); var transition = Instant.FromUtc(2500, 1, 10, 0, 0); var next = recurrence.Next(transition, Offset.Zero, Offset.Zero); Assert.AreEqual(2501, next.Value.Instant.InUtc().Year); } [Test] public void PreviousOrSame_IncludesGivenInstant() { var january10thMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 10, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("x", Offset.Zero, january10thMidnight, 2000, 3000); var transition = Instant.FromUtc(2500, 1, 10, 0, 0); var next = recurrence.PreviousOrSame(transition, Offset.Zero, Offset.Zero); Assert.AreEqual(transition, next.Value.Instant); } [Test] public void TestSerialization() { var dio = DtzIoHelper.CreateNoStringPool(); var yearOffset = new ZoneYearOffset(TransitionMode.Utc, 10, 31, (int)IsoDayOfWeek.Wednesday, true, LocalTime.Midnight); var expected = new ZoneRecurrence("bob", Offset.Zero, yearOffset, 1971, 2009); dio.TestZoneRecurrence(expected); } [Test] public void IEquatable_Tests() { var yearOffset = new ZoneYearOffset(TransitionMode.Utc, 10, 31, (int)IsoDayOfWeek.Wednesday, true, LocalTime.Midnight); var value = new ZoneRecurrence("bob", Offset.Zero, yearOffset, 1971, 2009); var equalValue = new ZoneRecurrence("bob", Offset.Zero, yearOffset, 1971, 2009); var unequalValue = new ZoneRecurrence("foo", Offset.Zero, yearOffset, 1971, 2009); TestHelper.TestEqualsClass(value, equalValue, unequalValue); } [Test] public void December31st2400_MaxYear_UtcTransition() { // Each year, the transition is at the midnight at the *end* of December 31st... var yearOffset = new ZoneYearOffset(TransitionMode.Utc, 12, 31, 0, true, LocalTime.Midnight, true); // ... and the recurrence is valid for the whole of time var recurrence = new ZoneRecurrence("awkward", Offset.FromHours(1), yearOffset, GregorianYearMonthDayCalculator.MinGregorianYear, GregorianYearMonthDayCalculator.MaxGregorianYear); var next = recurrence.Next(Instant.FromUtc(9999, 6, 1, 0, 0), Offset.Zero, Offset.Zero); Assert.AreEqual(Instant.AfterMaxValue, next.Value.Instant); } [Test] public void December31st2400_AskAtNanoBeforeLastTransition() { // The transition occurs after the end of the maximum // Each year, the transition is at the midnight at the *end* of December 31st... var yearOffset = new ZoneYearOffset(TransitionMode.Utc, 12, 31, 0, true, LocalTime.Midnight, true); // ... and the recurrence is valid for the whole of time var recurrence = new ZoneRecurrence("awkward", Offset.FromHours(1), yearOffset, 1, 5000); // We can find the final transition var finalTransition = Instant.FromUtc(5001, 1, 1, 0, 0); var next = recurrence.Next(finalTransition - Duration.Epsilon, Offset.Zero, Offset.Zero); Transition? expected = new Transition(finalTransition, Offset.FromHours(1)); Assert.AreEqual(expected, next); // But we correctly reject anything after that Assert.IsNull(recurrence.Next(finalTransition, Offset.Zero, Offset.Zero)); } } }
BenJenkinson/nodatime
src/NodaTime.Test/TimeZones/ZoneRecurrenceTest.cs
C#
apache-2.0
9,951
/* * Copyright 2016 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.channel.epoll; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.testsuite.transport.TestsuitePermutation; import io.netty.testsuite.transport.socket.SocketConnectTest; import java.util.List; public class EpollSocketConnectTest extends SocketConnectTest { @Override protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() { return EpollSocketTestPermutation.INSTANCE.socketWithoutFastOpen(); } }
johnou/netty
transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketConnectTest.java
Java
apache-2.0
1,165
package org.semanticweb.ontop.cli; import org.junit.Ignore; import org.junit.Test; public class OntopTest { @Test public void testOntopMainNoArgs(){ Ontop.main(); } @Test public void testOntopHelp(){ Ontop.main("help"); } @Test public void testOntopHelpMapping(){ Ontop.main("help", "mapping"); } @Test public void testOntopHelpMapping_ToR2rml(){ Ontop.main("help", "mapping", "to-r2rml"); } @Test public void testOntopHelpMapping_ToOBDA(){ Ontop.main("help", "mapping", "to-obda"); } @Test public void testOntopHelpMapping_Prettify(){ Ontop.main("help", "mapping", "pretty-r2rml"); } @Test public void testOntopMissingCommand (){ String[] argv = { "-m", "/Users/xiao/Projects/npd-benchmark/mappings/postgres/no-spatial/npd-v2-ql_a_postgres.obda", "-t", "/Users/xiao/Projects/npd-benchmark/ontology/vocabulary.owl", "-f", "turtle", "-o", "/tmp/npd", "--separate-files"}; Ontop.main(argv); } @Test public void testOntopMissingArgValues (){ String[] argv = { "materialize", "-m", "-t", "/Users/xiao/Projects/npd-benchmark/ontology/vocabulary.owl", "-f", "turtle", "-o", "/tmp/npd", "--separate-files"}; Ontop.main(argv); } @Test public void testOntopMissingRequiredArg (){ String[] argv = { "materialize", "-t", "/Users/xiao/Projects/npd-benchmark/ontology/vocabulary.owl", "-f", "turtle", "-o", "/tmp/npd", "--separate-files"}; Ontop.main(argv); } }
eschwert/ontop
ontop-cli/src/test/java/org/semanticweb/ontop/cli/OntopTest.java
Java
apache-2.0
1,665
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.RQName.Nodes; namespace Microsoft.VisualStudio.LanguageServices.Implementation.RQName { internal static class RQNodeBuilder { /// <summary> /// Builds the RQName for a given symbol. /// </summary> /// <returns>The node if it could be created, otherwise null</returns> public static UnresolvedRQNode Build(ISymbol symbol, bool buildForPublicAPIs = false) { // TODO(davip): Is buildForPublicAPIs necessary now? switch (symbol.Kind) { case SymbolKind.Namespace: return BuildNamespace(symbol as INamespaceSymbol); case SymbolKind.NamedType: return BuildNamedType(symbol as INamedTypeSymbol); case SymbolKind.Method: return BuildMethod(symbol as IMethodSymbol, buildForPublicAPIs); case SymbolKind.Field: return BuildField(symbol as IFieldSymbol); case SymbolKind.Event: return BuildEvent(symbol as IEventSymbol, buildForPublicAPIs); case SymbolKind.Property: return BuildProperty(symbol as IPropertySymbol, buildForPublicAPIs); default: return null; } } private static RQNamespace BuildNamespace(INamespaceSymbol @namespace) { return new RQNamespace(RQNodeBuilder.GetNameParts(@namespace)); } private static IList<string> GetNameParts(INamespaceSymbol @namespace) { var parts = new List<string>(); if (@namespace == null) { return parts; } while (!@namespace.IsGlobalNamespace) { parts.Add(@namespace.Name); @namespace = @namespace.ContainingNamespace; } parts.Reverse(); return parts; } private static RQUnconstructedType BuildNamedType(INamedTypeSymbol type) { // Anything that is a valid RQUnconstructed types is ALWAYS safe for public APIs if (type == null) { return null; } // Anonymous types are unsupported if (type.IsAnonymousType) { return null; } // the following types are supported for BuildType() used in signatures, but are not supported // for UnconstructedTypes if (type != type.ConstructedFrom || type.SpecialType == SpecialType.System_Void) { return null; } // make an RQUnconstructedType var namespaceNames = RQNodeBuilder.GetNameParts(@type.ContainingNamespace); var typeInfos = new List<RQUnconstructedTypeInfo>(); for (INamedTypeSymbol currentType = type; currentType != null; currentType = currentType.ContainingType) { typeInfos.Insert(0, new RQUnconstructedTypeInfo(currentType.Name, currentType.TypeParameters.Length)); } return new RQUnconstructedType(namespaceNames, typeInfos); } private static RQMember BuildField(IFieldSymbol symbol) { var containingType = BuildNamedType(symbol.ContainingType); if (containingType == null) { return null; } return new RQMemberVariable(containingType, symbol.Name); } private static RQProperty BuildProperty(IPropertySymbol symbol, bool buildForPublicAPIs) { RQMethodPropertyOrEventName name = symbol.IsIndexer ? RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryIndexerName() : RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryPropertyName(symbol.Name); if (symbol.ExplicitInterfaceImplementations.Any()) { if (symbol.ExplicitInterfaceImplementations.Length > 1) { return null; } name = new RQExplicitInterfaceMemberName( BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType as ITypeSymbol, buildForPublicAPIs), (RQOrdinaryMethodPropertyOrEventName)name); } var containingType = BuildNamedType(symbol.ContainingType); if (containingType == null) { return null; } var parameterList = BuildParameterList(symbol.Parameters, buildForPublicAPIs); return new RQProperty(containingType, name, typeParameterCount: 0, parameters: parameterList); } private static IList<RQParameter> BuildParameterList(ImmutableArray<IParameterSymbol> parameters, bool buildForPublicAPIs) { var parameterList = new List<RQParameter>(); foreach (var parameter in parameters) { var parameterType = BuildType(parameter.Type, buildForPublicAPIs); if (parameter.RefKind == RefKind.Out) { parameterList.Add(new RQOutParameter(parameterType)); } else if (parameter.RefKind == RefKind.Ref) { parameterList.Add(new RQRefParameter(parameterType)); } else { parameterList.Add(new RQNormalParameter(parameterType)); } } return parameterList; } private static RQEvent BuildEvent(IEventSymbol symbol, bool buildForPublicAPIs) { var containingType = BuildNamedType(symbol.ContainingType); if (containingType == null) { return null; } RQMethodPropertyOrEventName name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryEventName(symbol.Name); if (symbol.ExplicitInterfaceImplementations.Any()) { if (symbol.ExplicitInterfaceImplementations.Length > 1) { return null; } name = new RQExplicitInterfaceMemberName(BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType as ITypeSymbol, buildForPublicAPIs), (RQOrdinaryMethodPropertyOrEventName)name); } return new RQEvent(containingType, name); } private static RQMethod BuildMethod(IMethodSymbol symbol, bool buildForPublicAPIs) { if (symbol.MethodKind == MethodKind.UserDefinedOperator || symbol.MethodKind == MethodKind.BuiltinOperator || symbol.MethodKind == MethodKind.EventAdd || symbol.MethodKind == MethodKind.EventRemove || symbol.MethodKind == MethodKind.PropertySet || symbol.MethodKind == MethodKind.PropertyGet) { return null; } RQMethodPropertyOrEventName name; if (symbol.MethodKind == MethodKind.Constructor) { name = RQOrdinaryMethodPropertyOrEventName.CreateConstructorName(); } else if (symbol.MethodKind == MethodKind.Destructor) { name = RQOrdinaryMethodPropertyOrEventName.CreateDestructorName(); } else { name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryMethodName(symbol.Name); } if (symbol.ExplicitInterfaceImplementations.Any()) { if (symbol.ExplicitInterfaceImplementations.Length > 1) { return null; } name = new RQExplicitInterfaceMemberName(BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType as ITypeSymbol, buildForPublicAPIs), (RQOrdinaryMethodPropertyOrEventName)name); } var containingType = BuildNamedType(symbol.ContainingType); if (containingType == null) { return null; } var typeParamCount = symbol.TypeParameters.Length; var parameterList = BuildParameterList(symbol.Parameters, buildForPublicAPIs); return new RQMethod(containingType, name, typeParamCount, parameterList); } private static RQType BuildType(ITypeSymbol symbol, bool buildForPublicAPIs) { if (symbol.IsAnonymousType) { return null; } if (symbol.SpecialType == SpecialType.System_Void) { return RQVoidType.Singleton; } else if (symbol.TypeKind == TypeKind.Pointer) { return new RQPointerType(BuildType((symbol as IPointerTypeSymbol).PointedAtType, buildForPublicAPIs)); } else if (symbol.TypeKind == TypeKind.Array) { return new RQArrayType((symbol as IArrayTypeSymbol).Rank, BuildType((symbol as IArrayTypeSymbol).ElementType, buildForPublicAPIs)); } else if (symbol.TypeKind == TypeKind.TypeParameter) { return new RQTypeVariableType(symbol.Name); } else if (symbol.TypeKind == TypeKind.Unknown) { return new RQErrorType(symbol.Name); } else if (symbol.TypeKind == TypeKind.Dynamic) { if (buildForPublicAPIs) { var objectType = new RQUnconstructedType(new[] { "System" }, new[] { new RQUnconstructedTypeInfo("Object", 0) }); return new RQConstructedType(objectType, Array.Empty<RQType>()); } else { return RQDynamicType.Singleton; } } else if (symbol.Kind == SymbolKind.NamedType || symbol.Kind == SymbolKind.ErrorType) { var namedTypeSymbol = symbol as INamedTypeSymbol; var definingType = namedTypeSymbol.ConstructedFrom != null ? namedTypeSymbol.ConstructedFrom : namedTypeSymbol; var typeChain = new List<INamedTypeSymbol>(); var type = namedTypeSymbol; typeChain.Add(namedTypeSymbol); while (type.ContainingType != null) { type = type.ContainingType; typeChain.Add(type); } typeChain.Reverse(); var typeArgumentList = new List<RQType>(); foreach (var entry in typeChain) { foreach (var typeArgument in entry.TypeArguments) { typeArgumentList.Add(BuildType(typeArgument, buildForPublicAPIs)); } } var containingType = BuildNamedType(definingType); if (containingType == null) { return null; } return new RQConstructedType(containingType, typeArgumentList); } else { return null; } } } }
marksantos/roslyn
src/VisualStudio/Core/Def/Implementation/RQName/RQNodeBuilder.cs
C#
apache-2.0
11,800
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package perffmwk.samples; public class SampleStatException extends hydra.HydraRuntimeException { public SampleStatException(String s) { super(s); } public SampleStatException(String s,Exception e) { super(s,e); } public SampleStatException(String s,Throwable e) { super(s,e); } }
SnappyDataInc/snappy-store
tests/core/src/main/java/perffmwk/samples/SampleStatException.java
Java
apache-2.0
997
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper; import org.apache.lucene.document.InetAddressPoint; import org.apache.lucene.index.IndexableField; import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.network.InetAddresses; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import java.io.IOException; import java.net.InetAddress; import java.util.Arrays; import java.util.HashSet; import java.util.Locale; import static org.elasticsearch.index.query.RangeQueryBuilder.GT_FIELD; import static org.elasticsearch.index.query.RangeQueryBuilder.GTE_FIELD; import static org.elasticsearch.index.query.RangeQueryBuilder.LT_FIELD; import static org.elasticsearch.index.query.RangeQueryBuilder.LTE_FIELD; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsString; public class RangeFieldMapperTests extends AbstractNumericFieldMapperTestCase { private static String FROM_DATE = "2016-10-31"; private static String TO_DATE = "2016-11-01 20:00:00"; private static String FROM_IP = "::ffff:c0a8:107"; private static String TO_IP = "2001:db8::"; private static int FROM = 5; private static String FROM_STR = FROM + ""; private static int TO = 10; private static String TO_STR = TO + ""; private static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"; @Override protected void setTypeList() { TYPES = new HashSet<>(Arrays.asList("date_range", "ip_range", "float_range", "double_range", "integer_range", "long_range")); } private Object getFrom(String type) { if (type.equals("date_range")) { return FROM_DATE; } else if (type.equals("ip_range")) { return FROM_IP; } return random().nextBoolean() ? FROM : FROM_STR; } private String getFromField() { return random().nextBoolean() ? GT_FIELD.getPreferredName() : GTE_FIELD.getPreferredName(); } private String getToField() { return random().nextBoolean() ? LT_FIELD.getPreferredName() : LTE_FIELD.getPreferredName(); } private Object getTo(String type) { if (type.equals("date_range")) { return TO_DATE; } else if (type.equals("ip_range")) { return TO_IP; } return random().nextBoolean() ? TO : TO_STR; } private Object getMax(String type) { if (type.equals("date_range") || type.equals("long_range")) { return Long.MAX_VALUE; } else if (type.equals("ip_range")) { return InetAddressPoint.MAX_VALUE; } else if (type.equals("integer_range")) { return Integer.MAX_VALUE; } else if (type.equals("float_range")) { return Float.POSITIVE_INFINITY; } return Double.POSITIVE_INFINITY; } @Override public void doTestDefaults(String type) throws Exception { XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", type); if (type.equals("date_range")) { mapping = mapping.field("format", DATE_FORMAT); } mapping = mapping.endObject().endObject().endObject().endObject(); DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping.string())); assertEquals(mapping.string(), mapper.mappingSource().toString()); ParsedDocument doc = mapper.parse(SourceToParse.source("test", "type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("field") .field(getFromField(), getFrom(type)) .field(getToField(), getTo(type)) .endObject() .endObject().bytes(), XContentType.JSON)); IndexableField[] fields = doc.rootDoc().getFields("field"); assertEquals(1, fields.length); IndexableField pointField = fields[0]; assertEquals(2, pointField.fieldType().pointDimensionCount()); assertFalse(pointField.fieldType().stored()); } @Override protected void doTestNotIndexed(String type) throws Exception { XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", type).field("index", false); if (type.equals("date_range")) { mapping = mapping.field("format", DATE_FORMAT); } mapping = mapping.endObject().endObject().endObject().endObject(); DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping.string())); assertEquals(mapping.string(), mapper.mappingSource().toString()); ParsedDocument doc = mapper.parse(SourceToParse.source("test", "type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("field") .field(getFromField(), getFrom(type)) .field(getToField(), getTo(type)) .endObject() .endObject().bytes(), XContentType.JSON)); IndexableField[] fields = doc.rootDoc().getFields("field"); assertEquals(0, fields.length); } @Override protected void doTestNoDocValues(String type) throws Exception { XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", type).field("doc_values", false); if (type.equals("date_range")) { mapping = mapping.field("format", DATE_FORMAT); } mapping = mapping.endObject().endObject().endObject().endObject(); DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping.string())); assertEquals(mapping.string(), mapper.mappingSource().toString()); ParsedDocument doc = mapper.parse(SourceToParse.source("test", "type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("field") .field(getFromField(), getFrom(type)) .field(getToField(), getTo(type)) .endObject() .endObject().bytes(), XContentType.JSON)); IndexableField[] fields = doc.rootDoc().getFields("field"); assertEquals(1, fields.length); IndexableField pointField = fields[0]; assertEquals(2, pointField.fieldType().pointDimensionCount()); } @Override protected void doTestStore(String type) throws Exception { XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", type).field("store", true); if (type.equals("date_range")) { mapping = mapping.field("format", DATE_FORMAT); } mapping = mapping.endObject().endObject().endObject().endObject(); DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping.string())); assertEquals(mapping.string(), mapper.mappingSource().toString()); ParsedDocument doc = mapper.parse(SourceToParse.source("test", "type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("field") .field(getFromField(), getFrom(type)) .field(getToField(), getTo(type)) .endObject() .endObject().bytes(), XContentType.JSON)); IndexableField[] fields = doc.rootDoc().getFields("field"); assertEquals(2, fields.length); IndexableField pointField = fields[0]; assertEquals(2, pointField.fieldType().pointDimensionCount()); IndexableField storedField = fields[1]; assertTrue(storedField.fieldType().stored()); String strVal = "5"; if (type.equals("date_range")) { strVal = "1477872000000"; } else if (type.equals("ip_range")) { strVal = InetAddresses.toAddrString(InetAddresses.forString("192.168.1.7")) + " : " + InetAddresses.toAddrString(InetAddresses.forString("2001:db8:0:0:0:0:0:0")); } assertThat(storedField.stringValue(), containsString(strVal)); } @Override public void doTestCoerce(String type) throws IOException { XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", type); if (type.equals("date_range")) { mapping = mapping.field("format", DATE_FORMAT); } mapping = mapping.endObject().endObject().endObject().endObject(); DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping.string())); assertEquals(mapping.string(), mapper.mappingSource().toString()); ParsedDocument doc = mapper.parse(SourceToParse.source("test", "type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("field") .field(getFromField(), getFrom(type)) .field(getToField(), getTo(type)) .endObject() .endObject().bytes(), XContentType.JSON)); IndexableField[] fields = doc.rootDoc().getFields("field"); assertEquals(1, fields.length); IndexableField pointField = fields[0]; assertEquals(2, pointField.fieldType().pointDimensionCount()); mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", type).field("coerce", false).endObject().endObject() .endObject().endObject(); DocumentMapper mapper2 = parser.parse("type", new CompressedXContent(mapping.string())); assertEquals(mapping.string(), mapper2.mappingSource().toString()); ThrowingRunnable runnable = () -> mapper2.parse(SourceToParse.source("test", "type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("field") .field(getFromField(), "5.2") .field(getToField(), "10") .endObject() .endObject().bytes(), XContentType.JSON)); MapperParsingException e = expectThrows(MapperParsingException.class, runnable); assertThat(e.getCause().getMessage(), anyOf(containsString("passed as String"), containsString("failed to parse date"), containsString("is not an IP string literal"))); } @Override protected void doTestNullValue(String type) throws IOException { XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", type).field("store", true); if (type.equals("date_range")) { mapping = mapping.field("format", DATE_FORMAT); } mapping = mapping.endObject().endObject().endObject().endObject(); DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping.string())); assertEquals(mapping.string(), mapper.mappingSource().toString()); // test null value for min and max ParsedDocument doc = mapper.parse(SourceToParse.source("test", "type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("field") .nullField(getFromField()) .nullField(getToField()) .endObject() .endObject().bytes(), XContentType.JSON)); assertEquals(2, doc.rootDoc().getFields("field").length); IndexableField[] fields = doc.rootDoc().getFields("field"); IndexableField storedField = fields[1]; String expected = type.equals("ip_range") ? InetAddresses.toAddrString((InetAddress)getMax(type)) : getMax(type) +""; assertThat(storedField.stringValue(), containsString(expected)); // test null max value doc = mapper.parse(SourceToParse.source("test", "type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("field") .field(getFromField(), getFrom(type)) .nullField(getToField()) .endObject() .endObject().bytes(), XContentType.JSON)); fields = doc.rootDoc().getFields("field"); assertEquals(2, fields.length); IndexableField pointField = fields[0]; assertEquals(2, pointField.fieldType().pointDimensionCount()); assertFalse(pointField.fieldType().stored()); storedField = fields[1]; assertTrue(storedField.fieldType().stored()); String strVal = "5"; if (type.equals("date_range")) { strVal = "1477872000000"; } else if (type.equals("ip_range")) { strVal = InetAddresses.toAddrString(InetAddresses.forString("192.168.1.7")) + " : " + InetAddresses.toAddrString(InetAddresses.forString("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")); } assertThat(storedField.stringValue(), containsString(strVal)); } public void testNoBounds() throws Exception { for (String type : TYPES) { doTestNoBounds(type); } } public void doTestNoBounds(String type) throws IOException { XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", type).field("store", true); if (type.equals("date_range")) { mapping = mapping.field("format", DATE_FORMAT); } mapping = mapping.endObject().endObject().endObject().endObject(); DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping.string())); assertEquals(mapping.string(), mapper.mappingSource().toString()); // test no bounds specified ParsedDocument doc = mapper.parse(SourceToParse.source("test", "type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("field") .endObject() .endObject().bytes(), XContentType.JSON)); IndexableField[] fields = doc.rootDoc().getFields("field"); assertEquals(2, fields.length); IndexableField pointField = fields[0]; assertEquals(2, pointField.fieldType().pointDimensionCount()); assertFalse(pointField.fieldType().stored()); IndexableField storedField = fields[1]; assertTrue(storedField.fieldType().stored()); String expected = type.equals("ip_range") ? InetAddresses.toAddrString((InetAddress)getMax(type)) : getMax(type) +""; assertThat(storedField.stringValue(), containsString(expected)); } public void testIllegalArguments() throws Exception { XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", RangeFieldMapper.RangeType.INTEGER.name) .field("format", DATE_FORMAT).endObject().endObject().endObject().endObject(); ThrowingRunnable runnable = () -> parser.parse("type", new CompressedXContent(mapping.string())); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, runnable); assertThat(e.getMessage(), containsString("should not define a dateTimeFormatter")); } public void testSerializeDefaults() throws Exception { for (String type : TYPES) { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", type).endObject().endObject() .endObject().endObject().string(); DocumentMapper docMapper = parser.parse("type", new CompressedXContent(mapping)); RangeFieldMapper mapper = (RangeFieldMapper) docMapper.root().getMapper("field"); XContentBuilder builder = XContentFactory.jsonBuilder().startObject(); mapper.doXContentBody(builder, true, ToXContent.EMPTY_PARAMS); String got = builder.endObject().string(); // if type is date_range we check that the mapper contains the default format and locale // otherwise it should not contain a locale or format assertTrue(got, got.contains("\"format\":\"strict_date_optional_time||epoch_millis\"") == type.equals("date_range")); assertTrue(got, got.contains("\"locale\":" + "\"" + Locale.ROOT + "\"") == type.equals("date_range")); } } }
nezirus/elasticsearch
core/src/test/java/org/elasticsearch/index/mapper/RangeFieldMapperTests.java
Java
apache-2.0
17,540
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver15; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFActionPushVlanVer15 implements OFActionPushVlan { private static final Logger logger = LoggerFactory.getLogger(OFActionPushVlanVer15.class); // version: 1.5 final static byte WIRE_VERSION = 6; final static int LENGTH = 8; private final static EthType DEFAULT_ETHERTYPE = EthType.NONE; // OF message fields private final EthType ethertype; // // Immutable default instance final static OFActionPushVlanVer15 DEFAULT = new OFActionPushVlanVer15( DEFAULT_ETHERTYPE ); // package private constructor - used by readers, builders, and factory OFActionPushVlanVer15(EthType ethertype) { if(ethertype == null) { throw new NullPointerException("OFActionPushVlanVer15: property ethertype cannot be null"); } this.ethertype = ethertype; } // Accessors for OF message fields @Override public OFActionType getType() { return OFActionType.PUSH_VLAN; } @Override public EthType getEthertype() { return ethertype; } @Override public OFVersion getVersion() { return OFVersion.OF_15; } public OFActionPushVlan.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFActionPushVlan.Builder { final OFActionPushVlanVer15 parentMessage; // OF message fields private boolean ethertypeSet; private EthType ethertype; BuilderWithParent(OFActionPushVlanVer15 parentMessage) { this.parentMessage = parentMessage; } @Override public OFActionType getType() { return OFActionType.PUSH_VLAN; } @Override public EthType getEthertype() { return ethertype; } @Override public OFActionPushVlan.Builder setEthertype(EthType ethertype) { this.ethertype = ethertype; this.ethertypeSet = true; return this; } @Override public OFVersion getVersion() { return OFVersion.OF_15; } @Override public OFActionPushVlan build() { EthType ethertype = this.ethertypeSet ? this.ethertype : parentMessage.ethertype; if(ethertype == null) throw new NullPointerException("Property ethertype must not be null"); // return new OFActionPushVlanVer15( ethertype ); } } static class Builder implements OFActionPushVlan.Builder { // OF message fields private boolean ethertypeSet; private EthType ethertype; @Override public OFActionType getType() { return OFActionType.PUSH_VLAN; } @Override public EthType getEthertype() { return ethertype; } @Override public OFActionPushVlan.Builder setEthertype(EthType ethertype) { this.ethertype = ethertype; this.ethertypeSet = true; return this; } @Override public OFVersion getVersion() { return OFVersion.OF_15; } // @Override public OFActionPushVlan build() { EthType ethertype = this.ethertypeSet ? this.ethertype : DEFAULT_ETHERTYPE; if(ethertype == null) throw new NullPointerException("Property ethertype must not be null"); return new OFActionPushVlanVer15( ethertype ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFActionPushVlan> { @Override public OFActionPushVlan readFrom(ByteBuf bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property type == 17 short type = bb.readShort(); if(type != (short) 0x11) throw new OFParseError("Wrong type: Expected=OFActionType.PUSH_VLAN(17), got="+type); int length = U16.f(bb.readShort()); if(length != 8) throw new OFParseError("Wrong length: Expected=8(8), got="+length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); EthType ethertype = EthType.read2Bytes(bb); // pad: 2 bytes bb.skipBytes(2); OFActionPushVlanVer15 actionPushVlanVer15 = new OFActionPushVlanVer15( ethertype ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", actionPushVlanVer15); return actionPushVlanVer15; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFActionPushVlanVer15Funnel FUNNEL = new OFActionPushVlanVer15Funnel(); static class OFActionPushVlanVer15Funnel implements Funnel<OFActionPushVlanVer15> { private static final long serialVersionUID = 1L; @Override public void funnel(OFActionPushVlanVer15 message, PrimitiveSink sink) { // fixed value property type = 17 sink.putShort((short) 0x11); // fixed value property length = 8 sink.putShort((short) 0x8); message.ethertype.putTo(sink); // skip pad (2 bytes) } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFActionPushVlanVer15> { @Override public void write(ByteBuf bb, OFActionPushVlanVer15 message) { // fixed value property type = 17 bb.writeShort((short) 0x11); // fixed value property length = 8 bb.writeShort((short) 0x8); message.ethertype.write2Bytes(bb); // pad: 2 bytes bb.writeZero(2); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFActionPushVlanVer15("); b.append("ethertype=").append(ethertype); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFActionPushVlanVer15 other = (OFActionPushVlanVer15) obj; if (ethertype == null) { if (other.ethertype != null) return false; } else if (!ethertype.equals(other.ethertype)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((ethertype == null) ? 0 : ethertype.hashCode()); return result; } }
floodlight/loxigen-artifacts
openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver15/OFActionPushVlanVer15.java
Java
apache-2.0
8,632
require_relative '../../lib/cdo/pegasus' require 'minitest/autorun' class ObjectTest < Minitest::Unit::TestCase def test_nil_or_empty assert nil.nil_or_empty? assert ''.nil_or_empty? assert [].nil_or_empty? assert ({}).nil_or_empty? assert !('a'.nil_or_empty?) assert !([1].nil_or_empty?) assert !(({a: 1}).nil_or_empty?) end end
cloud3edu/code-dot-org-old
pegasus/test/test_object.rb
Ruby
apache-2.0
364
/** * @description Gruntfile that contains tasks to build, test and deploy a project. * * Configure all your tasks in the /tasks folder. * * For more help, see: http://gruntjs.com/getting-started */ module.exports = function(grunt) { 'use strict'; function loadConfig(path) { var glob = require('glob'); var object = {}; var key; glob.sync('*', {cwd: path}).forEach(function(option) { key = option.replace(/\.js$/, ''); object[key] = require(path + option); }); return object; } // Initial config var config = { pkg: grunt.file.readJSON('package.json') }; // Load tasks from tasks folder grunt.loadTasks('tasks'); grunt.util._.extend(config, loadConfig('./tasks/options/')); grunt.initConfig(config); require('load-grunt-tasks')(grunt); };
hanwb-code/predix
predix-angular-ui/Gruntfile.js
JavaScript
apache-2.0
877
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package com.amazonaws.util.awsclientgenerator.generators.cpp.rds; import com.amazonaws.util.awsclientgenerator.domainmodels.SdkFileEntry; import com.amazonaws.util.awsclientgenerator.domainmodels.codegeneration.ServiceModel; import com.amazonaws.util.awsclientgenerator.domainmodels.codegeneration.Shape; import com.amazonaws.util.awsclientgenerator.domainmodels.codegeneration.ShapeMember; import com.amazonaws.util.awsclientgenerator.domainmodels.codegeneration.cpp.CppViewHelper; import com.amazonaws.util.awsclientgenerator.generators.cpp.QueryCppClientGenerator; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import java.util.Set; import java.util.HashSet; public class RDSCppClientGenerator extends QueryCppClientGenerator { private static Set<String> opsThatHavePreSignedUrl = new HashSet<>(); static { opsThatHavePreSignedUrl.add("CopyDBClusterSnapshot"); opsThatHavePreSignedUrl.add("CreateDBCluster"); opsThatHavePreSignedUrl.add("CopyDBSnapshot"); opsThatHavePreSignedUrl.add("CreateDBInstanceReadReplica"); opsThatHavePreSignedUrl.add("StartDBInstanceAutomatedBackupsReplication"); } public RDSCppClientGenerator() throws Exception { super(); } @Override public SdkFileEntry[] generateSourceFiles(ServiceModel serviceModel) throws Exception { serviceModel.getMetadata().setHasPreSignedUrl(true); Shape sourceRegionShape = new Shape(); sourceRegionShape.setName("SourceRegion"); sourceRegionShape.setType("string"); sourceRegionShape.setReferenced(true); HashSet<String> sourceRegionReferencedBy = new HashSet<String>(); sourceRegionShape.setReferencedBy(sourceRegionReferencedBy); ShapeMember sourceRegionShapeMember = new ShapeMember(); sourceRegionShapeMember.setShape(sourceRegionShape); sourceRegionShapeMember.setDocumentation("If SourceRegion is specified, SDKs will generate pre-signed URLs and populate the pre-signed URL field."); serviceModel.getOperations().values().stream() .filter(operationEntry -> opsThatHavePreSignedUrl.contains(operationEntry.getName())) .forEach(operationEntry -> { operationEntry.setHasPreSignedUrl(true); operationEntry.getRequest().getShape().setHasPreSignedUrl(true); operationEntry.getRequest().getShape().getMembers().put(sourceRegionShape.getName(), sourceRegionShapeMember); sourceRegionShape.getReferencedBy().add(operationEntry.getRequest().getShape().getName()); }); return super.generateSourceFiles(serviceModel); } @Override protected SdkFileEntry generateClientHeaderFile(final ServiceModel serviceModel) throws Exception { Template template = velocityEngine.getTemplate("/com/amazonaws/util/awsclientgenerator/velocity/cpp/rds/RDSClientHeader.vm"); VelocityContext context = createContext(serviceModel); context.put("CppViewHelper", CppViewHelper.class); String fileName = String.format("include/aws/%s/%sClient.h", serviceModel.getMetadata().getProjectName(), serviceModel.getMetadata().getClassNamePrefix()); return makeFile(template, context, fileName, true); } @Override protected SdkFileEntry generateClientSourceFile(final ServiceModel serviceModel) throws Exception { Template template = velocityEngine.getTemplate("/com/amazonaws/util/awsclientgenerator/velocity/cpp/rds/RDSClientSource.vm"); VelocityContext context = createContext(serviceModel); context.put("CppViewHelper", CppViewHelper.class); String fileName = String.format("source/%sClient.cpp", serviceModel.getMetadata().getClassNamePrefix()); return makeFile(template, context, fileName, true); } }
awslabs/aws-sdk-cpp
code-generation/generator/src/main/java/com/amazonaws/util/awsclientgenerator/generators/cpp/rds/RDSCppClientGenerator.java
Java
apache-2.0
4,000
<!-- HTML header for doxygen 1.8.13--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <!--BEGIN PROJECT_NAME--><title>$projectname: $title</title><!--END PROJECT_NAME--> <!--BEGIN !PROJECT_NAME--><title>$title</title><!--END !PROJECT_NAME--> <link href="$relpath^tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="$relpath^jquery.js"></script> <script type="text/javascript" src="$relpath^dynsections.js"></script> $treeview $search $mathjax <link href="$relpath^$stylesheet" rel="stylesheet" type="text/css" /> $extrastylesheet </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <!--BEGIN TITLEAREA--> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <!--BEGIN PROJECT_LOGO--> <td id="projectlogo"><a href="http://www.eprosima.com"><img alt="Logo" src="$relpath^$projectlogo"/></a></td> <!--END PROJECT_LOGO--> <!--BEGIN PROJECT_NAME--> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">$projectname <!--BEGIN PROJECT_NUMBER-->&#160;<span id="projectnumber">$projectnumber</span><!--END PROJECT_NUMBER--> </div> <!--BEGIN PROJECT_BRIEF--><div id="projectbrief">$projectbrief</div><!--END PROJECT_BRIEF--> </td> <!--END PROJECT_NAME--> <!--BEGIN !PROJECT_NAME--> <!--BEGIN PROJECT_BRIEF--> <td style="padding-left: 0.5em;"> <div id="projectbrief">$projectbrief</div> </td> <!--END PROJECT_BRIEF--> <!--END !PROJECT_NAME--> <!--BEGIN DISABLE_INDEX--> <!--BEGIN SEARCHENGINE--> <td>$searchbox</td> <!--END SEARCHENGINE--> <!--END DISABLE_INDEX--> </tr> </tbody> </table> </div> <!--END TITLEAREA--> <!-- end header part -->
eProsima/Fast-DDS
utils/doxygen/pages/eprosima_header.html
HTML
apache-2.0
1,972
#!/usr/local/bin/python2 import os print "PID:",str(os.getpid()) while True: raw_input("press <RETURN> to open file") fh = open("/tmp/test.txt",'w') print "Opened /tmp/test.txt..." raw_input("press <RETURN> to close") fh.close()
rbprogrammer/advanced_python_topics
course-material/py2/solutions/13 File system control/fuser_t.py
Python
apache-2.0
256
import sys sys.path.insert(1, "../../../") import h2o import pandas as pd import statsmodels.api as sm def prostate(ip,port): # Log.info("Importing prostate.csv data...\n") h2o_data = h2o.upload_file(path=h2o.locate("smalldata/logreg/prostate.csv")) #prostate.summary() sm_data = pd.read_csv(h2o.locate("smalldata/logreg/prostate.csv")).as_matrix() sm_data_response = sm_data[:,1] sm_data_features = sm_data[:,2:] #Log.info(cat("B)H2O GLM (binomial) with parameters:\nX:", myX, "\nY:", myY, "\n")) h2o_glm = h2o.glm(y=h2o_data[1], x=h2o_data[2:], family="binomial", n_folds=10, alpha=[0.5]) h2o_glm.show() sm_glm = sm.GLM(endog=sm_data_response, exog=sm_data_features, family=sm.families.Binomial()).fit() assert abs(sm_glm.null_deviance - h2o_glm._model_json['output']['training_metrics']['null_deviance']) < 1e-5, "Expected null deviances to be the same" if __name__ == "__main__": h2o.run_test(sys.argv, prostate)
PawarPawan/h2o-v3
h2o-py/tests/testdir_algos/glm/pyunit_NOFEATURE_prostateGLM.py
Python
apache-2.0
956
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.vcloud.domain.network.nat.rules; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.CaseFormat; /** * The MappingMode element specifies how IP address mapping is implemented by the NAT service. */ public enum MappingMode { /** * the external IP address is specified in the ExternalIP element */ MANUAL, /** * the external IP address is assigned automatically */ AUTOMATIC, UNRECOGNIZED; public String value() { return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name()); } @Override public String toString() { return value(); } public static MappingMode fromValue(String mode) { try { return valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(mode, "mode"))); } catch (IllegalArgumentException e) { return UNRECOGNIZED; } } }
agentmilindu/stratos
dependencies/jclouds/apis/vcloud/1.8.1-stratos/src/main/java/org/jclouds/vcloud/domain/network/nat/rules/MappingMode.java
Java
apache-2.0
1,734
table.dataTable{border-left-width:0px !important}table.dataTable tr{border-left-width:0px}table.dataTable tr th:first-child,table.dataTable tr td:first-child{border-left:1px solid rgba(34, 36, 38, 0.15) !important}table.dataTable tr th{background-color:#f9fafb}table.dataTable tr td{background-color:white}table.dataTable tr th.dtfc-fixed-left,table.dataTable tr th.dtfc-fixed-right{z-index:1}div.dtfc-right-top-blocker{border-bottom:none !important}tr.dt-rowReorder-moving td.dtfc-fixed-left,tr.dt-rowReorder-moving td.dtfc-fixed-right{border-top:2px solid #888 !important;border-bottom:2px solid #888 !important}tr.dt-rowReorder-moving td.dtfc-fixed-left:first-child{border-left:2px solid #888 !important}tr.dt-rowReorder-moving td.dtfc-fixed-right:last-child{border-right:2px solid #888 !important}
phax/ph-oton
ph-oton-datatables/src/main/resources/datatables/FixedColumns-4.0.1/css/fixedColumns.semanticui.min.css
CSS
apache-2.0
802
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.runners.direct; import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkState; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isA; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.theInstance; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.util.UserCodeException; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link DoFnLifecycleManager}. */ @RunWith(JUnit4.class) public class DoFnLifecycleManagerTest { @Rule public ExpectedException thrown = ExpectedException.none(); private TestFn fn = new TestFn(); private DoFnLifecycleManager mgr = DoFnLifecycleManager.of(fn); @Test public void setupOnGet() throws Exception { TestFn obtained = (TestFn) mgr.get(); assertThat(obtained, not(theInstance(fn))); assertThat(obtained.setupCalled, is(true)); assertThat(obtained.teardownCalled, is(false)); } @Test public void getMultipleCallsSingleSetupCall() throws Exception { TestFn obtained = (TestFn) mgr.get(); TestFn secondObtained = (TestFn) mgr.get(); assertThat(obtained, theInstance(secondObtained)); assertThat(obtained.setupCalled, is(true)); assertThat(obtained.teardownCalled, is(false)); } @Test public void getMultipleThreadsDifferentInstances() throws Exception { CountDownLatch startSignal = new CountDownLatch(1); ExecutorService executor = Executors.newCachedThreadPool(); List<Future<TestFn>> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { futures.add(executor.submit(new GetFnCallable(mgr, startSignal))); } startSignal.countDown(); List<TestFn> fns = new ArrayList<>(); for (Future<TestFn> future : futures) { fns.add(future.get(1L, TimeUnit.SECONDS)); } for (TestFn fn : fns) { assertThat(fn.setupCalled, is(true)); int sameInstances = 0; for (TestFn otherFn : fns) { if (otherFn == fn) { sameInstances++; } } assertThat(sameInstances, equalTo(1)); } } @Test public void teardownOnRemove() throws Exception { TestFn obtained = (TestFn) mgr.get(); mgr.remove(); assertThat(obtained, not(theInstance(fn))); assertThat(obtained.setupCalled, is(true)); assertThat(obtained.teardownCalled, is(true)); assertThat(mgr.get(), not(Matchers.<DoFn<?, ?>>theInstance(obtained))); } @Test public void teardownThrowsRemoveThrows() throws Exception { TestFn obtained = (TestFn) mgr.get(); obtained.teardown(); thrown.expect(UserCodeException.class); thrown.expectCause(isA(IllegalStateException.class)); thrown.expectMessage("Cannot call teardown: already torn down"); mgr.remove(); } @Test public void teardownAllOnRemoveAll() throws Exception { CountDownLatch startSignal = new CountDownLatch(1); ExecutorService executor = Executors.newCachedThreadPool(); List<Future<TestFn>> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { futures.add(executor.submit(new GetFnCallable(mgr, startSignal))); } startSignal.countDown(); List<TestFn> fns = new ArrayList<>(); for (Future<TestFn> future : futures) { fns.add(future.get(1L, TimeUnit.SECONDS)); } mgr.removeAll(); for (TestFn fn : fns) { assertThat(fn.setupCalled, is(true)); assertThat(fn.teardownCalled, is(true)); } } @Test public void removeAndRemoveAllConcurrent() throws Exception { CountDownLatch startSignal = new CountDownLatch(1); ExecutorService executor = Executors.newCachedThreadPool(); List<Future<TestFn>> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { futures.add(executor.submit(new GetFnCallable(mgr, startSignal))); } startSignal.countDown(); List<TestFn> fns = new ArrayList<>(); for (Future<TestFn> future : futures) { fns.add(future.get(1L, TimeUnit.SECONDS)); } CountDownLatch removeSignal = new CountDownLatch(1); List<Future<Void>> removeFutures = new ArrayList<>(); for (int i = 0; i < 5; i++) { // These will reuse the threads used in the GetFns removeFutures.add(executor.submit(new TeardownFnCallable(mgr, removeSignal))); } removeSignal.countDown(); assertThat(mgr.removeAll(), Matchers.emptyIterable()); for (Future<Void> removed : removeFutures) { // Should not have thrown an exception. removed.get(); } for (TestFn fn : fns) { assertThat(fn.setupCalled, is(true)); assertThat(fn.teardownCalled, is(true)); } } private static class GetFnCallable implements Callable<TestFn> { private final DoFnLifecycleManager mgr; private final CountDownLatch startSignal; private GetFnCallable(DoFnLifecycleManager mgr, CountDownLatch startSignal) { this.mgr = mgr; this.startSignal = startSignal; } @Override public TestFn call() throws Exception { startSignal.await(); return (TestFn) mgr.get(); } } private static class TeardownFnCallable implements Callable<Void> { private final DoFnLifecycleManager mgr; private final CountDownLatch startSignal; private TeardownFnCallable(DoFnLifecycleManager mgr, CountDownLatch startSignal) { this.mgr = mgr; this.startSignal = startSignal; } @Override public Void call() throws Exception { startSignal.await(); // Will throw an exception if the TestFn has already been removed from this thread mgr.remove(); return null; } } private static class TestFn extends DoFn<Object, Object> { boolean setupCalled = false; boolean teardownCalled = false; @Setup public void setup() { checkState(!setupCalled, "Cannot call setup: already set up"); checkState(!teardownCalled, "Cannot call setup: already torn down"); setupCalled = true; } @ProcessElement public void processElement(ProcessContext c) throws Exception {} @Teardown public void teardown() { checkState(setupCalled, "Cannot call teardown: not set up"); checkState(!teardownCalled, "Cannot call teardown: already torn down"); teardownCalled = true; } } }
RyanSkraba/beam
runners/direct-java/src/test/java/org/apache/beam/runners/direct/DoFnLifecycleManagerTest.java
Java
apache-2.0
7,609
<?php namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2; use un\unece\uncefact\data\specification\UnqualifiedDataTypesSchemaModule\_2; /** * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2 * @xmlType CodeType * @xmlName DirectionCodeType * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\DirectionCodeType */ class DirectionCodeType extends _2\CodeType { } // end class DirectionCodeType
intuit/QuickBooks-V3-PHP-SDK
src/XSD2PHP/test/data/expected/ubl2.0/oasis/names/specification/ubl/schema/xsd/CommonBasicComponents_2/DirectionCodeType.php
PHP
apache-2.0
477
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2017 the original author or authors. */ package org.assertj.core.api.throwable; import org.assertj.core.api.ThrowableAssert; import org.assertj.core.api.ThrowableAssertBaseTest; import static org.mockito.Mockito.verify; /** * Tests for <code>{@link ThrowableAssert#hasMessageEndingWith(String)}</code>. * * @author Joel Costigliola */ public class ThrowableAssert_hasMessageEndingWith_Test extends ThrowableAssertBaseTest { @Override protected ThrowableAssert invoke_api_method() { return assertions.hasMessageEndingWith("age"); } @Override protected void verify_internal_effects() { verify(throwables).assertHasMessageEndingWith(getInfo(assertions), getActual(assertions), "age"); } }
ChrisCanCompute/assertj-core
src/test/java/org/assertj/core/api/throwable/ThrowableAssert_hasMessageEndingWith_Test.java
Java
apache-2.0
1,285
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.httpd.rpc.account; import com.google.gerrit.common.errors.NameAlreadyUsedException; import com.google.gerrit.common.errors.PermissionDeniedException; import com.google.gerrit.httpd.rpc.Handler; import com.google.gerrit.reviewdb.Account; import com.google.gerrit.reviewdb.AccountGroup; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.account.PerformCreateGroup; import com.google.gwtorm.client.OrmException; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import java.util.Collections; class CreateGroup extends Handler<AccountGroup.Id> { interface Factory { CreateGroup create(String groupName); } private final PerformCreateGroup.Factory performCreateGroupFactory; private final IdentifiedUser user; private final String groupName; @Inject CreateGroup(final PerformCreateGroup.Factory performCreateGroupFactory, final IdentifiedUser user, @Assisted final String groupName) { this.performCreateGroupFactory = performCreateGroupFactory; this.user = user; this.groupName = groupName; } @Override public AccountGroup.Id call() throws OrmException, NameAlreadyUsedException, PermissionDeniedException { final PerformCreateGroup performCreateGroup = performCreateGroupFactory.create(); final Account.Id me = user.getAccountId(); return performCreateGroup.createGroup(groupName, null, false, null, Collections.singleton(me), null); } }
duboisf/gerrit
gerrit-httpd/src/main/java/com/google/gerrit/httpd/rpc/account/CreateGroup.java
Java
apache-2.0
2,100
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_CXX11_TENSOR_TENSOR_LAYOUT_SWAP_H #define EIGEN_CXX11_TENSOR_TENSOR_LAYOUT_SWAP_H namespace Eigen { /** \class TensorLayoutSwap * \ingroup CXX11_Tensor_Module * * \brief Swap the layout from col-major to row-major, or row-major * to col-major, and invert the order of the dimensions. * * Beware: the dimensions are reversed by this operation. If you want to * preserve the ordering of the dimensions, you need to combine this * operation with a shuffle. * * \example: * Tensor<float, 2, ColMajor> input(2, 4); * Tensor<float, 2, RowMajor> output = input.swap_layout(); * eigen_assert(output.dimension(0) == 4); * eigen_assert(output.dimension(1) == 2); * * array<int, 2> shuffle(1, 0); * output = input.swap_layout().shuffle(shuffle); * eigen_assert(output.dimension(0) == 2); * eigen_assert(output.dimension(1) == 4); * */ namespace internal { template<typename XprType> struct traits<TensorLayoutSwapOp<XprType> > : public traits<XprType> { typedef typename XprType::Scalar Scalar; typedef traits<XprType> XprTraits; typedef typename XprTraits::StorageKind StorageKind; typedef typename XprTraits::Index Index; typedef typename XprType::Nested Nested; typedef typename remove_reference<Nested>::type _Nested; static const int NumDimensions = traits<XprType>::NumDimensions; static const int Layout = (traits<XprType>::Layout == ColMajor) ? RowMajor : ColMajor; typedef typename XprTraits::PointerType PointerType; }; template<typename XprType> struct eval<TensorLayoutSwapOp<XprType>, Eigen::Dense> { typedef const TensorLayoutSwapOp<XprType>& type; }; template<typename XprType> struct nested<TensorLayoutSwapOp<XprType>, 1, typename eval<TensorLayoutSwapOp<XprType> >::type> { typedef TensorLayoutSwapOp<XprType> type; }; } // end namespace internal template<typename XprType> class TensorLayoutSwapOp : public TensorBase<TensorLayoutSwapOp<XprType>, WriteAccessors> { public: typedef typename Eigen::internal::traits<TensorLayoutSwapOp>::Scalar Scalar; typedef typename Eigen::NumTraits<Scalar>::Real RealScalar; typedef typename internal::remove_const<typename XprType::CoeffReturnType>::type CoeffReturnType; typedef typename Eigen::internal::nested<TensorLayoutSwapOp>::type Nested; typedef typename Eigen::internal::traits<TensorLayoutSwapOp>::StorageKind StorageKind; typedef typename Eigen::internal::traits<TensorLayoutSwapOp>::Index Index; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorLayoutSwapOp(const XprType& expr) : m_xpr(expr) {} EIGEN_DEVICE_FUNC const typename internal::remove_all<typename XprType::Nested>::type& expression() const { return m_xpr; } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorLayoutSwapOp& operator = (const TensorLayoutSwapOp& other) { typedef TensorAssignOp<TensorLayoutSwapOp, const TensorLayoutSwapOp> Assign; Assign assign(*this, other); internal::TensorExecutor<const Assign, DefaultDevice>::run(assign, DefaultDevice()); return *this; } template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorLayoutSwapOp& operator = (const OtherDerived& other) { typedef TensorAssignOp<TensorLayoutSwapOp, const OtherDerived> Assign; Assign assign(*this, other); internal::TensorExecutor<const Assign, DefaultDevice>::run(assign, DefaultDevice()); return *this; } protected: typename XprType::Nested m_xpr; }; // Eval as rvalue template<typename ArgType, typename Device> struct TensorEvaluator<const TensorLayoutSwapOp<ArgType>, Device> { typedef TensorLayoutSwapOp<ArgType> XprType; typedef typename XprType::Index Index; static const int NumDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value; typedef DSizes<Index, NumDims> Dimensions; enum { IsAligned = TensorEvaluator<ArgType, Device>::IsAligned, PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess, BlockAccess = false, PreferBlockAccess = false, Layout = (static_cast<int>(TensorEvaluator<ArgType, Device>::Layout) == static_cast<int>(ColMajor)) ? RowMajor : ColMajor, CoordAccess = false, // to be implemented RawAccess = TensorEvaluator<ArgType, Device>::RawAccess }; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : m_impl(op.expression(), device) { for(int i = 0; i < NumDims; ++i) { m_dimensions[i] = m_impl.dimensions()[NumDims-1-i]; } } typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(CoeffReturnType* data) { return m_impl.evalSubExprsIfNeeded(data); } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void cleanup() { m_impl.cleanup(); } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_impl.coeff(index); } template<int LoadMode> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const { return m_impl.template packet<LoadMode>(index); } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { return m_impl.costPerCoeff(vectorized); } EIGEN_DEVICE_FUNC typename Eigen::internal::traits<XprType>::PointerType data() const { return m_impl.data(); } const TensorEvaluator<ArgType, Device>& impl() const { return m_impl; } protected: TensorEvaluator<ArgType, Device> m_impl; Dimensions m_dimensions; }; // Eval as lvalue template<typename ArgType, typename Device> struct TensorEvaluator<TensorLayoutSwapOp<ArgType>, Device> : public TensorEvaluator<const TensorLayoutSwapOp<ArgType>, Device> { typedef TensorEvaluator<const TensorLayoutSwapOp<ArgType>, Device> Base; typedef TensorLayoutSwapOp<ArgType> XprType; enum { IsAligned = TensorEvaluator<ArgType, Device>::IsAligned, PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess, BlockAccess = false, PreferBlockAccess = false, Layout = (static_cast<int>(TensorEvaluator<ArgType, Device>::Layout) == static_cast<int>(ColMajor)) ? RowMajor : ColMajor, CoordAccess = false // to be implemented }; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : Base(op, device) { } typedef typename XprType::Index Index; typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) { return this->m_impl.coeffRef(index); } template <int StoreMode> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writePacket(Index index, const PacketReturnType& x) { this->m_impl.template writePacket<StoreMode>(index, x); } }; } // end namespace Eigen #endif // EIGEN_CXX11_TENSOR_TENSOR_LAYOUT_SWAP_H
ColinGilbert/noobwerkz-engine
engine/lib/eigen/unsupported/Eigen/CXX11/src/Tensor/TensorLayoutSwap.h
C
apache-2.0
7,568
//>>built define( "dojox/atom/widget/nls/pt-pt/FeedEntryEditor", //begin v1.x content ({ doNew: "[novo]", edit: "[editar]", save: "[guardar]", cancel: "[cancelar]" }) //end v1.x content );
cfxram/grails-dojo
web-app/js/dojo/1.7.2/dojox/atom/widget/nls/pt-pt/FeedEntryEditor.js
JavaScript
apache-2.0
193
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.deltaspike.jsf.impl.injection.proxy; import javax.faces.component.PartialStateHolder; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class ValidatorInvocationHandler implements InvocationHandler { private DefaultPartialStateHolder defaultPartialStateHolder = new DefaultPartialStateHolder(); @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // if the original class implements PartialStateHolder already, we won't get in here if (PartialStateHolder.class.equals(method.getDeclaringClass())) { return method.invoke(defaultPartialStateHolder, args); } else { //shouldn't happen, because DelegatingMethodHandler delegates all methods to the real implementations return method.invoke(proxy, args); } } }
tremes/deltaspike
deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/injection/proxy/ValidatorInvocationHandler.java
Java
apache-2.0
1,718
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.indices.settings.put; import org.elasticsearch.action.Action; import org.elasticsearch.client.ElasticsearchClient; import org.elasticsearch.action.support.master.AcknowledgedResponse; public class UpdateSettingsAction extends Action<UpdateSettingsRequest, AcknowledgedResponse, UpdateSettingsRequestBuilder> { public static final UpdateSettingsAction INSTANCE = new UpdateSettingsAction(); public static final String NAME = "indices:admin/settings/update"; private UpdateSettingsAction() { super(NAME); } @Override public AcknowledgedResponse newResponse() { return new AcknowledgedResponse(); } @Override public UpdateSettingsRequestBuilder newRequestBuilder(ElasticsearchClient client) { return new UpdateSettingsRequestBuilder(client, this); } }
strapdata/elassandra
server/src/main/java/org/elasticsearch/action/admin/indices/settings/put/UpdateSettingsAction.java
Java
apache-2.0
1,648
define({ summary: '總計:${0}', summaryWithSelection: '總計:${0} 已選取:${1}' });
andrescabrera/gwt-dojo-toolkit
src/gwt/dojo/gridx/public/dojo/gridx/nls/zh-tw/SummaryBar.js
JavaScript
apache-2.0
102
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This class implements the basic block reordering transformation. // // The transformation reorders basic blocks to decrease the amount of taken and // mispredicted jumps. // // see: K.Pettis, R.C.Hansen, Profile Guided Code Positioning, // Proceedings of the ACM SIGPLAN 1990 Conference on Programming Language // Design and Implementation, Vol. 25, No. 6, June 1990, pp. 16-27. #ifndef SYZYGY_OPTIMIZE_TRANSFORMS_BASIC_BLOCK_REORDERING_TRANSFORM_H_ #define SYZYGY_OPTIMIZE_TRANSFORMS_BASIC_BLOCK_REORDERING_TRANSFORM_H_ #include "syzygy/block_graph/filterable.h" #include "syzygy/block_graph/transform_policy.h" #include "syzygy/block_graph/analysis/control_flow_analysis.h" #include "syzygy/optimize/application_profile.h" #include "syzygy/optimize/transforms/subgraph_transform.h" namespace optimize { namespace transforms { // This transformation uses the Pettis algorithm to reorder basic blocks. class BasicBlockReorderingTransform : public SubGraphTransformInterface { public: typedef block_graph::BasicBlockSubGraph BasicBlockSubGraph; typedef block_graph::BlockGraph BlockGraph; typedef block_graph::TransformPolicyInterface TransformPolicyInterface; typedef block_graph::analysis::ControlFlowAnalysis::BasicBlockOrdering BasicBlockOrdering; // Constructor. BasicBlockReorderingTransform() { } // @name SubGraphTransformInterface implementation. // @{ virtual bool TransformBasicBlockSubGraph( const TransformPolicyInterface* policy, BlockGraph* block_graph, BasicBlockSubGraph* subgraph, ApplicationProfile* profile, SubGraphProfile* subgraph_profile) OVERRIDE; // @} protected: // Exposed for unittesting. // @{ static bool FlattenStructuralTreeToAnOrder( const BasicBlockSubGraph* subgraph, const SubGraphProfile* subgraph_profile, BasicBlockOrdering* order); static uint64 EvaluateCost(const BasicBlockOrdering& order, const SubGraphProfile& profile); static void CommitOrdering( const BasicBlockOrdering& order, block_graph::BasicEndBlock* basic_end_block, BasicBlockSubGraph::BasicBlockOrdering* target); // @} private: DISALLOW_COPY_AND_ASSIGN(BasicBlockReorderingTransform); }; } // namespace transforms } // namespace optimize #endif // SYZYGY_OPTIMIZE_TRANSFORMS_BASIC_BLOCK_REORDERING_TRANSFORM_H_
pombreda/syzygy
syzygy/optimize/transforms/basic_block_reordering_transform.h
C
apache-2.0
2,994
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.extensions.sql.meta.provider.bigquery; import java.io.IOException; import java.io.Serializable; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.function.IntFunction; import java.util.stream.Collectors; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.extensions.sql.impl.BeamTableStatistics; import org.apache.beam.sdk.extensions.sql.meta.BeamSqlTableFilter; import org.apache.beam.sdk.extensions.sql.meta.DefaultTableFilter; import org.apache.beam.sdk.extensions.sql.meta.ProjectSupport; import org.apache.beam.sdk.extensions.sql.meta.SchemaBaseBeamTable; import org.apache.beam.sdk.extensions.sql.meta.Table; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryHelpers; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead.Method; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryOptions; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryUtils; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryUtils.ConversionOptions; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.schemas.FieldAccessDescriptor; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.SchemaCoder; import org.apache.beam.sdk.schemas.utils.SelectHelpers; import org.apache.beam.sdk.values.PBegin; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.POutput; import org.apache.beam.sdk.values.Row; import org.apache.beam.vendor.calcite.v1_20_0.com.google.common.annotations.VisibleForTesting; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rel.rel2sql.SqlImplementor; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rex.RexNode; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlIdentifier; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlNode; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.parser.SqlParserPos; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@code BigQueryTable} represent a BigQuery table as a target. This provider does not currently * support being a source. */ @Experimental @SuppressWarnings({ "rawtypes", // TODO(https://issues.apache.org/jira/browse/BEAM-10556) "nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402) }) class BigQueryTable extends SchemaBaseBeamTable implements Serializable { @VisibleForTesting static final String METHOD_PROPERTY = "method"; @VisibleForTesting static final String WRITE_DISPOSITION_PROPERTY = "writeDisposition"; @VisibleForTesting final String bqLocation; private final ConversionOptions conversionOptions; private BeamTableStatistics rowCountStatistics = null; private static final Logger LOG = LoggerFactory.getLogger(BigQueryTable.class); @VisibleForTesting final Method method; @VisibleForTesting final WriteDisposition writeDisposition; BigQueryTable(Table table, BigQueryUtils.ConversionOptions options) { super(table.getSchema()); this.conversionOptions = options; this.bqLocation = table.getLocation(); if (table.getProperties().containsKey(METHOD_PROPERTY)) { List<String> validMethods = Arrays.stream(Method.values()).map(Enum::toString).collect(Collectors.toList()); // toUpperCase should make it case-insensitive String selectedMethod = table.getProperties().getString(METHOD_PROPERTY).toUpperCase(); if (validMethods.contains(selectedMethod)) { method = Method.valueOf(selectedMethod); } else { throw new InvalidPropertyException( "Invalid method " + "'" + selectedMethod + "'. " + "Supported methods are: " + validMethods.toString() + "."); } } else { method = Method.DIRECT_READ; } LOG.info("BigQuery method is set to: " + method.toString()); if (table.getProperties().containsKey(WRITE_DISPOSITION_PROPERTY)) { List<String> validWriteDispositions = Arrays.stream(WriteDisposition.values()).map(Enum::toString).collect(Collectors.toList()); // toUpperCase should make it case-insensitive String selectedWriteDisposition = table.getProperties().getString(WRITE_DISPOSITION_PROPERTY).toUpperCase(); if (validWriteDispositions.contains(selectedWriteDisposition)) { writeDisposition = WriteDisposition.valueOf(selectedWriteDisposition); } else { throw new InvalidPropertyException( "Invalid write disposition " + "'" + selectedWriteDisposition + "'. " + "Supported write dispositions are: " + validWriteDispositions.toString() + "."); } } else { writeDisposition = WriteDisposition.WRITE_EMPTY; } LOG.info("BigQuery writeDisposition is set to: " + writeDisposition.toString()); } @Override public BeamTableStatistics getTableStatistics(PipelineOptions options) { if (rowCountStatistics == null) { rowCountStatistics = getRowCountFromBQ(options, bqLocation); } return rowCountStatistics; } @Override public PCollection.IsBounded isBounded() { return PCollection.IsBounded.BOUNDED; } @Override public PCollection<Row> buildIOReader(PBegin begin) { return begin.apply("Read Input BQ Rows", getBigQueryTypedRead(getSchema())); } @Override public PCollection<Row> buildIOReader( PBegin begin, BeamSqlTableFilter filters, List<String> fieldNames) { if (!method.equals(Method.DIRECT_READ)) { LOG.info("Predicate/project push-down only available for `DIRECT_READ` method, skipping."); return buildIOReader(begin); } final FieldAccessDescriptor resolved = FieldAccessDescriptor.withFieldNames(fieldNames).resolve(getSchema()); final Schema newSchema = SelectHelpers.getOutputSchema(getSchema(), resolved); TypedRead<Row> typedRead = getBigQueryTypedRead(newSchema); if (!(filters instanceof DefaultTableFilter)) { BigQueryFilter bigQueryFilter = (BigQueryFilter) filters; if (!bigQueryFilter.getSupported().isEmpty()) { String rowRestriction = generateRowRestrictions(getSchema(), bigQueryFilter.getSupported()); if (!rowRestriction.isEmpty()) { LOG.info("Pushing down the following filter: " + rowRestriction); typedRead = typedRead.withRowRestriction(rowRestriction); } } } if (!fieldNames.isEmpty()) { typedRead = typedRead.withSelectedFields(fieldNames); } return begin.apply("Read Input BQ Rows with push-down", typedRead); } @Override public POutput buildIOWriter(PCollection<Row> input) { return input.apply( BigQueryIO.<Row>write() .withSchema(BigQueryUtils.toTableSchema(getSchema())) .withFormatFunction(BigQueryUtils.toTableRow()) .withWriteDisposition(writeDisposition) .to(bqLocation)); } @Override public ProjectSupport supportsProjects() { return method.equals(Method.DIRECT_READ) ? ProjectSupport.WITHOUT_FIELD_REORDERING : ProjectSupport.NONE; } @Override public BeamSqlTableFilter constructFilter(List<RexNode> filter) { if (method.equals(Method.DIRECT_READ)) { return new BigQueryFilter(filter); } return super.constructFilter(filter); } private String generateRowRestrictions(Schema schema, List<RexNode> supported) { assert !supported.isEmpty(); final IntFunction<SqlNode> field = i -> new SqlIdentifier(schema.getField(i).getName(), SqlParserPos.ZERO); // TODO: BigQuerySqlDialectWithTypeTranslation can be replaced with BigQuerySqlDialect after // updating vendor Calcite version. SqlImplementor.Context context = new BeamSqlUnparseContext(field); // Create a single SqlNode from a list of RexNodes SqlNode andSqlNode = null; for (RexNode node : supported) { SqlNode sqlNode = context.toSql(null, node); if (andSqlNode == null) { andSqlNode = sqlNode; continue; } // AND operator must have exactly 2 operands. andSqlNode = SqlStdOperatorTable.AND.createCall( SqlParserPos.ZERO, ImmutableList.of(andSqlNode, sqlNode)); } return andSqlNode.toSqlString(BeamBigQuerySqlDialect.DEFAULT).getSql(); } private TypedRead<Row> getBigQueryTypedRead(Schema schema) { return BigQueryIO.read( record -> BigQueryUtils.toBeamRow(record.getRecord(), schema, conversionOptions)) .withMethod(method) .from(bqLocation) .withCoder(SchemaCoder.of(schema)); } private static BeamTableStatistics getRowCountFromBQ(PipelineOptions o, String bqLocation) { try { BigInteger rowCount = BigQueryHelpers.getNumRows( o.as(BigQueryOptions.class), BigQueryHelpers.parseTableSpec(bqLocation)); if (rowCount == null) { return BeamTableStatistics.BOUNDED_UNKNOWN; } return BeamTableStatistics.createBoundedTableStatistics(rowCount.doubleValue()); } catch (IOException | InterruptedException e) { LOG.warn("Could not get the row count for the table " + bqLocation, e); } return BeamTableStatistics.BOUNDED_UNKNOWN; } public static class InvalidPropertyException extends UnsupportedOperationException { private InvalidPropertyException(String s) { super(s); } } }
lukecwik/incubator-beam
sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/meta/provider/bigquery/BigQueryTable.java
Java
apache-2.0
10,738
/** * Copyright 2012-2013 Niall Gallagher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.concurrenttrees.examples.filesystem; import com.googlecode.concurrenttrees.common.CharSequences; import com.googlecode.concurrenttrees.common.Iterables; import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree; import com.googlecode.concurrenttrees.radix.RadixTree; import com.googlecode.concurrenttrees.radix.node.Node; import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory; import com.googlecode.concurrenttrees.radix.node.util.PrettyPrintable; import java.util.*; /** * A simple implementation of {@link InMemoryFileSystem} based on {@link ConcurrentRadixTree}. * * @author Niall Gallagher */ public class ConcurrentRadixTreeInMemoryFileSystem<F> implements PrettyPrintable, InMemoryFileSystem<F> { private final RadixTree<F> radixTree = new ConcurrentRadixTree<F>(new DefaultCharArrayNodeFactory()); @Override public void addFile(String containingDirectory, String fileName, F file) { if (!containingDirectory.endsWith("/")) { throw new IllegalArgumentException("Containing directory must end with '/': " + containingDirectory); } if (containingDirectory.contains("$")) { throw new IllegalArgumentException("Containing directory cannot contain '$': " + containingDirectory); } if (fileName.contains("/")) { throw new IllegalArgumentException("File name cannot contain '/': " + fileName); } if (fileName.contains("$")) { throw new IllegalArgumentException("File name cannot contain '$': " + fileName); } if (file == null) { throw new IllegalArgumentException("File cannot be null"); } String fullyQualifiedFileName = containingDirectory + "$" + fileName; radixTree.put(fullyQualifiedFileName, file); } @Override public F getFile(String containingDirectory, String fileName) { if (!containingDirectory.endsWith("/")) { throw new IllegalArgumentException("Containing directory must end with '/': " + containingDirectory); } if (containingDirectory.contains("$")) { throw new IllegalArgumentException("Containing directory cannot contain '$': " + containingDirectory); } if (fileName.contains("/")) { throw new IllegalArgumentException("File name cannot contain '/': " + fileName); } if (fileName.contains("$")) { throw new IllegalArgumentException("File name cannot contain '$': " + fileName); } String fullyQualifiedFileName = containingDirectory + "$" + fileName; return radixTree.getValueForExactKey(fullyQualifiedFileName); } @Override public Collection<String> getFileNamesInDirectory(String containingDirectory) { if (!containingDirectory.endsWith("/")) { throw new IllegalArgumentException("Containing directory must end with '/': " + containingDirectory); } if (containingDirectory.contains("$")) { throw new IllegalArgumentException("Containing directory cannot contain '$': " + containingDirectory); } String fullyQualifiedDirectory = containingDirectory + "$"; Iterable<CharSequence> filePaths = radixTree.getKeysStartingWith(fullyQualifiedDirectory); List<String> fileNames = new LinkedList<String>(); for (CharSequence filePath : filePaths) { fileNames.add(new StringBuilder(CharSequences.subtractPrefix(filePath, fullyQualifiedDirectory)).toString()); } return fileNames; } @Override public Collection<F> getFilesInDirectory(String containingDirectory) { if (!containingDirectory.endsWith("/")) { throw new IllegalArgumentException("Containing directory must end with '/': " + containingDirectory); } if (containingDirectory.contains("$")) { throw new IllegalArgumentException("Containing directory cannot contain '$': " + containingDirectory); } String fullyQualifiedPath = containingDirectory + "$"; return Iterables.toList(radixTree.getValuesForKeysStartingWith(fullyQualifiedPath)); } @Override public Collection<String> getFileNamesInDirectoryRecursive(String containingDirectory) { if (!containingDirectory.endsWith("/")) { throw new IllegalArgumentException("Containing directory must end with '/': " + containingDirectory); } if (containingDirectory.contains("$")) { throw new IllegalArgumentException("Containing directory cannot contain '$': " + containingDirectory); } Iterable<CharSequence> filePaths = radixTree.getKeysStartingWith(containingDirectory); List<String> fileNames = new LinkedList<String>(); for (CharSequence filePath : filePaths) { String filePathString = new StringBuilder(filePath).toString(); filePathString = filePathString.replaceFirst(".*\\$", ""); fileNames.add(filePathString); } return fileNames; } @Override public Collection<F> getFilesInDirectoryRecursive(String containingDirectory) { if (!containingDirectory.endsWith("/")) { throw new IllegalArgumentException("Containing directory must end with '/': " + containingDirectory); } if (containingDirectory.contains("$")) { throw new IllegalArgumentException("Containing directory cannot contain '$': " + containingDirectory); } return Iterables.toList(radixTree.getValuesForKeysStartingWith(containingDirectory)); } @Override public Node getNode() { return ((PrettyPrintable)radixTree).getNode(); } }
opentalking/concurrent-trees
concurrent-trees/src/test/java/com/googlecode/concurrenttrees/examples/filesystem/ConcurrentRadixTreeInMemoryFileSystem.java
Java
apache-2.0
6,351
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License /* ****************************************************************************** * Copyright (C) 2003-2011, International Business Machines Corporation and * * others. All Rights Reserved. * ****************************************************************************** */ package com.ibm.icu.impl; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import com.ibm.icu.impl.locale.AsciiUtil; /** * Utility class to parse and normalize locale ids (including POSIX style) */ public final class LocaleIDParser { /** * Char array representing the locale ID. */ private char[] id; /** * Current position in {@link #id} (while parsing). */ private int index; /** * Temporary buffer for parsed sections of data. */ private StringBuilder buffer; // um, don't handle POSIX ids unless we request it. why not? well... because. private boolean canonicalize; private boolean hadCountry; // used when canonicalizing Map<String, String> keywords; String baseName; /** * Parsing constants. */ private static final char KEYWORD_SEPARATOR = '@'; private static final char HYPHEN = '-'; private static final char KEYWORD_ASSIGN = '='; private static final char COMMA = ','; private static final char ITEM_SEPARATOR = ';'; private static final char DOT = '.'; private static final char UNDERSCORE = '_'; public LocaleIDParser(String localeID) { this(localeID, false); } public LocaleIDParser(String localeID, boolean canonicalize) { id = localeID.toCharArray(); index = 0; buffer = new StringBuilder(id.length + 5); this.canonicalize = canonicalize; } private void reset() { index = 0; buffer = new StringBuilder(id.length + 5); } // utilities for working on text in the buffer /** * Append c to the buffer. */ private void append(char c) { buffer.append(c); } private void addSeparator() { append(UNDERSCORE); } /** * Returns the text in the buffer from start to blen as a String. */ private String getString(int start) { return buffer.substring(start); } /** * Set the length of the buffer to pos, then append the string. */ private void set(int pos, String s) { buffer.delete(pos, buffer.length()); buffer.insert(pos, s); } /** * Append the string to the buffer. */ private void append(String s) { buffer.append(s); } // utilities for parsing text out of the id /** * Character to indicate no more text is available in the id. */ private static final char DONE = '\uffff'; /** * Returns the character at index in the id, and advance index. The returned character * is DONE if index was at the limit of the buffer. The index is advanced regardless * so that decrementing the index will always 'unget' the last character returned. */ private char next() { if (index == id.length) { index++; return DONE; } return id[index++]; } /** * Advance index until the next terminator or id separator, and leave it there. */ private void skipUntilTerminatorOrIDSeparator() { while (!isTerminatorOrIDSeparator(next())); --index; } /** * Returns true if the character at index in the id is a terminator. */ private boolean atTerminator() { return index >= id.length || isTerminator(id[index]); } /** * Returns true if the character is a terminator (keyword separator, dot, or DONE). * Dot is a terminator because of the POSIX form, where dot precedes the codepage. */ private boolean isTerminator(char c) { // always terminate at DOT, even if not handling POSIX. It's an error... return c == KEYWORD_SEPARATOR || c == DONE || c == DOT; } /** * Returns true if the character is a terminator or id separator. */ private boolean isTerminatorOrIDSeparator(char c) { return c == UNDERSCORE || c == HYPHEN || isTerminator(c); } /** * Returns true if the start of the buffer has an experimental or private language * prefix, the pattern '[ixIX][-_].' shows the syntax checked. */ private boolean haveExperimentalLanguagePrefix() { if (id.length > 2) { char c = id[1]; if (c == HYPHEN || c == UNDERSCORE) { c = id[0]; return c == 'x' || c == 'X' || c == 'i' || c == 'I'; } } return false; } /** * Returns true if a value separator occurs at or after index. */ private boolean haveKeywordAssign() { // assume it is safe to start from index for (int i = index; i < id.length; ++i) { if (id[i] == KEYWORD_ASSIGN) { return true; } } return false; } /** * Advance index past language, and accumulate normalized language code in buffer. * Index must be at 0 when this is called. Index is left at a terminator or id * separator. Returns the start of the language code in the buffer. */ private int parseLanguage() { int startLength = buffer.length(); if (haveExperimentalLanguagePrefix()) { append(AsciiUtil.toLower(id[0])); append(HYPHEN); index = 2; } char c; while(!isTerminatorOrIDSeparator(c = next())) { append(AsciiUtil.toLower(c)); } --index; // unget if (buffer.length() - startLength == 3) { String lang = LocaleIDs.threeToTwoLetterLanguage(getString(0)); if (lang != null) { set(0, lang); } } return 0; } /** * Advance index past language. Index must be at 0 when this is called. Index * is left at a terminator or id separator. */ private void skipLanguage() { if (haveExperimentalLanguagePrefix()) { index = 2; } skipUntilTerminatorOrIDSeparator(); } /** * Advance index past script, and accumulate normalized script in buffer. * Index must be immediately after the language. * If the item at this position is not a script (is not four characters * long) leave index and buffer unchanged. Otherwise index is left at * a terminator or id separator. Returns the start of the script code * in the buffer (this may be equal to the buffer length, if there is no * script). */ private int parseScript() { if (!atTerminator()) { int oldIndex = index; // save original index ++index; int oldBlen = buffer.length(); // get before append hyphen, if we truncate everything is undone char c; boolean firstPass = true; while(!isTerminatorOrIDSeparator(c = next()) && AsciiUtil.isAlpha(c)) { if (firstPass) { addSeparator(); append(AsciiUtil.toUpper(c)); firstPass = false; } else { append(AsciiUtil.toLower(c)); } } --index; // unget /* If it's not exactly 4 characters long, then it's not a script. */ if (index - oldIndex != 5) { // +1 to account for separator index = oldIndex; buffer.delete(oldBlen, buffer.length()); } else { oldBlen++; // index past hyphen, for clients who want to extract just the script } return oldBlen; } return buffer.length(); } /** * Advance index past script. * Index must be immediately after the language and IDSeparator. * If the item at this position is not a script (is not four characters * long) leave index. Otherwise index is left at a terminator or * id separator. */ private void skipScript() { if (!atTerminator()) { int oldIndex = index; ++index; char c; while (!isTerminatorOrIDSeparator(c = next()) && AsciiUtil.isAlpha(c)); --index; if (index - oldIndex != 5) { // +1 to account for separator index = oldIndex; } } } /** * Advance index past country, and accumulate normalized country in buffer. * Index must be immediately after the script (if there is one, else language) * and IDSeparator. Return the start of the country code in the buffer. */ private int parseCountry() { if (!atTerminator()) { int oldIndex = index; ++index; int oldBlen = buffer.length(); char c; boolean firstPass = true; while (!isTerminatorOrIDSeparator(c = next())) { if (firstPass) { // first, add hyphen hadCountry = true; // we have a country, let variant parsing know addSeparator(); ++oldBlen; // increment past hyphen firstPass = false; } append(AsciiUtil.toUpper(c)); } --index; // unget int charsAppended = buffer.length() - oldBlen; if (charsAppended == 0) { // Do nothing. } else if (charsAppended < 2 || charsAppended > 3) { // It's not a country, so return index and blen to // their previous values. index = oldIndex; --oldBlen; buffer.delete(oldBlen, buffer.length()); hadCountry = false; } else if (charsAppended == 3) { String region = LocaleIDs.threeToTwoLetterRegion(getString(oldBlen)); if (region != null) { set(oldBlen, region); } } return oldBlen; } return buffer.length(); } /** * Advance index past country. * Index must be immediately after the script (if there is one, else language) * and IDSeparator. */ private void skipCountry() { if (!atTerminator()) { if (id[index] == UNDERSCORE || id[index] == HYPHEN) { ++index; } /* * Save the index point after the separator, since the format * requires two separators if the country is not present. */ int oldIndex = index; skipUntilTerminatorOrIDSeparator(); int charsSkipped = index - oldIndex; if (charsSkipped < 2 || charsSkipped > 3) { index = oldIndex; } } } /** * Advance index past variant, and accumulate normalized variant in buffer. This ignores * the codepage information from POSIX ids. Index must be immediately after the country * or script. Index is left at the keyword separator or at the end of the text. Return * the start of the variant code in the buffer. * * In standard form, we can have the following forms: * ll__VVVV * ll_CC_VVVV * ll_Ssss_VVVV * ll_Ssss_CC_VVVV * * This also handles POSIX ids, which can have the following forms (pppp is code page id): * ll_CC.pppp --> ll_CC * ll_CC.pppp@VVVV --> ll_CC_VVVV * ll_CC@VVVV --> ll_CC_VVVV * * We identify this use of '@' in POSIX ids by looking for an '=' following * the '@'. If there is one, we consider '@' to start a keyword list, instead of * being part of a POSIX id. * * Note: since it was decided that we want an option to not handle POSIX ids, this * becomes a bit more complex. */ private int parseVariant() { int oldBlen = buffer.length(); boolean start = true; boolean needSeparator = true; boolean skipping = false; char c; boolean firstPass = true; while ((c = next()) != DONE) { if (c == DOT) { start = false; skipping = true; } else if (c == KEYWORD_SEPARATOR) { if (haveKeywordAssign()) { break; } skipping = false; start = false; needSeparator = true; // add another underscore if we have more text } else if (start) { start = false; if (c != UNDERSCORE && c != HYPHEN) { index--; } } else if (!skipping) { if (needSeparator) { needSeparator = false; if (firstPass && !hadCountry) { // no country, we'll need two addSeparator(); ++oldBlen; // for sure } addSeparator(); if (firstPass) { // only for the first separator ++oldBlen; firstPass = false; } } c = AsciiUtil.toUpper(c); if (c == HYPHEN || c == COMMA) { c = UNDERSCORE; } append(c); } } --index; // unget return oldBlen; } // no need for skipvariant, to get the keywords we'll just scan directly for // the keyword separator /** * Returns the normalized language id, or the empty string. */ public String getLanguage() { reset(); return getString(parseLanguage()); } /** * Returns the normalized script id, or the empty string. */ public String getScript() { reset(); skipLanguage(); return getString(parseScript()); } /** * return the normalized country id, or the empty string. */ public String getCountry() { reset(); skipLanguage(); skipScript(); return getString(parseCountry()); } /** * Returns the normalized variant id, or the empty string. */ public String getVariant() { reset(); skipLanguage(); skipScript(); skipCountry(); return getString(parseVariant()); } /** * Returns the language, script, country, and variant as separate strings. */ public String[] getLanguageScriptCountryVariant() { reset(); return new String[] { getString(parseLanguage()), getString(parseScript()), getString(parseCountry()), getString(parseVariant()) }; } public void setBaseName(String baseName) { this.baseName = baseName; } public void parseBaseName() { if (baseName != null) { set(0, baseName); } else { reset(); parseLanguage(); parseScript(); parseCountry(); parseVariant(); // catch unwanted trailing underscore after country if there was no variant int len = buffer.length(); if (len > 0 && buffer.charAt(len - 1) == UNDERSCORE) { buffer.deleteCharAt(len - 1); } } } /** * Returns the normalized base form of the locale id. The base * form does not include keywords. */ public String getBaseName() { if (baseName != null) { return baseName; } parseBaseName(); return getString(0); } /** * Returns the normalized full form of the locale id. The full * form includes keywords if they are present. */ public String getName() { parseBaseName(); parseKeywords(); return getString(0); } // keyword utilities /** * If we have keywords, advance index to the start of the keywords and return true, * otherwise return false. */ private boolean setToKeywordStart() { for (int i = index; i < id.length; ++i) { if (id[i] == KEYWORD_SEPARATOR) { if (canonicalize) { for (int j = ++i; j < id.length; ++j) { // increment i past separator for return if (id[j] == KEYWORD_ASSIGN) { index = i; return true; } } } else { if (++i < id.length) { index = i; return true; } } break; } } return false; } private static boolean isDoneOrKeywordAssign(char c) { return c == DONE || c == KEYWORD_ASSIGN; } private static boolean isDoneOrItemSeparator(char c) { return c == DONE || c == ITEM_SEPARATOR; } private String getKeyword() { int start = index; while (!isDoneOrKeywordAssign(next())) { } --index; return AsciiUtil.toLowerString(new String(id, start, index-start).trim()); } private String getValue() { int start = index; while (!isDoneOrItemSeparator(next())) { } --index; return new String(id, start, index-start).trim(); // leave case alone } private Comparator<String> getKeyComparator() { final Comparator<String> comp = new Comparator<String>() { @Override public int compare(String lhs, String rhs) { return lhs.compareTo(rhs); } }; return comp; } /** * Returns a map of the keywords and values, or null if there are none. */ public Map<String, String> getKeywordMap() { if (keywords == null) { TreeMap<String, String> m = null; if (setToKeywordStart()) { // trim spaces and convert to lower case, both keywords and values. do { String key = getKeyword(); if (key.length() == 0) { break; } char c = next(); if (c != KEYWORD_ASSIGN) { // throw new IllegalArgumentException("key '" + key + "' missing a value."); if (c == DONE) { break; } else { continue; } } String value = getValue(); if (value.length() == 0) { // throw new IllegalArgumentException("key '" + key + "' missing a value."); continue; } if (m == null) { m = new TreeMap<String, String>(getKeyComparator()); } else if (m.containsKey(key)) { // throw new IllegalArgumentException("key '" + key + "' already has a value."); continue; } m.put(key, value); } while (next() == ITEM_SEPARATOR); } keywords = m != null ? m : Collections.<String, String>emptyMap(); } return keywords; } /** * Parse the keywords and return start of the string in the buffer. */ private int parseKeywords() { int oldBlen = buffer.length(); Map<String, String> m = getKeywordMap(); if (!m.isEmpty()) { boolean first = true; for (Map.Entry<String, String> e : m.entrySet()) { append(first ? KEYWORD_SEPARATOR : ITEM_SEPARATOR); first = false; append(e.getKey()); append(KEYWORD_ASSIGN); append(e.getValue()); } if (first == false) { ++oldBlen; } } return oldBlen; } /** * Returns an iterator over the keywords, or null if we have an empty map. */ public Iterator<String> getKeywords() { Map<String, String> m = getKeywordMap(); return m.isEmpty() ? null : m.keySet().iterator(); } /** * Returns the value for the named keyword, or null if the keyword is not * present. */ public String getKeywordValue(String keywordName) { Map<String, String> m = getKeywordMap(); return m.isEmpty() ? null : m.get(AsciiUtil.toLowerString(keywordName.trim())); } /** * Set the keyword value only if it is not already set to something else. */ public void defaultKeywordValue(String keywordName, String value) { setKeywordValue(keywordName, value, false); } /** * Set the value for the named keyword, or unset it if value is null. If * keywordName itself is null, unset all keywords. If keywordName is not null, * value must not be null. */ public void setKeywordValue(String keywordName, String value) { setKeywordValue(keywordName, value, true); } /** * Set the value for the named keyword, or unset it if value is null. If * keywordName itself is null, unset all keywords. If keywordName is not null, * value must not be null. If reset is true, ignore any previous value for * the keyword, otherwise do not change the keyword (including removal of * one or all keywords). */ private void setKeywordValue(String keywordName, String value, boolean reset) { if (keywordName == null) { if (reset) { // force new map, ignore value keywords = Collections.<String, String>emptyMap(); } } else { keywordName = AsciiUtil.toLowerString(keywordName.trim()); if (keywordName.length() == 0) { throw new IllegalArgumentException("keyword must not be empty"); } if (value != null) { value = value.trim(); if (value.length() == 0) { throw new IllegalArgumentException("value must not be empty"); } } Map<String, String> m = getKeywordMap(); if (m.isEmpty()) { // it is EMPTY_MAP if (value != null) { // force new map keywords = new TreeMap<String, String>(getKeyComparator()); keywords.put(keywordName, value.trim()); } } else { if (reset || !m.containsKey(keywordName)) { if (value != null) { m.put(keywordName, value); } else { m.remove(keywordName); if (m.isEmpty()) { // force new map keywords = Collections.<String, String>emptyMap(); } } } } } } }
abhijitvalluri/fitnotifications
icu4j/src/main/java/com/ibm/icu/impl/LocaleIDParser.java
Java
apache-2.0
23,748
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.2.3.7-6-a-100 description: > Object.defineProperties - 'P' is data property, several attributes values of P and properties are different (8.12.9 step 12) includes: [propertyHelper.js] ---*/ var obj = {}; Object.defineProperty(obj, "foo", { value: 100, writable: true, configurable: true }); Object.defineProperties(obj, { foo: { value: 200, writable: false, configurable: false } }); verifyEqualTo(obj, "foo", 200); verifyNotWritable(obj, "foo"); verifyNotEnumerable(obj, "foo"); verifyNotConfigurable(obj, "foo");
m0ppers/arangodb
3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Object/defineProperties/15.2.3.7-6-a-100.js
JavaScript
apache-2.0
730
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _DECAF_UTIL_CONCURRENT_LOCKS_LOCK_H_ #define _DECAF_UTIL_CONCURRENT_LOCKS_LOCK_H_ #include <decaf/util/Config.h> #include <decaf/lang/exceptions/InterruptedException.h> #include <decaf/lang/exceptions/UnsupportedOperationException.h> #include <decaf/util/concurrent/locks/Condition.h> namespace decaf { namespace util { namespace concurrent { namespace locks { /** * Lock implementations provide more extensive locking operations than can be * obtained using synchronized statements. They allow more flexible structuring, * may have quite different properties, and may support multiple associated * Condition objects. * * A lock is a tool for controlling access to a shared resource by multiple * threads. Commonly, a lock provides exclusive access to a shared resource: * only one thread at a time can acquire the lock and all access to the shared * resource requires that the lock be acquired first. However, some locks may * allow concurrent access to a shared resource, such as the read lock of a * ReadWriteLock. * * While the scoping mechanism for synchronized statements makes it much easier * easier to program with monitor locks, and helps avoid many common programming * errors involving locks, there are occasions where you need to work with locks * in a more flexible way. For example, some algorithms for traversing concurrently * accessed data structures require the use of "hand-over-hand" or * "chain locking": you acquire the lock of node A, then node B, then release A * and acquire C, then release B and acquire D and so on. Implementations of the * Lock interface enable the use of such techniques by allowing a lock to be * acquired and released in different scopes, and allowing multiple locks to be * acquired and released in any order. * * With this increased flexibility comes additional responsibility. The absence of * block-structured locking removes the automatic release of locks that occurs with * synchronized statements. In most cases, the following idiom should be used: * * Lock l = ...; * l.lock(); * try { * // access the resource protected by this lock * } catch(...) { * l.unlock(); * } * * When locking and unlocking occur in different scopes, care must be taken to ensure * that all code that is executed while the lock is held is protected by try-catch * ensure that the lock is released when necessary. * * Lock implementations provide additional functionality over the use of synchronized * methods and statements by providing a non-blocking attempt to acquire a lock * (tryLock()), an attempt to acquire the lock that can be interrupted (lockInterruptibly(), * and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)). * * Note that Lock instances are just normal objects and can themselves be used as the * target in a synchronized statement. * * The three forms of lock acquisition (interruptible, non-interruptible, and timed) * may differ in their performance characteristics, ordering guarantees, or other * implementation qualities. Further, the ability to interrupt the ongoing acquisition * of a lock may not be available in a given Lock class. Consequently, an implementation * is not required to define exactly the same guarantees or semantics for all three forms * of lock acquisition, nor is it required to support interruption of an ongoing lock * acquisition. An implementation is required to clearly document the semantics and * guarantees provided by each of the locking methods. It must also obey the interruption * semantics as defined in this interface, to the extent that interruption of lock * acquisition is supported: which is either totally, or only on method entry. * * As interruption generally implies cancellation, and checks for interruption are * often infrequent, an implementation can favor responding to an interrupt over normal * method return. This is true even if it can be shown that the interrupt occurred after * another action may have unblocked the thread. An implementation should document this * behavior. * * @since 1.0 */ class DECAF_API Lock { public: virtual ~Lock(); /** * Acquires the lock. * * If the lock is not available then the current thread becomes disabled for thread * scheduling purposes and lies dormant until the lock has been acquired. * * Implementation Considerations * * A Lock implementation may be able to detect erroneous use of the lock, such as an * invocation that would cause deadlock, and may throw an exception in such circumstances. * The circumstances and the exception type must be documented by that Lock implementation. * * @throws RuntimeException if an error occurs while acquiring the lock. */ virtual void lock() = 0; /** * Acquires the lock unless the current thread is interrupted. * <p> * Acquires the lock if it is available and returns immediately. * <p> * If the lock is not available then the current thread becomes disabled for thread * scheduling purposes and lies dormant until one of two things happens: * * * The lock is acquired by the current thread; or * * Some other thread interrupts the current thread, and interruption of lock * acquisition is supported. * * If the current thread: * * * has its interrupted status set on entry to this method; or * * is interrupted while acquiring the lock, and interruption of lock acquisition * is supported, * * then InterruptedException is thrown and the current thread's interrupted status * is cleared. * * Implementation Considerations * * The ability to interrupt a lock acquisition in some implementations may not be * possible, and if possible may be an expensive operation. The programmer should * be aware that this may be the case. An implementation should document when this * is the case. * * An implementation can favor responding to an interrupt over normal method return. * * A Lock implementation may be able to detect erroneous use of the lock, such as an * invocation that would cause deadlock, and may throw an exception in such * circumstances. The circumstances and the exception type must be documented by * that Lock implementation. * * @throws RuntimeException if an error occurs while acquiring the lock. * @throws InterruptedException * if the current thread is interrupted while acquiring the lock (and * interruption of lock acquisition is supported). */ virtual void lockInterruptibly() = 0; /** * Acquires the lock only if it is free at the time of invocation. * <p> * Acquires the lock if it is available and returns immediately with the value true. * If the lock is not available then this method will return immediately with the * value false. * <p> * A typical usage idiom for this method would be: * * Lock lock = ...; * if (lock.tryLock()) { * try { * // manipulate protected state * } catch(...) { * lock.unlock(); * } * } else { * // perform alternative actions * } * * This usage ensures that the lock is unlocked if it was acquired, and doesn't * try to unlock if the lock was not acquired. * * @return true if the lock was acquired and false otherwise * * @throws RuntimeException if an error occurs while acquiring the lock. */ virtual bool tryLock() = 0; /** * Acquires the lock if it is free within the given waiting time and the current * thread has not been interrupted. * <p> * If the lock is available this method returns immediately with the value true. * If the lock is not available then the current thread becomes disabled for thread * scheduling purposes and lies dormant until one of three things happens: * * * The lock is acquired by the current thread; or * * Some other thread interrupts the current thread, and interruption of lock * acquisition is supported; or * * The specified waiting time elapses * * If the lock is acquired then the value true is returned. * * If the current thread: * * * has its interrupted status set on entry to this method; or * * is interrupted while acquiring the lock, and interruption of lock acquisition * is supported, * * then InterruptedException is thrown and the current thread's interrupted status * is cleared. * * If the specified waiting time elapses then the value false is returned. If the * time is less than or equal to zero, the method will not wait at all. * * Implementation Considerations * * The ability to interrupt a lock acquisition in some implementations may not * be possible, and if possible may be an expensive operation. The programmer should * be aware that this may be the case. An implementation should document when this * is the case. * * An implementation can favor responding to an interrupt over normal method return, * or reporting a timeout. * * A Lock implementation may be able to detect erroneous use of the lock, such as an * invocation that would cause deadlock, and may throw an (unchecked) exception in * such circumstances. The circumstances and the exception type must be documented by * that Lock implementation. * * @param time * the maximum time to wait for the lock * @param unit * the time unit of the time argument * * @return true if the lock was acquired and false if the waiting time elapsed * before the lock was acquired * * @throws RuntimeException if an error occurs while acquiring the lock. * @throws InterruptedException * if the current thread is interrupted while acquiring the lock (and * interruption of lock acquisition is supported) */ virtual bool tryLock(long long time, const TimeUnit& unit) = 0; /** * Releases the lock. * <p> * Implementation Considerations * * A Lock implementation will usually impose restrictions on which thread can release * a lock (typically only the holder of the lock can release it) and may throw an * exception if the restriction is violated. Any restrictions and the exception * type must be documented by that Lock implementation. * * @throws RuntimeException if an error occurs while acquiring the lock. * @throws IllegalMonitorStateException if the current thread is not the owner of the lock. */ virtual void unlock() = 0; /** * Returns a new Condition instance that is bound to this Lock instance. * <p> * Before waiting on the condition the lock must be held by the current thread. * A call to Condition.await() will atomically release the lock before waiting * and re-acquire the lock before the wait returns. * <p> * Implementation Considerations * <p> * The exact operation of the Condition instance depends on the Lock implementation * and must be documented by that implementation. * * @return A new Condition instance for this Lock instance the caller must * delete the returned Condition object when done with it. * * @throws RuntimeException if an error occurs while creating the Condition. * @throws UnsupportedOperationException * if this Lock implementation does not support conditions */ virtual Condition* newCondition() = 0; /** * @return a string representation of the Lock useful for debugging purposes. */ virtual std::string toString() const = 0; }; }}}} #endif /*_DECAF_UTIL_CONCURRENT_LOCKS_LOCK_H_ */
lleoha/activemq-cpp-debian
src/main/decaf/util/concurrent/locks/Lock.h
C
apache-2.0
13,877
CREATE TABLE gspanother.C_TABLE ( C_ID BIGINT IDENTITY NOT NULL , TEST_NAME VARCHAR(100) NULL , TEST1 VARCHAR(100) NULL , TEST2 VARCHAR(500) NULL , TEST3 VARCHAR(500) NULL ); EXEC sys.sp_addextendedproperty @name = N'Description', @value = N'C_TABLE', @level0type = N'SCHEMA', @level0name = gspanother, @level1type = N'TABLE', @level1name = C_TABLE; EXEC sys.sp_addextendedproperty @name = N'Description', @value = N'C_ID', @level0type = N'SCHEMA', @level0name = gspanother, @level1type = N'TABLE', @level1name = C_TABLE, @level2type = N'COLUMN', @level2name = C_ID; EXEC sys.sp_addextendedproperty @name = N'Description', @value = N'TEST_NAME', @level0type = N'SCHEMA', @level0name = gspanother, @level1type = N'TABLE', @level1name = C_TABLE, @level2type = N'COLUMN', @level2name = TEST_NAME; EXEC sys.sp_addextendedproperty @name = N'Description', @value = N'TEST1', @level0type = N'SCHEMA', @level0name = gspanother, @level1type = N'TABLE', @level1name = C_TABLE, @level2type = N'COLUMN', @level2name = TEST1; EXEC sys.sp_addextendedproperty @name = N'Description', @value = N'TEST2', @level0type = N'SCHEMA', @level0name = gspanother, @level1type = N'TABLE', @level1name = C_TABLE, @level2type = N'COLUMN', @level2name = TEST2; EXEC sys.sp_addextendedproperty @name = N'Description', @value = N'TEST3', @level0type = N'SCHEMA', @level0name = gspanother, @level1type = N'TABLE', @level1name = C_TABLE, @level2type = N'COLUMN', @level2name = TEST3;
coastland/gsp-dba-maven-plugin
src/test/resources/jp/co/tis/gsp/tools/dba/mojo/LoadDataMojo_test/another_schema/sqlserver/ddl/10_CREATE_C_TABLE.sql
SQL
apache-2.0
1,473
------------------------------------------------------------------------------- -- cms catalog ------------------------------------------------------------------------------- CREATE TABLE CMS_CATALOG( ID BIGINT NOT NULL, NAME VARCHAR(50), CODE VARCHAR(200), LOGO VARCHAR(200), TYPE INT, TEMPLATE_INDEX VARCHAR(200), TEMPLATE_LIST VARCHAR(200), TEMPLATE_DETAIL VARCHAR(200), KEYWORD VARCHAR(200), DESCRIPTION VARCHAR(200), PARENT_ID BIGINT, CONSTRAINT PK_CMS_CATALOG PRIMARY KEY(ID), CONSTRAINT FK_CMS_CATALOG_PARENT FOREIGN KEY(PARENT_ID) REFERENCES CMS_CATALOG(ID) ) ENGINE=INNODB CHARSET=UTF8;
xuhuisheng/lemon
src/main/resources/dbmigrate/mysql/cms/V0_0_1__cms_catalog.sql
SQL
apache-2.0
627
/* * Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat; import io.mycat.server.config.node.SystemConfig; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.log4j.helpers.LogLog; /** * @author mycat */ public final class MycatStartup { private static final String dateFormat = "yyyy-MM-dd HH:mm:ss"; public static void main(String[] args) { try { String home = SystemConfig.getHomePath(); if (home == null) { System.out.println(SystemConfig.SYS_HOME + " is not set."); System.exit(-1); } // init MycatServer server = MycatServer.getInstance(); server.beforeStart(); // startup server.startup(); System.out.println("MyCAT Server startup successfully. see logs in logs/mycat.log"); while (true) { Thread.sleep(300 * 1000); } } catch (Exception e) { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); LogLog.error(sdf.format(new Date()) + " startup error", e); System.exit(-1); } } }
runfriends/Mycat-Server
src/main/java/io/mycat/MycatStartup.java
Java
apache-2.0
2,045
using Lucene.Net.Index; using Lucene.Net.Search; using Lucene.Net.Util; using System; namespace Lucene.Net.Join { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// A field comparer that allows parent documents to be sorted by fields /// from the nested / child documents. /// /// @lucene.experimental /// </summary> public abstract class ToParentBlockJoinFieldComparer : FieldComparer<object> { private readonly Filter _parentFilter; private readonly Filter _childFilter; private readonly int _spareSlot; private FieldComparer _wrappedComparer; private FixedBitSet _parentDocuments; private FixedBitSet _childDocuments; private ToParentBlockJoinFieldComparer(FieldComparer wrappedComparer, Filter parentFilter, Filter childFilter, int spareSlot) { _wrappedComparer = wrappedComparer; _parentFilter = parentFilter; _childFilter = childFilter; _spareSlot = spareSlot; } public override int Compare(int slot1, int slot2) { return _wrappedComparer.Compare(slot1, slot2); } public override void SetBottom(int slot) { _wrappedComparer.SetBottom(slot); } public override void SetTopValue(object value) { _wrappedComparer.SetTopValue(value); } public override FieldComparer SetNextReader(AtomicReaderContext context) { DocIdSet innerDocuments = _childFilter.GetDocIdSet(context, null); if (IsEmpty(innerDocuments)) { _childDocuments = null; } else if (innerDocuments is FixedBitSet) { _childDocuments = (FixedBitSet)innerDocuments; } else { DocIdSetIterator iterator = innerDocuments.GetIterator(); _childDocuments = iterator != null ? ToFixedBitSet(iterator, context.AtomicReader.MaxDoc) : null; } DocIdSet rootDocuments = _parentFilter.GetDocIdSet(context, null); if (IsEmpty(rootDocuments)) { _parentDocuments = null; } else if (rootDocuments is FixedBitSet) { _parentDocuments = (FixedBitSet)rootDocuments; } else { DocIdSetIterator iterator = rootDocuments.GetIterator(); _parentDocuments = iterator != null ? ToFixedBitSet(iterator, context.AtomicReader.MaxDoc) : null; } _wrappedComparer = _wrappedComparer.SetNextReader(context); return this; } private static bool IsEmpty(DocIdSet set) { return set == null; } private static FixedBitSet ToFixedBitSet(DocIdSetIterator iterator, int numBits) { var set = new FixedBitSet(numBits); int doc; while ((doc = iterator.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { set.Set(doc); } return set; } // LUCENENET NOTE: This was value(int) in Lucene. public override IComparable this[int slot] => _wrappedComparer[slot]; /// <summary> /// Concrete implementation of <see cref="ToParentBlockJoinSortField"/> to sorts the parent docs with the lowest values /// in the child / nested docs first. /// </summary> public sealed class Lowest : ToParentBlockJoinFieldComparer { /// <summary> /// Create <see cref="ToParentBlockJoinFieldComparer.Lowest"/> /// </summary> /// <param name="wrappedComparer">The <see cref="FieldComparer"/> on the child / nested level. </param> /// <param name="parentFilter"><see cref="Filter"/> (must produce <see cref="FixedBitSet"/> per-segment) that identifies the parent documents. </param> /// <param name="childFilter"><see cref="Filter"/> that defines which child / nested documents participates in sorting. </param> /// <param name="spareSlot">The extra slot inside the wrapped comparer that is used to compare which nested document /// inside the parent document scope is most competitive. </param> public Lowest(FieldComparer wrappedComparer, Filter parentFilter, Filter childFilter, int spareSlot) : base(wrappedComparer, parentFilter, childFilter, spareSlot) { } public override int CompareBottom(int parentDoc) { if (parentDoc == 0 || _parentDocuments == null || _childDocuments == null) { return 0; } // We need to copy the lowest value from all child docs into slot. int prevParentDoc = _parentDocuments.PrevSetBit(parentDoc - 1); int childDoc = _childDocuments.NextSetBit(prevParentDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return 0; } // We only need to emit a single cmp value for any matching child doc int cmp = _wrappedComparer.CompareBottom(childDoc); if (cmp > 0) { return cmp; } while (true) { childDoc = _childDocuments.NextSetBit(childDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return cmp; } int cmp1 = _wrappedComparer.CompareBottom(childDoc); if (cmp1 > 0) { return cmp1; } if (cmp1 == 0) { cmp = 0; } } } public override void Copy(int slot, int parentDoc) { if (parentDoc == 0 || _parentDocuments == null || _childDocuments == null) { return; } // We need to copy the lowest value from all child docs into slot. int prevParentDoc = _parentDocuments.PrevSetBit(parentDoc - 1); int childDoc = _childDocuments.NextSetBit(prevParentDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return; } _wrappedComparer.Copy(_spareSlot, childDoc); _wrappedComparer.Copy(slot, childDoc); while (true) { childDoc = _childDocuments.NextSetBit(childDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return; } _wrappedComparer.Copy(_spareSlot, childDoc); if (_wrappedComparer.Compare(_spareSlot, slot) < 0) { _wrappedComparer.Copy(slot, childDoc); } } } public override int CompareTop(int parentDoc) { if (parentDoc == 0 || _parentDocuments == null || _childDocuments == null) { return 0; } // We need to copy the lowest value from all nested docs into slot. int prevParentDoc = _parentDocuments.PrevSetBit(parentDoc - 1); int childDoc = _childDocuments.NextSetBit(prevParentDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return 0; } // We only need to emit a single cmp value for any matching child doc int cmp = _wrappedComparer.CompareBottom(childDoc); if (cmp > 0) { return cmp; } while (true) { childDoc = _childDocuments.NextSetBit(childDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return cmp; } int cmp1 = _wrappedComparer.CompareTop(childDoc); if (cmp1 > 0) { return cmp1; } if (cmp1 == 0) { cmp = 0; } } } } /// <summary> /// Concrete implementation of <see cref="ToParentBlockJoinSortField"/> to sorts the parent docs with the highest values /// in the child / nested docs first. /// </summary> public sealed class Highest : ToParentBlockJoinFieldComparer { /// <summary> /// Create <see cref="ToParentBlockJoinFieldComparer.Highest"/> /// </summary> /// <param name="wrappedComparer">The <see cref="FieldComparer"/> on the child / nested level. </param> /// <param name="parentFilter"><see cref="Filter"/> (must produce <see cref="FixedBitSet"/> per-segment) that identifies the parent documents. </param> /// <param name="childFilter"><see cref="Filter"/> that defines which child / nested documents participates in sorting. </param> /// <param name="spareSlot">The extra slot inside the wrapped comparer that is used to compare which nested document /// inside the parent document scope is most competitive. </param> public Highest(FieldComparer wrappedComparer, Filter parentFilter, Filter childFilter, int spareSlot) : base(wrappedComparer, parentFilter, childFilter, spareSlot) { } public override int CompareBottom(int parentDoc) { if (parentDoc == 0 || _parentDocuments == null || _childDocuments == null) { return 0; } int prevParentDoc = _parentDocuments.PrevSetBit(parentDoc - 1); int childDoc = _childDocuments.NextSetBit(prevParentDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return 0; } int cmp = _wrappedComparer.CompareBottom(childDoc); if (cmp < 0) { return cmp; } while (true) { childDoc = _childDocuments.NextSetBit(childDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return cmp; } int cmp1 = _wrappedComparer.CompareBottom(childDoc); if (cmp1 < 0) { return cmp1; } else { if (cmp1 == 0) { cmp = 0; } } } } public override void Copy(int slot, int parentDoc) { if (parentDoc == 0 || _parentDocuments == null || _childDocuments == null) { return; } int prevParentDoc = _parentDocuments.PrevSetBit(parentDoc - 1); int childDoc = _childDocuments.NextSetBit(prevParentDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return; } _wrappedComparer.Copy(_spareSlot, childDoc); _wrappedComparer.Copy(slot, childDoc); while (true) { childDoc = _childDocuments.NextSetBit(childDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return; } _wrappedComparer.Copy(_spareSlot, childDoc); if (_wrappedComparer.Compare(_spareSlot, slot) > 0) { _wrappedComparer.Copy(slot, childDoc); } } } public override int CompareTop(int parentDoc) { if (parentDoc == 0 || _parentDocuments == null || _childDocuments == null) { return 0; } int prevParentDoc = _parentDocuments.PrevSetBit(parentDoc - 1); int childDoc = _childDocuments.NextSetBit(prevParentDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return 0; } int cmp = _wrappedComparer.CompareBottom(childDoc); if (cmp < 0) { return cmp; } while (true) { childDoc = _childDocuments.NextSetBit(childDoc + 1); if (childDoc >= parentDoc || childDoc == -1) { return cmp; } int cmp1 = _wrappedComparer.CompareTop(childDoc); if (cmp1 < 0) { return cmp1; } if (cmp1 == 0) { cmp = 0; } } } } } }
jeme/lucenenet
src/Lucene.Net.Join/ToParentBlockJoinFieldComparator.cs
C#
apache-2.0
14,822
module APIDemos module Home class << self # # elements # def accessibility_click self.assert wait { text(2).click } accessibility.assert end def animation_click self.assert wait { text(3).click } animation.assert end # # asserts # def assert_exists # we're on the homepage if both # of these strings are visible text_exact 'Accessibility' text_exact 'Animation' end def assert wait { self.assert_exists } end end end end module Kernel def home APIDemos::Home end end
vikramvi/tutorial
projects/ruby_android/appium/android/pages/home.rb
Ruby
apache-2.0
664
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN""http://www.w3.org/TR/REC-html40/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Fri Aug 22 03:43:54 EDT 2003 --> <TITLE> org.apache.struts.plugins (Apache Struts API Documentation) </TITLE> <META NAME="keywords" CONTENT="org.apache.struts.plugins package"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> </HEAD> <SCRIPT> function asd() { parent.document.title="org.apache.struts.plugins (Apache Struts API Documentation)"; } </SCRIPT> <BODY BGCOLOR="white" onload="asd();"> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_top"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/struts/config/impl/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/struts/taglib/bean/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" TARGET="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp; <SCRIPT> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> <H2> Package org.apache.struts.plugins </H2> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Class Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="ModuleConfigVerifier.html">ModuleConfigVerifier</A></B></TD> <TD>Convenient implementation of <A HREF="../../../../org/apache/struts/action/PlugIn.html"><CODE>PlugIn</CODE></A> that performs as many verification tests on the information stored in the <A HREF="../../../../org/apache/struts/config/ModuleConfig.html"><CODE>ModuleConfig</CODE></A> for this application module as is practical.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_bottom"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/struts/config/impl/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/struts/taglib/bean/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" TARGET="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp; <SCRIPT> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> Copyright © 2000-2003 - Apache Software Foundation </BODY> </HTML>
codelibs/cl-struts
legacy/api-1.1/org/apache/struts/plugins/package-summary.html
HTML
apache-2.0
6,119
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.view; import android.annotation.NonNull; import android.util.Log; import android.os.Looper; import android.os.MessageQueue; import com.android.internal.util.VirtualRefBasePtr; import java.lang.NullPointerException; import java.lang.ref.WeakReference; import java.lang.SuppressWarnings; /** * Provides streaming access to frame stats information from the rendering * subsystem to apps. * * @hide */ public class FrameMetricsObserver { private MessageQueue mMessageQueue; private WeakReference<Window> mWindow; private FrameMetrics mFrameMetrics; /* package */ Window.OnFrameMetricsAvailableListener mListener; /* package */ VirtualRefBasePtr mNative; /** * Creates a FrameMetricsObserver * * @param looper the looper to use when invoking callbacks */ FrameMetricsObserver(@NonNull Window window, @NonNull Looper looper, @NonNull Window.OnFrameMetricsAvailableListener listener) { if (looper == null) { throw new NullPointerException("looper cannot be null"); } mMessageQueue = looper.getQueue(); if (mMessageQueue == null) { throw new IllegalStateException("invalid looper, null message queue\n"); } mFrameMetrics = new FrameMetrics(); mWindow = new WeakReference<>(window); mListener = listener; } // Called by native on the provided Handler @SuppressWarnings("unused") private void notifyDataAvailable(int dropCount) { final Window window = mWindow.get(); if (window != null) { mListener.onFrameMetricsAvailable(window, mFrameMetrics, dropCount); } } }
xorware/android_frameworks_base
core/java/android/view/FrameMetricsObserver.java
Java
apache-2.0
2,311
/* This file was generated by upbc (the upb compiler) from the input * file: * * envoy/config/core/v3/protocol.proto * * Do not edit -- your changes will be discarded when the file is * regenerated. */ #ifndef ENVOY_CONFIG_CORE_V3_PROTOCOL_PROTO_UPBDEFS_H_ #define ENVOY_CONFIG_CORE_V3_PROTOCOL_PROTO_UPBDEFS_H_ #include "upb/def.h" #include "upb/port_def.inc" #ifdef __cplusplus extern "C" { #endif #include "upb/def.h" #include "upb/port_def.inc" extern _upb_DefPool_Init envoy_config_core_v3_protocol_proto_upbdefinit; UPB_INLINE const upb_MessageDef *envoy_config_core_v3_TcpProtocolOptions_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.TcpProtocolOptions"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_QuicKeepAliveSettings_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.QuicKeepAliveSettings"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_QuicProtocolOptions_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.QuicProtocolOptions"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_UpstreamHttpProtocolOptions_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.UpstreamHttpProtocolOptions"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_AlternateProtocolsCacheOptions_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.AlternateProtocolsCacheOptions"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_AlternateProtocolsCacheOptions_AlternateProtocolsCacheEntry_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.AlternateProtocolsCacheOptions.AlternateProtocolsCacheEntry"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_HttpProtocolOptions_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.HttpProtocolOptions"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_Http1ProtocolOptions_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.Http1ProtocolOptions"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_Http1ProtocolOptions_HeaderKeyFormat_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.Http1ProtocolOptions.HeaderKeyFormat"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_Http1ProtocolOptions_HeaderKeyFormat_ProperCaseWords_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.Http1ProtocolOptions.HeaderKeyFormat.ProperCaseWords"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_KeepaliveSettings_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.KeepaliveSettings"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_Http2ProtocolOptions_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.Http2ProtocolOptions"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_Http2ProtocolOptions_SettingsParameter_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.Http2ProtocolOptions.SettingsParameter"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_GrpcProtocolOptions_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.GrpcProtocolOptions"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_Http3ProtocolOptions_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.Http3ProtocolOptions"); } UPB_INLINE const upb_MessageDef *envoy_config_core_v3_SchemeHeaderTransformation_getmsgdef(upb_DefPool *s) { _upb_DefPool_LoadDefInit(s, &envoy_config_core_v3_protocol_proto_upbdefinit); return upb_DefPool_FindMessageByName(s, "envoy.config.core.v3.SchemeHeaderTransformation"); } #ifdef __cplusplus } /* extern "C" */ #endif #include "upb/port_undef.inc" #endif /* ENVOY_CONFIG_CORE_V3_PROTOCOL_PROTO_UPBDEFS_H_ */
grpc/grpc
src/core/ext/upbdefs-generated/envoy/config/core/v3/protocol.upbdefs.h
C
apache-2.0
5,303
<?php # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/networkmanagement/v1/trace.proto namespace Google\Cloud\NetworkManagement\V1; use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** * For display only. Metadata associated with a Compute Engine network. * * Generated from protobuf message <code>google.cloud.networkmanagement.v1.NetworkInfo</code> */ class NetworkInfo extends \Google\Protobuf\Internal\Message { /** * Name of a Compute Engine network. * * Generated from protobuf field <code>string display_name = 1;</code> */ private $display_name = ''; /** * URI of a Compute Engine network. * * Generated from protobuf field <code>string uri = 2;</code> */ private $uri = ''; /** * The IP range that matches the test. * * Generated from protobuf field <code>string matched_ip_range = 4;</code> */ private $matched_ip_range = ''; /** * Constructor. * * @param array $data { * Optional. Data for populating the Message object. * * @type string $display_name * Name of a Compute Engine network. * @type string $uri * URI of a Compute Engine network. * @type string $matched_ip_range * The IP range that matches the test. * } */ public function __construct($data = NULL) { \GPBMetadata\Google\Cloud\Networkmanagement\V1\Trace::initOnce(); parent::__construct($data); } /** * Name of a Compute Engine network. * * Generated from protobuf field <code>string display_name = 1;</code> * @return string */ public function getDisplayName() { return $this->display_name; } /** * Name of a Compute Engine network. * * Generated from protobuf field <code>string display_name = 1;</code> * @param string $var * @return $this */ public function setDisplayName($var) { GPBUtil::checkString($var, True); $this->display_name = $var; return $this; } /** * URI of a Compute Engine network. * * Generated from protobuf field <code>string uri = 2;</code> * @return string */ public function getUri() { return $this->uri; } /** * URI of a Compute Engine network. * * Generated from protobuf field <code>string uri = 2;</code> * @param string $var * @return $this */ public function setUri($var) { GPBUtil::checkString($var, True); $this->uri = $var; return $this; } /** * The IP range that matches the test. * * Generated from protobuf field <code>string matched_ip_range = 4;</code> * @return string */ public function getMatchedIpRange() { return $this->matched_ip_range; } /** * The IP range that matches the test. * * Generated from protobuf field <code>string matched_ip_range = 4;</code> * @param string $var * @return $this */ public function setMatchedIpRange($var) { GPBUtil::checkString($var, True); $this->matched_ip_range = $var; return $this; } }
googleapis/google-cloud-php-network-management
src/V1/NetworkInfo.php
PHP
apache-2.0
3,348
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/guardduty/model/ListDetectorsRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/http/URI.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::GuardDuty::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws::Http; ListDetectorsRequest::ListDetectorsRequest() : m_maxResults(0), m_maxResultsHasBeenSet(false), m_nextTokenHasBeenSet(false) { } Aws::String ListDetectorsRequest::SerializePayload() const { return {}; } void ListDetectorsRequest::AddQueryStringParameters(URI& uri) const { Aws::StringStream ss; if(m_maxResultsHasBeenSet) { ss << m_maxResults; uri.AddQueryStringParameter("maxResults", ss.str()); ss.str(""); } if(m_nextTokenHasBeenSet) { ss << m_nextToken; uri.AddQueryStringParameter("nextToken", ss.str()); ss.str(""); } }
awslabs/aws-sdk-cpp
aws-cpp-sdk-guardduty/source/model/ListDetectorsRequest.cpp
C++
apache-2.0
1,071
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const crypto = require("crypto"); const SortableSet = require("../util/SortableSet"); const GraphHelpers = require("../GraphHelpers"); const { isSubset } = require("../util/SetHelpers"); const deterministicGrouping = require("../util/deterministicGrouping"); const MinMaxSizeWarning = require("./MinMaxSizeWarning"); const contextify = require("../util/identifier").contextify; /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Module")} Module */ /** @typedef {import("../util/deterministicGrouping").Options<Module>} DeterministicGroupingOptionsForModule */ /** @typedef {import("../util/deterministicGrouping").GroupedItems<Module>} DeterministicGroupingGroupedItemsForModule */ const deterministicGroupingForModules = /** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ (deterministicGrouping); const hashFilename = name => { return crypto .createHash("md4") .update(name) .digest("hex") .slice(0, 8); }; const sortByIdentifier = (a, b) => { if (a.identifier() > b.identifier()) return 1; if (a.identifier() < b.identifier()) return -1; return 0; }; const getRequests = chunk => { let requests = 0; for (const chunkGroup of chunk.groupsIterable) { requests = Math.max(requests, chunkGroup.chunks.length); } return requests; }; const getModulesSize = modules => { let sum = 0; for (const m of modules) { sum += m.size(); } return sum; }; /** * @template T * @param {Set<T>} a set * @param {Set<T>} b other set * @returns {boolean} true if at least one item of a is in b */ const isOverlap = (a, b) => { for (const item of a) { if (b.has(item)) return true; } return false; }; const compareEntries = (a, b) => { // 1. by priority const diffPriority = a.cacheGroup.priority - b.cacheGroup.priority; if (diffPriority) return diffPriority; // 2. by number of chunks const diffCount = a.chunks.size - b.chunks.size; if (diffCount) return diffCount; // 3. by size reduction const aSizeReduce = a.size * (a.chunks.size - 1); const bSizeReduce = b.size * (b.chunks.size - 1); const diffSizeReduce = aSizeReduce - bSizeReduce; if (diffSizeReduce) return diffSizeReduce; // 4. by number of modules (to be able to compare by identifier) const modulesA = a.modules; const modulesB = b.modules; const diff = modulesA.size - modulesB.size; if (diff) return diff; // 5. by module identifiers modulesA.sort(); modulesB.sort(); const aI = modulesA[Symbol.iterator](); const bI = modulesB[Symbol.iterator](); // eslint-disable-next-line no-constant-condition while (true) { const aItem = aI.next(); const bItem = bI.next(); if (aItem.done) return 0; const aModuleIdentifier = aItem.value.identifier(); const bModuleIdentifier = bItem.value.identifier(); if (aModuleIdentifier > bModuleIdentifier) return -1; if (aModuleIdentifier < bModuleIdentifier) return 1; } }; const compareNumbers = (a, b) => a - b; const INITIAL_CHUNK_FILTER = chunk => chunk.canBeInitial(); const ASYNC_CHUNK_FILTER = chunk => !chunk.canBeInitial(); const ALL_CHUNK_FILTER = chunk => true; module.exports = class SplitChunksPlugin { constructor(options) { this.options = SplitChunksPlugin.normalizeOptions(options); } static normalizeOptions(options = {}) { return { chunksFilter: SplitChunksPlugin.normalizeChunksFilter( options.chunks || "all" ), minSize: options.minSize || 0, maxSize: options.maxSize || 0, minChunks: options.minChunks || 1, maxAsyncRequests: options.maxAsyncRequests || 1, maxInitialRequests: options.maxInitialRequests || 1, hidePathInfo: options.hidePathInfo || false, filename: options.filename || undefined, getCacheGroups: SplitChunksPlugin.normalizeCacheGroups({ cacheGroups: options.cacheGroups, name: options.name, automaticNameDelimiter: options.automaticNameDelimiter, automaticNameMaxLength: options.automaticNameMaxLength }), automaticNameDelimiter: options.automaticNameDelimiter, automaticNameMaxLength: options.automaticNameMaxLength || 109, fallbackCacheGroup: SplitChunksPlugin.normalizeFallbackCacheGroup( options.fallbackCacheGroup || {}, options ) }; } static normalizeName({ name, automaticNameDelimiter, automaticNamePrefix, automaticNameMaxLength }) { if (name === true) { /** @type {WeakMap<Chunk[], Record<string, string>>} */ const cache = new WeakMap(); const fn = (module, chunks, cacheGroup) => { let cacheEntry = cache.get(chunks); if (cacheEntry === undefined) { cacheEntry = {}; cache.set(chunks, cacheEntry); } else if (cacheGroup in cacheEntry) { return cacheEntry[cacheGroup]; } const names = chunks.map(c => c.name); if (!names.every(Boolean)) { cacheEntry[cacheGroup] = undefined; return; } names.sort(); const prefix = typeof automaticNamePrefix === "string" ? automaticNamePrefix : cacheGroup; const namePrefix = prefix ? prefix + automaticNameDelimiter : ""; let name = namePrefix + names.join(automaticNameDelimiter); // Filenames and paths can't be too long otherwise an // ENAMETOOLONG error is raised. If the generated name if too // long, it is truncated and a hash is appended. The limit has // been set to 109 to prevent `[name].[chunkhash].[ext]` from // generating a 256+ character string. if (name.length > automaticNameMaxLength) { const hashedFilename = hashFilename(name); const sliceLength = automaticNameMaxLength - (automaticNameDelimiter.length + hashedFilename.length); name = name.slice(0, sliceLength) + automaticNameDelimiter + hashFilename(name); } cacheEntry[cacheGroup] = name; return name; }; return fn; } if (typeof name === "string") { const fn = () => { return name; }; return fn; } if (typeof name === "function") return name; } static normalizeChunksFilter(chunks) { if (chunks === "initial") { return INITIAL_CHUNK_FILTER; } if (chunks === "async") { return ASYNC_CHUNK_FILTER; } if (chunks === "all") { return ALL_CHUNK_FILTER; } if (typeof chunks === "function") return chunks; } static normalizeFallbackCacheGroup( { minSize = undefined, maxSize = undefined, automaticNameDelimiter = undefined }, { minSize: defaultMinSize = undefined, maxSize: defaultMaxSize = undefined, automaticNameDelimiter: defaultAutomaticNameDelimiter = undefined } ) { return { minSize: typeof minSize === "number" ? minSize : defaultMinSize || 0, maxSize: typeof maxSize === "number" ? maxSize : defaultMaxSize || 0, automaticNameDelimiter: automaticNameDelimiter || defaultAutomaticNameDelimiter || "~" }; } static normalizeCacheGroups({ cacheGroups, name, automaticNameDelimiter, automaticNameMaxLength }) { if (typeof cacheGroups === "function") { // TODO webpack 5 remove this if (cacheGroups.length !== 1) { return module => cacheGroups(module, module.getChunks()); } return cacheGroups; } if (cacheGroups && typeof cacheGroups === "object") { const fn = module => { let results; for (const key of Object.keys(cacheGroups)) { let option = cacheGroups[key]; if (option === false) continue; if (option instanceof RegExp || typeof option === "string") { option = { test: option }; } if (typeof option === "function") { let result = option(module); if (result) { if (results === undefined) results = []; for (const r of Array.isArray(result) ? result : [result]) { const result = Object.assign({ key }, r); if (result.name) result.getName = () => result.name; if (result.chunks) { result.chunksFilter = SplitChunksPlugin.normalizeChunksFilter( result.chunks ); } results.push(result); } } } else if (SplitChunksPlugin.checkTest(option.test, module)) { if (results === undefined) results = []; results.push({ key: key, priority: option.priority, getName: SplitChunksPlugin.normalizeName({ name: option.name || name, automaticNameDelimiter: typeof option.automaticNameDelimiter === "string" ? option.automaticNameDelimiter : automaticNameDelimiter, automaticNamePrefix: option.automaticNamePrefix, automaticNameMaxLength: option.automaticNameMaxLength || automaticNameMaxLength }) || (() => {}), chunksFilter: SplitChunksPlugin.normalizeChunksFilter( option.chunks ), enforce: option.enforce, minSize: option.minSize, maxSize: option.maxSize, minChunks: option.minChunks, maxAsyncRequests: option.maxAsyncRequests, maxInitialRequests: option.maxInitialRequests, filename: option.filename, reuseExistingChunk: option.reuseExistingChunk }); } } return results; }; return fn; } const fn = () => {}; return fn; } static checkTest(test, module) { if (test === undefined) return true; if (typeof test === "function") { if (test.length !== 1) { return test(module, module.getChunks()); } return test(module); } if (typeof test === "boolean") return test; if (typeof test === "string") { if ( module.nameForCondition && module.nameForCondition().startsWith(test) ) { return true; } for (const chunk of module.chunksIterable) { if (chunk.name && chunk.name.startsWith(test)) { return true; } } return false; } if (test instanceof RegExp) { if (module.nameForCondition && test.test(module.nameForCondition())) { return true; } for (const chunk of module.chunksIterable) { if (chunk.name && test.test(chunk.name)) { return true; } } return false; } return false; } /** * @param {Compiler} compiler webpack compiler * @returns {void} */ apply(compiler) { compiler.hooks.thisCompilation.tap("SplitChunksPlugin", compilation => { let alreadyOptimized = false; compilation.hooks.unseal.tap("SplitChunksPlugin", () => { alreadyOptimized = false; }); compilation.hooks.optimizeChunksAdvanced.tap( "SplitChunksPlugin", chunks => { if (alreadyOptimized) return; alreadyOptimized = true; // Give each selected chunk an index (to create strings from chunks) const indexMap = new Map(); let index = 1; for (const chunk of chunks) { indexMap.set(chunk, index++); } const getKey = chunks => { return Array.from(chunks, c => indexMap.get(c)) .sort(compareNumbers) .join(); }; /** @type {Map<string, Set<Chunk>>} */ const chunkSetsInGraph = new Map(); for (const module of compilation.modules) { const chunksKey = getKey(module.chunksIterable); if (!chunkSetsInGraph.has(chunksKey)) { chunkSetsInGraph.set(chunksKey, new Set(module.chunksIterable)); } } // group these set of chunks by count // to allow to check less sets via isSubset // (only smaller sets can be subset) /** @type {Map<number, Array<Set<Chunk>>>} */ const chunkSetsByCount = new Map(); for (const chunksSet of chunkSetsInGraph.values()) { const count = chunksSet.size; let array = chunkSetsByCount.get(count); if (array === undefined) { array = []; chunkSetsByCount.set(count, array); } array.push(chunksSet); } // Create a list of possible combinations const combinationsCache = new Map(); // Map<string, Set<Chunk>[]> const getCombinations = key => { const chunksSet = chunkSetsInGraph.get(key); var array = [chunksSet]; if (chunksSet.size > 1) { for (const [count, setArray] of chunkSetsByCount) { // "equal" is not needed because they would have been merge in the first step if (count < chunksSet.size) { for (const set of setArray) { if (isSubset(chunksSet, set)) { array.push(set); } } } } } return array; }; /** * @typedef {Object} SelectedChunksResult * @property {Chunk[]} chunks the list of chunks * @property {string} key a key of the list */ /** * @typedef {function(Chunk): boolean} ChunkFilterFunction */ /** @type {WeakMap<Set<Chunk>, WeakMap<ChunkFilterFunction, SelectedChunksResult>>} */ const selectedChunksCacheByChunksSet = new WeakMap(); /** * get list and key by applying the filter function to the list * It is cached for performance reasons * @param {Set<Chunk>} chunks list of chunks * @param {ChunkFilterFunction} chunkFilter filter function for chunks * @returns {SelectedChunksResult} list and key */ const getSelectedChunks = (chunks, chunkFilter) => { let entry = selectedChunksCacheByChunksSet.get(chunks); if (entry === undefined) { entry = new WeakMap(); selectedChunksCacheByChunksSet.set(chunks, entry); } /** @type {SelectedChunksResult} */ let entry2 = entry.get(chunkFilter); if (entry2 === undefined) { /** @type {Chunk[]} */ const selectedChunks = []; for (const chunk of chunks) { if (chunkFilter(chunk)) selectedChunks.push(chunk); } entry2 = { chunks: selectedChunks, key: getKey(selectedChunks) }; entry.set(chunkFilter, entry2); } return entry2; }; /** * @typedef {Object} ChunksInfoItem * @property {SortableSet} modules * @property {TODO} cacheGroup * @property {string} name * @property {boolean} validateSize * @property {number} size * @property {Set<Chunk>} chunks * @property {Set<Chunk>} reuseableChunks * @property {Set<string>} chunksKeys */ // Map a list of chunks to a list of modules // For the key the chunk "index" is used, the value is a SortableSet of modules /** @type {Map<string, ChunksInfoItem>} */ const chunksInfoMap = new Map(); /** * @param {TODO} cacheGroup the current cache group * @param {Chunk[]} selectedChunks chunks selected for this module * @param {string} selectedChunksKey a key of selectedChunks * @param {Module} module the current module * @returns {void} */ const addModuleToChunksInfoMap = ( cacheGroup, selectedChunks, selectedChunksKey, module ) => { // Break if minimum number of chunks is not reached if (selectedChunks.length < cacheGroup.minChunks) return; // Determine name for split chunk const name = cacheGroup.getName( module, selectedChunks, cacheGroup.key ); // Create key for maps // When it has a name we use the name as key // Elsewise we create the key from chunks and cache group key // This automatically merges equal names const key = cacheGroup.key + (name ? ` name:${name}` : ` chunks:${selectedChunksKey}`); // Add module to maps let info = chunksInfoMap.get(key); if (info === undefined) { chunksInfoMap.set( key, (info = { modules: new SortableSet(undefined, sortByIdentifier), cacheGroup, name, validateSize: cacheGroup.minSize > 0, size: 0, chunks: new Set(), reuseableChunks: new Set(), chunksKeys: new Set() }) ); } info.modules.add(module); if (info.validateSize) { info.size += module.size(); } if (!info.chunksKeys.has(selectedChunksKey)) { info.chunksKeys.add(selectedChunksKey); for (const chunk of selectedChunks) { info.chunks.add(chunk); } } }; // Walk through all modules for (const module of compilation.modules) { // Get cache group let cacheGroups = this.options.getCacheGroups(module); if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { continue; } // Prepare some values const chunksKey = getKey(module.chunksIterable); let combs = combinationsCache.get(chunksKey); if (combs === undefined) { combs = getCombinations(chunksKey); combinationsCache.set(chunksKey, combs); } for (const cacheGroupSource of cacheGroups) { const cacheGroup = { key: cacheGroupSource.key, priority: cacheGroupSource.priority || 0, chunksFilter: cacheGroupSource.chunksFilter || this.options.chunksFilter, minSize: cacheGroupSource.minSize !== undefined ? cacheGroupSource.minSize : cacheGroupSource.enforce ? 0 : this.options.minSize, minSizeForMaxSize: cacheGroupSource.minSize !== undefined ? cacheGroupSource.minSize : this.options.minSize, maxSize: cacheGroupSource.maxSize !== undefined ? cacheGroupSource.maxSize : cacheGroupSource.enforce ? 0 : this.options.maxSize, minChunks: cacheGroupSource.minChunks !== undefined ? cacheGroupSource.minChunks : cacheGroupSource.enforce ? 1 : this.options.minChunks, maxAsyncRequests: cacheGroupSource.maxAsyncRequests !== undefined ? cacheGroupSource.maxAsyncRequests : cacheGroupSource.enforce ? Infinity : this.options.maxAsyncRequests, maxInitialRequests: cacheGroupSource.maxInitialRequests !== undefined ? cacheGroupSource.maxInitialRequests : cacheGroupSource.enforce ? Infinity : this.options.maxInitialRequests, getName: cacheGroupSource.getName !== undefined ? cacheGroupSource.getName : this.options.getName, filename: cacheGroupSource.filename !== undefined ? cacheGroupSource.filename : this.options.filename, automaticNameDelimiter: cacheGroupSource.automaticNameDelimiter !== undefined ? cacheGroupSource.automaticNameDelimiter : this.options.automaticNameDelimiter, reuseExistingChunk: cacheGroupSource.reuseExistingChunk }; // For all combination of chunk selection for (const chunkCombination of combs) { // Break if minimum number of chunks is not reached if (chunkCombination.size < cacheGroup.minChunks) continue; // Select chunks by configuration const { chunks: selectedChunks, key: selectedChunksKey } = getSelectedChunks( chunkCombination, cacheGroup.chunksFilter ); addModuleToChunksInfoMap( cacheGroup, selectedChunks, selectedChunksKey, module ); } } } // Filter items were size < minSize for (const pair of chunksInfoMap) { const info = pair[1]; if (info.validateSize && info.size < info.cacheGroup.minSize) { chunksInfoMap.delete(pair[0]); } } /** @type {Map<Chunk, {minSize: number, maxSize: number, automaticNameDelimiter: string, keys: string[]}>} */ const maxSizeQueueMap = new Map(); while (chunksInfoMap.size > 0) { // Find best matching entry let bestEntryKey; let bestEntry; for (const pair of chunksInfoMap) { const key = pair[0]; const info = pair[1]; if (bestEntry === undefined) { bestEntry = info; bestEntryKey = key; } else if (compareEntries(bestEntry, info) < 0) { bestEntry = info; bestEntryKey = key; } } const item = bestEntry; chunksInfoMap.delete(bestEntryKey); let chunkName = item.name; // Variable for the new chunk (lazy created) /** @type {Chunk} */ let newChunk; // When no chunk name, check if we can reuse a chunk instead of creating a new one let isReused = false; if (item.cacheGroup.reuseExistingChunk) { outer: for (const chunk of item.chunks) { if (chunk.getNumberOfModules() !== item.modules.size) continue; if (chunk.hasEntryModule()) continue; for (const module of item.modules) { if (!chunk.containsModule(module)) continue outer; } if (!newChunk || !newChunk.name) { newChunk = chunk; } else if ( chunk.name && chunk.name.length < newChunk.name.length ) { newChunk = chunk; } else if ( chunk.name && chunk.name.length === newChunk.name.length && chunk.name < newChunk.name ) { newChunk = chunk; } chunkName = undefined; isReused = true; } } // Check if maxRequests condition can be fulfilled const usedChunks = Array.from(item.chunks).filter(chunk => { // skip if we address ourself return ( (!chunkName || chunk.name !== chunkName) && chunk !== newChunk ); }); // Skip when no chunk selected if (usedChunks.length === 0) continue; let validChunks = usedChunks; if ( Number.isFinite(item.cacheGroup.maxInitialRequests) || Number.isFinite(item.cacheGroup.maxAsyncRequests) ) { validChunks = validChunks.filter(chunk => { // respect max requests when not enforced const maxRequests = chunk.isOnlyInitial() ? item.cacheGroup.maxInitialRequests : chunk.canBeInitial() ? Math.min( item.cacheGroup.maxInitialRequests, item.cacheGroup.maxAsyncRequests ) : item.cacheGroup.maxAsyncRequests; return ( !isFinite(maxRequests) || getRequests(chunk) < maxRequests ); }); } validChunks = validChunks.filter(chunk => { for (const module of item.modules) { if (chunk.containsModule(module)) return true; } return false; }); if (validChunks.length < usedChunks.length) { if (validChunks.length >= item.cacheGroup.minChunks) { for (const module of item.modules) { addModuleToChunksInfoMap( item.cacheGroup, validChunks, getKey(validChunks), module ); } } continue; } // Create the new chunk if not reusing one if (!isReused) { newChunk = compilation.addChunk(chunkName); } // Walk through all chunks for (const chunk of usedChunks) { // Add graph connections for splitted chunk chunk.split(newChunk); } // Add a note to the chunk newChunk.chunkReason = isReused ? "reused as split chunk" : "split chunk"; if (item.cacheGroup.key) { newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`; } if (chunkName) { newChunk.chunkReason += ` (name: ${chunkName})`; // If the chosen name is already an entry point we remove the entry point const entrypoint = compilation.entrypoints.get(chunkName); if (entrypoint) { compilation.entrypoints.delete(chunkName); entrypoint.remove(); newChunk.entryModule = undefined; } } if (item.cacheGroup.filename) { if (!newChunk.isOnlyInitial()) { throw new Error( "SplitChunksPlugin: You are trying to set a filename for a chunk which is (also) loaded on demand. " + "The runtime can only handle loading of chunks which match the chunkFilename schema. " + "Using a custom filename would fail at runtime. " + `(cache group: ${item.cacheGroup.key})` ); } newChunk.filenameTemplate = item.cacheGroup.filename; } if (!isReused) { // Add all modules to the new chunk for (const module of item.modules) { if (typeof module.chunkCondition === "function") { if (!module.chunkCondition(newChunk)) continue; } // Add module to new chunk GraphHelpers.connectChunkAndModule(newChunk, module); // Remove module from used chunks for (const chunk of usedChunks) { chunk.removeModule(module); module.rewriteChunkInReasons(chunk, [newChunk]); } } } else { // Remove all modules from used chunks for (const module of item.modules) { for (const chunk of usedChunks) { chunk.removeModule(module); module.rewriteChunkInReasons(chunk, [newChunk]); } } } if (item.cacheGroup.maxSize > 0) { const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk); maxSizeQueueMap.set(newChunk, { minSize: Math.max( oldMaxSizeSettings ? oldMaxSizeSettings.minSize : 0, item.cacheGroup.minSizeForMaxSize ), maxSize: Math.min( oldMaxSizeSettings ? oldMaxSizeSettings.maxSize : Infinity, item.cacheGroup.maxSize ), automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter, keys: oldMaxSizeSettings ? oldMaxSizeSettings.keys.concat(item.cacheGroup.key) : [item.cacheGroup.key] }); } // remove all modules from other entries and update size for (const [key, info] of chunksInfoMap) { if (isOverlap(info.chunks, item.chunks)) { if (info.validateSize) { // update modules and total size // may remove it from the map when < minSize const oldSize = info.modules.size; for (const module of item.modules) { info.modules.delete(module); } if (info.modules.size === 0) { chunksInfoMap.delete(key); continue; } if (info.modules.size !== oldSize) { info.size = getModulesSize(info.modules); if (info.size < info.cacheGroup.minSize) { chunksInfoMap.delete(key); } } } else { // only update the modules for (const module of item.modules) { info.modules.delete(module); } if (info.modules.size === 0) { chunksInfoMap.delete(key); } } } } } const incorrectMinMaxSizeSet = new Set(); // Make sure that maxSize is fulfilled for (const chunk of compilation.chunks.slice()) { const { minSize, maxSize, automaticNameDelimiter, keys } = maxSizeQueueMap.get(chunk) || this.options.fallbackCacheGroup; if (!maxSize) continue; if (minSize > maxSize) { const warningKey = `${keys && keys.join()} ${minSize} ${maxSize}`; if (!incorrectMinMaxSizeSet.has(warningKey)) { incorrectMinMaxSizeSet.add(warningKey); compilation.warnings.push( new MinMaxSizeWarning(keys, minSize, maxSize) ); } } const results = deterministicGroupingForModules({ maxSize: Math.max(minSize, maxSize), minSize, items: chunk.modulesIterable, getKey(module) { const ident = contextify( compilation.options.context, module.identifier() ); const name = module.nameForCondition ? contextify( compilation.options.context, module.nameForCondition() ) : ident.replace(/^.*!|\?[^?!]*$/g, ""); const fullKey = name + automaticNameDelimiter + hashFilename(ident); return fullKey.replace(/[\\/?]/g, "_"); }, getSize(module) { return module.size(); } }); results.sort((a, b) => { if (a.key < b.key) return -1; if (a.key > b.key) return 1; return 0; }); for (let i = 0; i < results.length; i++) { const group = results[i]; const key = this.options.hidePathInfo ? hashFilename(group.key) : group.key; let name = chunk.name ? chunk.name + automaticNameDelimiter + key : null; if (name && name.length > 100) { name = name.slice(0, 100) + automaticNameDelimiter + hashFilename(name); } let newPart; if (i !== results.length - 1) { newPart = compilation.addChunk(name); chunk.split(newPart); newPart.chunkReason = chunk.chunkReason; // Add all modules to the new chunk for (const module of group.items) { if (typeof module.chunkCondition === "function") { if (!module.chunkCondition(newPart)) continue; } // Add module to new chunk GraphHelpers.connectChunkAndModule(newPart, module); // Remove module from used chunks chunk.removeModule(module); module.rewriteChunkInReasons(chunk, [newPart]); } } else { // change the chunk to be a part newPart = chunk; chunk.name = name; } } } } ); }); } };
cloudfoundry-community/asp.net5-buildpack
fixtures/node_apps/angular_dotnet/ClientApp/node_modules/webpack/lib/optimize/SplitChunksPlugin.js
JavaScript
apache-2.0
29,448
//===----------------------------------------------------------------------===// // // Peloton // // index_tuner.cpp // // Identification: src/brain/index_tuner.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "brain/index_tuner.h" #include <algorithm> #include "brain/brain_util.h" #include "concurrency/transaction_manager_factory.h" #include "brain/clusterer.h" #include "catalog/catalog.h" #include "catalog/schema.h" #include "common/container_tuple.h" #include "common/logger.h" #include "common/macros.h" #include "common/timer.h" #include "index/index_factory.h" #include "storage/data_table.h" #include "storage/tile_group.h" namespace peloton { namespace brain { IndexTuner& IndexTuner::GetInstance() { static IndexTuner index_tuner; return index_tuner; } IndexTuner::IndexTuner() { tile_groups_indexed_ = 0; // Nothing to do here ! } IndexTuner::~IndexTuner() {} void IndexTuner::Start() { // Set signal index_tuning_stop = false; // Launch thread index_tuner_thread = std::thread(&brain::IndexTuner::Tune, this); LOG_INFO("Started index tuner"); } // Add an ad-hoc index static void AddIndex(storage::DataTable* table, std::set<oid_t> suggested_index_attrs) { // Construct index metadata std::vector<oid_t> key_attrs(suggested_index_attrs.size()); std::copy(suggested_index_attrs.begin(), suggested_index_attrs.end(), key_attrs.begin()); auto index_count = table->GetIndexCount(); auto index_oid = index_count + 1; auto tuple_schema = table->GetSchema(); catalog::Schema* key_schema; index::IndexMetadata* index_metadata; bool unique; key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs); key_schema->SetIndexedColumns(key_attrs); unique = true; index_metadata = new index::IndexMetadata( "adhoc_index_" + std::to_string(index_oid), index_oid, table->GetOid(), table->GetDatabaseOid(), IndexType::BWTREE, IndexConstraintType::PRIMARY_KEY, tuple_schema, key_schema, key_attrs, unique); // Set initial utility ratio double intial_utility_ratio = 0.5; index_metadata->SetUtility(intial_utility_ratio); std::shared_ptr<index::Index> adhoc_index( index::IndexFactory::GetIndex(index_metadata)); // Add index table->AddIndex(adhoc_index); LOG_DEBUG("Creating index : %s", index_metadata->GetInfo().c_str()); } void IndexTuner::BuildIndex(storage::DataTable* table, std::shared_ptr<index::Index> index) { auto table_schema = table->GetSchema(); auto index_tile_group_offset = index->GetIndexedTileGroupOff(); auto table_tile_group_count = table->GetTileGroupCount(); oid_t tile_groups_indexed = 0; auto index_schema = index->GetKeySchema(); auto indexed_columns = index_schema->GetIndexedColumns(); std::unique_ptr<storage::Tuple> key(new storage::Tuple(index_schema, true)); while (index_tile_group_offset < table_tile_group_count && (tile_groups_indexed < tile_groups_indexed_per_iteration)) { std::unique_ptr<storage::Tuple> tuple_ptr( new storage::Tuple(table_schema, true)); auto tile_group = table->GetTileGroup(index_tile_group_offset); auto tile_group_id = tile_group->GetTileGroupId(); oid_t active_tuple_count = tile_group->GetNextTupleSlot(); for (oid_t tuple_id = 0; tuple_id < active_tuple_count; tuple_id++) { // Setup container tuple ContainerTuple<storage::TileGroup> container_tuple(tile_group.get(), tuple_id); // Set the location ItemPointer location(tile_group_id, tuple_id); // Set the key key->SetFromTuple(&container_tuple, indexed_columns, index->GetPool()); // Insert in specific index // TODO: Allocate itempointer ? index->InsertEntry(key.get(), &location); } // Update indexed tile group offset (set of tgs indexed) index->IncrementIndexedTileGroupOffset(); index_tile_group_offset++; tile_groups_indexed++; } tile_groups_indexed_ += tile_groups_indexed; } void IndexTuner::BuildIndices(storage::DataTable* table) { oid_t index_count = table->GetIndexCount(); for (oid_t index_itr = 0; index_itr < index_count; index_itr++) { // Get index auto index = table->GetIndex(index_itr); if (index == nullptr) { continue; } // Build index // BuildIndex(table, index); } } double IndexTuner::ComputeWorkloadWriteRatio( const std::vector<brain::Sample>& samples) { double write_ratio = 0; double total_read_duration = 0; double total_write_duration = 0; // Go over all samples for (auto sample : samples) { if (sample.GetSampleType() == SampleType::ACCESS) { total_read_duration += sample.GetWeight(); } else if (sample.GetSampleType() == SampleType::UPDATE) { total_write_duration += sample.GetWeight(); } else { throw Exception("Unknown sample type : " + std::to_string(static_cast<int>(sample.GetSampleType()))); } } // Compute write ratio auto total_duration = total_read_duration + total_write_duration; PL_ASSERT(total_duration > 0); write_ratio = total_write_duration / (total_duration); // Compute exponential moving average if (average_write_ratio == INVALID_RATIO) { average_write_ratio = write_ratio; } else { // S_t = alpha * Y_t + (1 - alpha) * S_t-1 average_write_ratio = write_ratio * alpha + (1 - alpha) * average_write_ratio; } LOG_TRACE("Average write Ratio : %.2lf", average_write_ratio); return average_write_ratio; } typedef std::pair<brain::Sample, double> sample_frequency_map_entry; bool SampleFrequencyMapEntryComparator(sample_frequency_map_entry a, sample_frequency_map_entry b) { return a.second > b.second; } std::vector<sample_frequency_map_entry> GetFrequentSamples( const std::vector<brain::Sample>& samples) { std::unordered_map<brain::Sample, double> sample_frequency_map; double total_weight = 0; // Go over all samples for (auto sample : samples) { if (sample.GetSampleType() == SampleType::ACCESS) { // Update sample count sample_frequency_map[sample] += sample.GetWeight(); total_weight += sample.GetWeight(); } else if (sample.GetSampleType() == SampleType::UPDATE) { // Update sample count sample_frequency_map[sample] += sample.GetWeight(); total_weight += sample.GetWeight(); } else { throw Exception("Unknown sample type : " + std::to_string(static_cast<int>(sample.GetSampleType()))); } } PL_ASSERT(total_weight > 0); // Normalize std::unordered_map<brain::Sample, double>::iterator sample_frequency_map_itr; for (sample_frequency_map_itr = sample_frequency_map.begin(); sample_frequency_map_itr != sample_frequency_map.end(); ++sample_frequency_map_itr) { // Normalize sample's utility sample_frequency_map_itr->second /= total_weight; } std::vector<sample_frequency_map_entry> sample_frequency_entry_list; for (auto sample_frequency_map_entry : sample_frequency_map) { auto entry = std::make_pair(sample_frequency_map_entry.first, sample_frequency_map_entry.second); sample_frequency_entry_list.push_back(entry); } std::sort(sample_frequency_entry_list.begin(), sample_frequency_entry_list.end(), SampleFrequencyMapEntryComparator); // Print sample frequency map for (auto sample_frequency_map_entry : sample_frequency_map) { LOG_TRACE("Sample: %s Utility %.1lf", sample_frequency_map_entry.first.GetInfo().c_str(), sample_frequency_map_entry.second); } return sample_frequency_entry_list; } std::vector<std::vector<double>> GetSuggestedIndices( const std::vector<sample_frequency_map_entry>& list) { // Find frequent samples size_t frequency_rank_threshold = 10; // Print top-k frequent samples for table std::vector<std::vector<double>> suggested_indices; auto list_size = list.size(); for (size_t entry_itr = 0; (entry_itr < frequency_rank_threshold) && (entry_itr < list_size); entry_itr++) { auto& entry = list[entry_itr]; auto& sample = entry.first; LOG_TRACE("%s Utility : %.2lf", sample.GetInfo().c_str(), entry.second); suggested_indices.push_back(sample.GetColumnsAccessed()); } return suggested_indices; } double GetCurrentIndexUtility( std::set<oid_t> suggested_index_set, const std::vector<sample_frequency_map_entry>& list) { double current_index_utility = 0; auto list_size = list.size(); for (size_t entry_itr = 0; entry_itr < list_size; entry_itr++) { auto& entry = list[entry_itr]; auto& sample = entry.first; auto& columns = sample.GetColumnsAccessed(); std::set<oid_t> columns_set(columns.begin(), columns.end()); if (columns_set == suggested_index_set) { LOG_TRACE("Sample~Index Match : %s ", sample.GetInfo().c_str()); current_index_utility = entry.second; break; } } return current_index_utility; } void IndexTuner::DropIndexes(storage::DataTable* table) { oid_t index_count = table->GetIndexCount(); // Go over indices oid_t index_itr; for (index_itr = 0; index_itr < index_count; index_itr++) { auto index = table->GetIndex(index_itr); if (index == nullptr) { continue; } // auto average_index_utility = index_metadata->GetUtility(); auto index_oid = index->GetOid(); // Check if index utility below threshold and drop if needed // if (average_index_utility < index_utility_threshold) { LOG_DEBUG("Dropping index : %s", index->GetMetadata()->GetInfo().c_str()); table->DropIndexWithOid(index_oid); // Drop one index at a time return; // Update index count index_count = table->GetIndexCount(); // } } } void IndexTuner::AddIndexes( storage::DataTable* table, const std::vector<std::vector<double>>& suggested_indices) { oid_t valid_index_count = table->GetValidIndexCount(); size_t constructed_index_itr = 0; // Check if we have constructed too many indexess if (valid_index_count > index_count_threshold) { LOG_TRACE("Constructed too many indexes"); return; } for (auto suggested_index : suggested_indices) { std::set<oid_t> suggested_index_set(suggested_index.begin(), suggested_index.end()); if (suggested_index_set.empty()) continue; // Go over all indices bool suggested_index_found = false; oid_t index_count = table->GetIndexCount(); oid_t index_itr; for (index_itr = 0; index_itr < index_count; index_itr++) { // Check attributes auto index_attrs = table->GetIndexAttrs(index_itr); if (index_attrs != suggested_index_set) { continue; } // Exact match suggested_index_found = true; break; } // Did we find suggested index ? if (visibility_mode_ == false && suggested_index_found == false) { LOG_TRACE("Did not find suggested index."); // Add adhoc index with given utility AddIndex(table, suggested_index_set); constructed_index_itr++; } // Found suggested index, enable it else if (suggested_index_found == true) { LOG_TRACE("Found suggested index."); // Make it visible if it already isn't auto index = table->GetIndex(index_itr); auto index_metadata = index->GetMetadata(); auto index_is_visible = index_metadata->GetVisibility(); if (index_is_visible == false) { LOG_INFO("Enabling index : %s", index_metadata->GetName().c_str()); index_metadata->SetVisibility(true); } } } } void UpdateIndexUtility(storage::DataTable* table, const std::vector<sample_frequency_map_entry>& list) { oid_t index_count = table->GetIndexCount(); for (oid_t index_itr = 0; index_itr < index_count; index_itr++) { // Get index auto index = table->GetIndex(index_itr); if (index == nullptr) { continue; } auto index_metadata = index->GetMetadata(); auto index_key_attrs = index_metadata->GetKeyAttrs(); std::set<oid_t> index_set(index_key_attrs.begin(), index_key_attrs.end()); // Get current index utility auto current_index_utility = GetCurrentIndexUtility(index_set, list); auto average_index_utility = index_metadata->GetUtility(); LOG_TRACE("Average index utility %5.2lf", average_index_utility); LOG_TRACE("Current index utility %5.2lf", current_index_utility); // alpha (weight for old samples) double alpha = 0.2; // Update index utility auto updated_average_index_utility = alpha * current_index_utility + (1 - alpha) * average_index_utility; index_metadata->SetUtility(updated_average_index_utility); LOG_TRACE("Updated index utility %5.2lf :: %s", updated_average_index_utility, index_metadata->GetInfo().c_str()); } } void PrintIndexInformation(storage::DataTable* table) { oid_t index_count = table->GetIndexCount(); auto table_tilegroup_count = table->GetTileGroupCount(); LOG_INFO("Index count : %u", table->GetValidIndexCount()); for (oid_t index_itr = 0; index_itr < index_count; index_itr++) { // Get index auto index = table->GetIndex(index_itr); if (index == nullptr) { continue; } auto indexed_tile_group_offset = index->GetIndexedTileGroupOff(); // Get percentage completion double fraction = 0.0; if (table_tilegroup_count != 0) { fraction = (double)indexed_tile_group_offset / (double)table_tilegroup_count; fraction *= 100; } LOG_DEBUG("%s %.1f%%", index->GetMetadata()->GetInfo().c_str(), fraction); } } void IndexTuner::Analyze(storage::DataTable* table) { // Process all samples in table auto samples = table->GetIndexSamples(); // Check write ratio auto average_write_ratio = ComputeWorkloadWriteRatio(samples); // Determine frequent samples auto sample_frequency_entry_list = GetFrequentSamples(samples); // Compute suggested indices auto suggested_indices = GetSuggestedIndices(sample_frequency_entry_list); // Check index storage footprint auto valid_index_count = table->GetValidIndexCount(); //////////////////////////////////////////////// // Drop indexes if // a) constructed too many indexes // b) write intensive workloads //////////////////////////////////////////////// auto index_overflow = (valid_index_count > index_count_threshold); auto write_intensive_workload = (average_write_ratio > write_ratio_threshold); // Skip drop table time if (visibility_mode_ == false) { if (index_overflow == true || write_intensive_workload == true) { DropIndexes(table); } } // Add indexes if needed AddIndexes(table, suggested_indices); // Update index utility if (visibility_mode_ == false) { UpdateIndexUtility(table, sample_frequency_entry_list); } // Display index information PrintIndexInformation(table); } void IndexTuner::IndexTuneHelper(storage::DataTable* table) { // Process all samples in table auto samples = table->GetIndexSamples(); auto sample_count = samples.size(); // Check if we have sufficient number of samples for build if (sample_count >= analyze_sample_count_threshold) { // Add required indices Analyze(table); // Clear samples table->ClearIndexSamples(); } // Build desired indices BuildIndices(table); } oid_t IndexTuner::GetIndexCount() const { oid_t index_count = 0; // Go over all tables for (auto table : tables) { oid_t table_index_count = table->GetValidIndexCount(); // Update index count index_count += table_index_count; } return index_count; } void IndexTuner::Tune() { LOG_TRACE("Begin tuning"); Timer<std::milli> pause_timer; pause_timer.Start(); // Continue till signal is not false while (index_tuning_stop == false) { // Go over one table at a time for (auto table : tables) { // Update indices periodically IndexTuneHelper(table); LOG_INFO("TUNER PAUSE [%dms]", duration_of_pause); std::this_thread::sleep_for(std::chrono::milliseconds(duration_of_pause)); } pause_timer.Stop(); auto duration = pause_timer.GetDuration(); // Sleep a bit if needed if (duration > duration_between_pauses) { std::this_thread::sleep_for(std::chrono::milliseconds(duration_of_pause)); pause_timer.Reset(); pause_timer.Start(); } } } void IndexTuner::Stop() { // Stop tuning index_tuning_stop = true; // Stop thread index_tuner_thread.join(); LOG_INFO("Stopped index tuner"); } void IndexTuner::AddTable(storage::DataTable* table) { { std::lock_guard<std::mutex> lock(index_tuner_mutex); tables.push_back(table); } } void IndexTuner::ClearTables() { { std::lock_guard<std::mutex> lock(index_tuner_mutex); tables.clear(); } } void IndexTuner::BootstrapTPCC(const std::string& path) { // Enable visibility mode SetVisibilityMode(); auto tables_samples = brain::BrainUtil::LoadSamplesFile(path); // Build sample map std::string database_name = "default_database"; auto catalog = catalog::Catalog::GetInstance(); // Go over set of tables, and add samples for (auto table_samples : tables_samples) { // Get table name auto table_name = table_samples.first; auto samples = table_samples.second; // Locate table in catalog auto& txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); auto table = catalog->GetTableWithName(database_name, table_name, txn); txn_manager.CommitTransaction(txn); PL_ASSERT(table != nullptr); for (auto& sample : samples) { table->RecordIndexSample(sample); } LOG_INFO("Added table to index tuner : %s", table_name.c_str()); // Attach table to tuner AddTable(table); } } // Load statistics for Index Tuner from a file void LoadStatsFromFile(const std::string& path) { LOG_INFO("LoadStatsFromFile Invoked"); // Get index tuner auto& index_tuner = brain::IndexTuner::GetInstance(); // Set duration between pauses auto duration = 30000; // in ms index_tuner.SetDurationOfPause(duration); // Bootstrap index_tuner.BootstrapTPCC(path); return; } } // namespace brain } // namespace peloton
seojungmin/peloton
src/brain/index_tuner.cpp
C++
apache-2.0
18,648
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function (scrollUtil) { 'use strict'; var lib = { validateAnimationName: function(animName) { if(animName && animName.match(/^move(to|from)(bottom|top|left|right|center|pop)$/)) { return true; } return false; }, /** * returns the initial, first and last focusable in the given panel * @param containerEl * @returns {{initial: *, first: *, last: *}} */ getFocusables: function(containerEl) { if(!containerEl) { return { initial: null, first: null, last: null } } var els = containerEl.querySelectorAll('input,button,a,textarea,select'), len = els.length, i, el; // The 'initial' element is the first non-button focusable element (see W-2512261) // whereas the 'first' element is the first (button or non-button) focusable element var initial, first, last; for (i = 0; i < len; i++) { el = els[i]; if (this.focusAllowed(el)) { if (!first) { first = el; } if (!/button/i.test(el.type)) { initial = el; break; } } } for (i = len - 1; i >= 0; i--) { el = els[i]; if (this.focusAllowed(el)) { last = el; break; } } return { // security restriction on iOS doesn't allow focus without user gesture, and focusing an input // inside a timeout causes weird behaviours (See W-2564192) // we can't completely ignore focus in iOS because the header is positioned on focus. Therefore // allowing iOS to focus the header buttons as before. initial: initial && !$A.get('$Browser.isIOS') ? initial : first, first: first, last: last }; }, /** * returns the key event handler function that do things based on the config * @param cmp * @param config {closeOnEsc, trapFocus, closeOnTabOut} * @param closeAction the caller defined close action * @returns {Function} */ getKeyEventListener: function(cmp, conf, closeAction) { var me = this, config = conf || {}; return function(e) { var el; if (!cmp.isValid()) { return; } var event = e || window.event, keyCode = event.keyCode; if (keyCode == 27 && config.closeOnEsc) { //escape to close $A.util.squash(e); if ($A.util.isFunction(closeAction)) { closeAction(cmp, "closeOnEsc"); } else { cmp.close(); } } else if (keyCode == 9) { //close on tab out var shiftPressed = event.shiftKey, current = document.activeElement, el = cmp.getElement(), focusables; if(el) { focusables = me.getFocusables(cmp.getElement()); } if (focusables && config.trapFocus) { if (current === focusables.last && !shiftPressed) { $A.util.squash(event, true); focusables.first.focus(); } else if (current === focusables.first && shiftPressed) { $A.util.squash(event, true); focusables.last.focus(); } } else if (focusables && config.closeOnTabOut) { if (current === focusables.last && !shiftPressed) { $A.util.squash(event, true); if ($A.util.isFunction(closeAction)) { closeAction(cmp, "closeOnTabOut"); } else { cmp.close(); } } } } }; }, /** * returns the mouse event handler function that do things base on the config * @param panelCmp * @param config {closeOnClickOut} * @param closeAction the caller defined close action * @returns {Function} */ getMouseEventListener: function(panelCmp, config, closeAction) { var self = this; return function(e) { if (!panelCmp.isValid()) { return; } var event = e || window.event, panelEl = panelCmp.getElement(), target = event.target || event.srcElement; if (config.closeOnClickOut) { var clickedInside = $A.util.contains(panelEl, target); if (panelEl && !clickedInside) { if ($A.util.isFunction(closeAction)) { closeAction(panelCmp, "closeOnClickOut"); } else { panelCmp.close(); } } } }; }, /** * show panel based on the config * @param cmp * @param config */ show: function(cmp, config) { if(!cmp.isValid()) { return; } var me = this, animEnd = this.getAnimationEndEventName(), animName = config.animationName, panel = cmp.getElement(), useTransition = config.useTransition, closeButton, animEl = config.animationEl || panel; //make sure animation name is valid if(useTransition) { useTransition = this.validateAnimationName(animName); } //need to notify panel manager to de-activate other panels; cmp.getEvent('notify').setParams({ action: 'beforeShow', typeOf: 'ui:panel', payload: { panelInstance: cmp.getGlobalId() } }).fire(); //endAnimationHandler: cleanup all classes and events var finishHandler = function (e) { if(!cmp.isValid()) { return; } if (animEl) { $A.util.removeClass(animEl, 'transitioning ' + animName); animEl.removeEventListener(animEnd, finishHandler); } $A.util.addClass(panel, 'active'); cmp.set('v.visible', true); if (config.autoFocus) { me.setFocus(cmp); } else { // If auto focus is false attempt to focus // on the close button. closeButton = cmp.getElement().querySelector('.closeBtn'); if(closeButton && closeButton.focus) { closeButton.focus(); } } config.onFinish && config.onFinish(); }; panel.setAttribute("aria-hidden", 'false'); if (useTransition) { animEl.addEventListener(animEnd, finishHandler, false); setTimeout(function() { $A.util.addClass(panel, 'open'); },10); $A.util.addClass(animEl, 'transitioning ' + animName); } else { $A.util.addClass(panel, 'open'); finishHandler(); } }, /** * hide panel * @param cmp * @param config */ hide: function(cmp, config) { var animEnd = this.getAnimationEndEventName(), animName = config.animationName, panel = cmp.getElement(), useTransition = config.useTransition, animEl = config.animationEl || panel; //make sure animation name is valid if(useTransition) { useTransition = this.validateAnimationName(animName); } cmp.set('v.visible', false); //endAnimationHandler: cleanup all classes and events var finishHandler = function (e) { // make sure the compoment is valid befdore // doining anything with it, because // this is asynchronous if(cmp.isValid()) { if (config.useTransition) { panel.removeEventListener(animEl, finishHandler); } config.onFinish && config.onFinish(); setTimeout(function() { $A.util.removeClass(panel, 'open'); $A.util.removeClass(panel, 'active'); $A.util.removeClass(animEl, 'transitioning ' + animName); }, 1000); //make sure all transitions are finished } else { config.onFinish && config.onFinish(); } }; panel.setAttribute("aria-hidden", 'true'); if (useTransition) { animEl.addEventListener(animEnd, finishHandler, false); $A.util.addClass(animEl, 'transitioning ' + animName); } else { finishHandler(); } }, /** * Update panel body * @param cmp * @param body * @param callback */ updatePanel: function(panel, facets, callback) { if ($A.util.isObject(facets)) { var facet, body = facets['body'] || panel.get('v.body'); for (var key in facets) { facet = facets[key]; if (facets.hasOwnProperty(key) && $A.util.isComponent(facet)) { panel.set('v.' + key, facet); } } if (!$A.util.isEmpty(body)) { //set body as value provider to route the events to the body //presume only one root body component var avp = $A.util.isComponent(body) ? body : body[0], header = facets['header'] || panel.get('v.header'), footer = facets['footer'] || panel.get('v.footer'); if ($A.util.isComponent(avp)) { avp.setAttributeValueProvider(panel); } if (!$A.util.isEmpty(header)) { if ($A.util.isComponent(header)) { header.setAttributeValueProvider(avp); } else { for (var i = 0, length = header.length; i < length; i++) { header[i].setAttributeValueProvider(avp); } } } if (!$A.util.isEmpty(footer)) { if ($A.util.isComponent(header)) { header.setAttributeValueProvider(avp); } else { for (var i = 0, length = footer.length; i < length; i++) { footer[0].setAttributeValueProvider(avp); } } } } } callback && callback(); }, handleNotify: function(cmp, event, helper) { var params = event.getParams(); if (!params) { return; } switch (params.action) { case 'destroyPanel': //contained component tries to close the panel but doesn't have access to this panelInstance //attach this id to the event and let it bubble up if (params.typeOf === 'ui:destroyPanel' && !params.payload) { params.payload = { panelInstance: cmp.getGlobalId() } } break; case 'closePanel': event.stopPropagation(); helper.close(cmp, params.payload ? params.payload.callback : null); break; case 'setFocus': if (cmp.get('v.autoFocus')) { this.setFocus(cmp); } break; } }, /** * Activate or de-activate the panel * @param cmp * @param active */ setActive: function(cmp, active) { if (!cmp.isValid() && !cmp.isRendered()) { return; } var panel = cmp.getElement(); if (active) { $A.util.addClass(panel, 'active'); panel.setAttribute('aria-hidden', 'false'); if (cmp.get('v.autoFocus')) { this.setFocus(cmp); } } else if ($A.util.hasClass(panel, 'active')) { cmp.returnFocus = document.activeElement; $A.util.removeClass(panel, 'active'); panel.setAttribute('aria-hidden', 'true'); } }, /** * returns the vendor prefix * @private */ getPrefix : function () { if (!this._prefix) { var styles = window.getComputedStyle(document.documentElement, ''), pre = (Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o']))[1], up = $A.util.isIE; this._prefix = up ? pre.toUpperCase() : pre; } return this._prefix; }, /** * returns the animationEnd event name * @private */ getAnimationEndEventName: function () { var eventName = this.ANIMATION_END_EVENT_NAMES[this.getPrefix()]; return eventName ? eventName : 'animationend'; }, /** * determines the element is visible or not * @private */ isVisible: function(el) { while (el && el.style) { if (window.getComputedStyle(el).display == 'none') { return false; } el = el.parentNode; } return true; }, /** * determines the element is focusable or not * @private */ focusAllowed: function(el) { return el && !el.disabled && !/hidden/i.test(el.type) && this.isVisible(el); }, /** * Set to first focusable element * @private */ setFocus: function(cmp) { if(cmp.isValid()) { var focusables, el; el = cmp.getElement(); if(cmp.returnFocus) { cmp.returnFocus.focus(); } else if(el && el.querySelectorAll) { var focusables = this.getFocusables(el); focusables.initial && focusables.initial.focus(); } } }, scopeScroll: function (dom) { scrollUtil.scope(dom); }, unscopeScroll: function (dom) { scrollUtil.unscope(dom); }, ANIMATION_END_EVENT_NAMES : { webkit : 'webkitAnimationEnd', o : 'oAnimationEnd', moz : 'animationend', ms : 'animationend' // IE 10 or above } }; return lib; }
TribeMedia/aura
aura-components/src/main/components/ui/panelLib/panelLibCore.js
JavaScript
apache-2.0
17,174
#ifndef CNN_GPU_FUNCTORS_H #define CNN_GPU_FUNCTORS_H #include <cstdint> #include <limits> #if HAVE_CUDA # define CNN_DEVICE_FUNC __device__ # define CNN_DEVICE_MIN -1.175494351e-38f #else # include <boost/math/special_functions/digamma.hpp> # define CNN_DEVICE_FUNC # define CNN_DEVICE_MIN std::numeric_limits<float>::min() #endif // these functions are used both in CPU and in GPU computation // this file may be compiled with NVCC or a standard C++ tool. // if you need a new elementwise (nullary, unary, binary...) // functor, this is the place for it // // note: also see xfunctors.h - functors implemented there can // use Eigen's internal support for vectorized operations which // can give faster performance on some hardware namespace cnn { struct FHuberForward { FHuberForward(float c) : c(c) {} CNN_DEVICE_FUNC inline float operator()(float x) const { const float a = fabs(x); return (a < c) ? x*x : c*(2*a - c); } const float c; }; template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } struct FL1Backward { FL1Backward(float d) : d(d) {} CNN_DEVICE_FUNC inline float operator()(float x) const { return sgn(x) * d; } const float d; }; struct FHuberBackward { FHuberBackward(float c, float dEdf) : c(c), d(dEdf) {} CNN_DEVICE_FUNC inline float operator()(float x) const { const float a = fabs(x); return (2 * d) * ((a < c) ? x : c * sgn(x)); } const float c; const float d; }; struct FProduct { CNN_DEVICE_FUNC inline float operator()(float a, float b) const { return a * b; } }; struct FQuotient { CNN_DEVICE_FUNC inline float operator()(float a, float b) const { return a / b; } }; struct FConstantPlus { FConstantPlus(float c) : c(c) {} CNN_DEVICE_FUNC inline float operator()(float x) const { return c + x; } float c; }; struct FConstantMinus { FConstantMinus(float c) : c(c) {} CNN_DEVICE_FUNC inline float operator()(float x) const { return c - x; } float c; }; struct FNegate { CNN_DEVICE_FUNC inline float operator()(float x) const { return -x; } }; struct FErf { CNN_DEVICE_FUNC inline float operator()(float x) const { return erff(x); } }; struct FTanh { CNN_DEVICE_FUNC inline float operator()(float x) const { #ifdef FAST_TANH float x2 = x * x; float a = x * (135135.0f + x2 * (17325.0f + x2 * (378.0f + x2))); float b = 135135.0f + x2 * (62370.0f + x2 * (3150.0f + x2 * 28.0f)); return a / b; #else return tanhf(x); #endif } }; struct FLog { CNN_DEVICE_FUNC inline float operator()(float x) const { return logf(x); } }; struct FMaxBackwardInv { CNN_DEVICE_FUNC inline float operator()(float u, float d) const { return (1.f - u) * d; } }; struct FSqrtBackward { CNN_DEVICE_FUNC inline float operator()(float t, float d) const { return d / (2.f * t); } }; struct FErfBackward { CNN_DEVICE_FUNC inline float operator()(float x, float d) const { return 1.1283791670955125738961589f * expf(-x * x) * d; } }; struct FTanhBackward { CNN_DEVICE_FUNC inline float operator()(float t, float d) const { return (1.f - t * t) * d; } }; struct FLogBackward { CNN_DEVICE_FUNC inline float operator()(float t, float d) const { return (1.f / t) * d; } }; struct FPairwiseRankLoss { FPairwiseRankLoss(float m) : margin(m) {} CNN_DEVICE_FUNC float operator()(float a, float b) const { float d = margin - a + b; return d > 0.f ? d : 0.f; } float margin; }; struct FRectifyBackward { CNN_DEVICE_FUNC inline float operator()(float t, float d) const { return (t) ? d : 0.f; } }; struct FRectifyNegateBackward { CNN_DEVICE_FUNC inline float operator()(float t, float d) const { return (t) ? -d : 0.f; } }; struct FSoftmaxNormalize { explicit FSoftmaxNormalize(float logz) : logz(logz) {} CNN_DEVICE_FUNC inline float operator()(float x) const { return expf(x - logz); } float logz; }; struct FSoftmaxBackward { explicit FSoftmaxBackward(float off_diag_sum) : off_diag_sum(off_diag_sum) {} CNN_DEVICE_FUNC inline float operator()(float t, float d) const { return (off_diag_sum + d) * t; } float off_diag_sum; }; struct FLogGammaBackward { CNN_DEVICE_FUNC inline float operator()(float x, float d) const { #ifndef HAVE_CUDA return boost::math::digamma(x) * d; #else assert(false); // Not supported on GPUs? return 0; #endif } }; struct FNegLogSoftmaxBackward { FNegLogSoftmaxBackward(float lz, float err) : logz(lz), d(err) {} CNN_DEVICE_FUNC inline float operator()(float t) const { return expf(t - logz) * d; } float logz; float d; }; struct FPtrNegLogSoftmaxBackward { FPtrNegLogSoftmaxBackward(const float* lz, const float* err) : logz(lz), d(err) {} CNN_DEVICE_FUNC inline float operator()(float t) const { return expf(t - *logz) * *d; } const float* logz; const float* d; }; struct FLogSoftmaxNormalize { explicit FLogSoftmaxNormalize(float logz) : logz(logz) {} CNN_DEVICE_FUNC inline float operator()(float x) const { return x - logz; } float logz; }; struct FWeightedError { float operator()(float t, float d) const { return expf(t) * d / expf(t); } }; struct FLogSoftmaxBackward { explicit FLogSoftmaxBackward(float off_diag_sum) : off_diag_sum(off_diag_sum) {} CNN_DEVICE_FUNC inline float operator()(float t, float d) const { return off_diag_sum * expf(t) + d; //return (off_diag_sum + d) * t; } float off_diag_sum; }; struct FRectify { CNN_DEVICE_FUNC inline float operator()(float x) const { return (x > 0.f) ? x : 0.f; } }; struct FSoftSign { CNN_DEVICE_FUNC inline float operator()(float x) const { return x / (1.f + (x < 0.f ? -x : x)); } }; struct FSoftSignBackward { CNN_DEVICE_FUNC inline float operator()(float t, float d) const { float a = 1.f - (t < 0.f ? -t : t); return a * a * d; } }; struct FLogisticSigmoid { CNN_DEVICE_FUNC inline float operator()(float x) const { return 1.f / (1.f + expf(-x)); } }; struct FLogisticSigmoidBackward { CNN_DEVICE_FUNC inline float operator()(float t, float d) const { return (1.f - t) * t * d; } }; struct FSqDist { CNN_DEVICE_FUNC inline float operator()(float a, float b) const { float d = a - b; return d * d; } }; struct FEuclideanBackward { FEuclideanBackward(int i, const float* s) : i(i), scalar(s) {} CNN_DEVICE_FUNC inline float operator()(float a, float b) const { return (i == 0 ? 2.f : -2.f) * (*scalar) * (a - b); } int i; const float* scalar; }; struct FL2SGDUpdate { FL2SGDUpdate(float l, float s) : lambda(l), scale(-s) {} CNN_DEVICE_FUNC inline float operator()(float x, float g) const { return scale * g - x * lambda; } float lambda; float scale; }; struct FBinaryLogLoss { CNN_DEVICE_FUNC inline float operator()(float x, float x_true) const { if (x_true == 1.f) { if (x == 0.f) x = CNN_DEVICE_MIN; return -1.f * x_true * log(x); } else if (x_true == 0.f) { if (x == 1.f) x = CNN_DEVICE_MIN; return (x_true - 1.f) * log1p(-x); } else { if (x == 0.f) x = CNN_DEVICE_MIN; if (x == 1.f) x = CNN_DEVICE_MIN; return -1.f * (x_true * log(x) + (1.f - x_true) * log1p(-x)); } } }; struct FBinaryLogLossBackward { explicit FBinaryLogLossBackward(float d) : d(d) {} CNN_DEVICE_FUNC inline float operator()(float x, float x_true) const { if (x == x_true) return 0; if (x == 0.f) x = CNN_DEVICE_MIN; if (x == 1.f) x = 0.9999999f; if (x_true == 1.f) { return d * -x_true / x; } else if (x_true == 0.f) { return d * (1.f - x_true) / (1.f - x); } return d * ((1.f - x_true) / (1.f - x) + (-x_true / x)); } float d; }; } // namespace cnn #endif
dhgarrette/cnn
cnn/functors.h
C
apache-2.0
7,794
using System; using System.Threading.Tasks; using Elasticsearch.Net; using System.Threading; namespace Nest { public partial interface IElasticClient { /// <summary> /// Returns information and statistics on terms in the fields of a particular document as stored in the index. /// <para> </para><a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-termvectors.html">http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-termvectors.html</a> /// </summary> /// <typeparam name="T">The type of the document</typeparam> /// <param name="selector">A descriptor for the terms vector operation</param> ITermVectorsResponse TermVectors<T>(Func<TermVectorsDescriptor<T>, ITermVectorsRequest<T>> selector) where T : class; /// <inheritdoc/> ITermVectorsResponse TermVectors<T>(ITermVectorsRequest<T> request) where T : class; /// <inheritdoc/> Task<ITermVectorsResponse> TermVectorsAsync<T>( Func<TermVectorsDescriptor<T>, ITermVectorsRequest<T>> selector, CancellationToken cancellationToken = default(CancellationToken) ) where T : class; /// <inheritdoc/> Task<ITermVectorsResponse> TermVectorsAsync<T>(ITermVectorsRequest<T> request, CancellationToken cancellationToken = default(CancellationToken)) where T : class; } public partial class ElasticClient { ///<inheritdoc/> public ITermVectorsResponse TermVectors<T>(Func<TermVectorsDescriptor<T>, ITermVectorsRequest<T>> selector) where T : class => this.TermVectors(selector?.Invoke(new TermVectorsDescriptor<T>(typeof(T), typeof(T)))); ///<inheritdoc/> public ITermVectorsResponse TermVectors<T>(ITermVectorsRequest<T> request) where T : class { return this.Dispatcher.Dispatch<ITermVectorsRequest<T>, TermVectorsRequestParameters, TermVectorsResponse>( request, this.LowLevelDispatch.TermvectorsDispatch<TermVectorsResponse> ); } ///<inheritdoc/> public Task<ITermVectorsResponse> TermVectorsAsync<T>( Func<TermVectorsDescriptor<T>, ITermVectorsRequest<T>> selector, CancellationToken cancellationToken = default(CancellationToken) ) where T : class => this.TermVectorsAsync(selector?.Invoke(new TermVectorsDescriptor<T>(typeof(T), typeof(T))), cancellationToken); ///<inheritdoc/> public Task<ITermVectorsResponse> TermVectorsAsync<T>(ITermVectorsRequest<T> request, CancellationToken cancellationToken = default(CancellationToken)) where T : class => this.Dispatcher.DispatchAsync<ITermVectorsRequest<T>, TermVectorsRequestParameters, TermVectorsResponse, ITermVectorsResponse>( request, cancellationToken, this.LowLevelDispatch.TermvectorsDispatchAsync<TermVectorsResponse> ); } }
CSGOpenSource/elasticsearch-net
src/Nest/Document/Single/TermVectors/ElasticClient-TermVectors.cs
C#
apache-2.0
2,710
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.google.drive; import java.util.Arrays; import java.util.List; import com.google.api.services.drive.DriveScopes; import org.apache.camel.component.google.drive.internal.GoogleDriveApiName; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriParams; import org.apache.camel.spi.UriPath; /** * Component configuration for GoogleDrive component. */ @UriParams public class GoogleDriveConfiguration { private static final List<String> DEFAULT_SCOPES = Arrays.asList(DriveScopes.DRIVE_FILE, DriveScopes.DRIVE_APPS_READONLY, DriveScopes.DRIVE_METADATA_READONLY, DriveScopes.DRIVE); @UriPath(enums = "drive-about,drive-apps,drive-changes,drive-channels,drive-children,drive-comments,drive-files,drive-parents" + ",drive-permissions,drive-properties,drive-realtime,drive-replies,drive-revisions") @Metadata(required = true) private GoogleDriveApiName apiName; @UriPath(enums = "copy,delete,get,getIdForEmail,insert,list,patch,stop,touch,trash,untrash,update,watch") @Metadata(required = true) private String methodName; @UriParam private List<String> scopes = DEFAULT_SCOPES; @UriParam private String clientId; @UriParam(label = "security", secret = true) private String clientSecret; @UriParam(label = "security", secret = true) private String accessToken; @UriParam(label = "security", secret = true) private String refreshToken; @UriParam private String applicationName; public GoogleDriveApiName getApiName() { return apiName; } /** * What kind of operation to perform */ public void setApiName(GoogleDriveApiName apiName) { this.apiName = apiName; } public String getMethodName() { return methodName; } /** * What sub operation to use for the selected operation */ public void setMethodName(String methodName) { this.methodName = methodName; } public String getClientId() { return clientId; } /** * Client ID of the drive application */ public void setClientId(String clientId) { this.clientId = clientId; } public String getClientSecret() { return clientSecret; } /** * Client secret of the drive application */ public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } public String getAccessToken() { return accessToken; } /** * OAuth 2 access token. This typically expires after an hour so refreshToken is recommended for long term usage. */ public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public String getRefreshToken() { return refreshToken; } /** * OAuth 2 refresh token. Using this, the Google Calendar component can obtain a new accessToken whenever the current one expires - a necessity if the application is long-lived. */ public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } public String getApplicationName() { return applicationName; } /** * Google drive application name. Example would be "camel-google-drive/1.0" */ public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public List<String> getScopes() { return scopes; } /** * Specifies the level of permissions you want a drive application to have to a user account. See https://developers.google.com/drive/web/scopes for more info. */ public void setScopes(List<String> scopes) { this.scopes = scopes; } }
DariusX/camel
components/camel-google-drive/src/main/java/org/apache/camel/component/google/drive/GoogleDriveConfiguration.java
Java
apache-2.0
4,612
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "syzygy/agent/asan/heap_checker.h" #include "base/rand_util.h" #include "gtest/gtest.h" #include "syzygy/agent/asan/logger.h" #include "syzygy/agent/asan/page_protection_helpers.h" #include "syzygy/agent/asan/runtime.h" #include "syzygy/agent/asan/unittest_util.h" namespace agent { namespace asan { namespace { typedef public testing::TestWithAsanRuntime HeapCheckerTest; using testing::FakeAsanBlock; } // namespace TEST_F(HeapCheckerTest, HeapCheckerHandlesPageProtections) { // Make a large allocation bigger than a couple pages. This will ensure // that its big enough to have page protections. The HeapChecker will have // to unset these in order to do its work successfully. Otherwise it will // cause an access violation. FakeAsanBlock fake_large_block( runtime_->shadow(), kShadowRatioLog, runtime_->stack_cache()); fake_large_block.InitializeBlock(2 * static_cast<uint32_t>(GetPageSize())); base::RandBytes(fake_large_block.block_info.body, 2 * GetPageSize()); fake_large_block.MarkBlockAsQuarantined(); BlockProtectAll(fake_large_block.block_info, runtime_->shadow()); HeapChecker heap_checker(runtime_->shadow()); HeapChecker::CorruptRangesVector corrupt_ranges; EXPECT_FALSE(heap_checker.IsHeapCorrupt(&corrupt_ranges)); BlockProtectNone(fake_large_block.block_info, runtime_->shadow()); } TEST_F(HeapCheckerTest, IsHeapCorruptInvalidChecksum) { const size_t kAllocSize = 100; FakeAsanBlock fake_block( runtime_->shadow(), kShadowRatioLog, runtime_->stack_cache()); fake_block.InitializeBlock(kAllocSize); base::RandBytes(fake_block.block_info.body, kAllocSize); HeapChecker heap_checker(runtime_->shadow()); HeapChecker::CorruptRangesVector corrupt_ranges; EXPECT_FALSE(heap_checker.IsHeapCorrupt(&corrupt_ranges)); // Free the block and corrupt its data. ASSERT_TRUE(fake_block.MarkBlockAsQuarantined()); size_t header_checksum = fake_block.block_info.header->checksum; // Corrupt the data in such a way that we can guarantee no hash collision. const size_t kMaxIterations = 10; size_t iteration = 0; uint8_t original_value = fake_block.block_info.RawBody(0); do { fake_block.block_info.RawBody(0)++; BlockSetChecksum(fake_block.block_info); } while (fake_block.block_info.header->checksum == header_checksum && iteration++ < kMaxIterations); // Restore the checksum to make sure that the corruption gets detected. fake_block.block_info.header->checksum = header_checksum; EXPECT_TRUE(heap_checker.IsHeapCorrupt(&corrupt_ranges)); ASSERT_EQ(1, corrupt_ranges.size()); AsanCorruptBlockRange range_info = *corrupt_ranges.begin(); EXPECT_EQ(1, range_info.block_count); ShadowWalker shadow_walker( runtime_->shadow(), reinterpret_cast<const uint8_t*>(range_info.address), reinterpret_cast<const uint8_t*>(range_info.address) + range_info.length); BlockInfo block_info = {}; EXPECT_TRUE(shadow_walker.Next(&block_info)); EXPECT_EQ(fake_block.block_info.header, block_info.header); EXPECT_FALSE(shadow_walker.Next(&block_info)); fake_block.block_info.header->checksum = header_checksum; fake_block.block_info.RawBody(0) = original_value; EXPECT_FALSE(heap_checker.IsHeapCorrupt(&corrupt_ranges)); } TEST_F(HeapCheckerTest, IsHeapCorruptInvalidMagicNumber) { const size_t kAllocSize = 100; FakeAsanBlock fake_block( runtime_->shadow(), kShadowRatioLog, runtime_->stack_cache()); fake_block.InitializeBlock(kAllocSize); base::RandBytes(fake_block.block_info.body, kAllocSize); HeapChecker heap_checker(runtime_->shadow()); HeapChecker::CorruptRangesVector corrupt_ranges; EXPECT_FALSE(heap_checker.IsHeapCorrupt(&corrupt_ranges)); // Corrupt the header of the block and ensure that the heap corruption gets // detected. fake_block.block_info.header->magic = ~fake_block.block_info.header->magic; EXPECT_TRUE(heap_checker.IsHeapCorrupt(&corrupt_ranges)); ASSERT_EQ(1, corrupt_ranges.size()); AsanCorruptBlockRange range_info = *corrupt_ranges.begin(); EXPECT_EQ(1, range_info.block_count); ShadowWalker shadow_walker( runtime_->shadow(), reinterpret_cast<const uint8_t*>(range_info.address), reinterpret_cast<const uint8_t*>(range_info.address) + range_info.length); BlockInfo block_info = {}; EXPECT_TRUE(shadow_walker.Next(&block_info)); EXPECT_EQ(fake_block.block_info.header, block_info.header); EXPECT_FALSE(shadow_walker.Next(&block_info)); fake_block.block_info.header->magic = ~fake_block.block_info.header->magic; EXPECT_FALSE(heap_checker.IsHeapCorrupt(&corrupt_ranges)); } TEST_F(HeapCheckerTest, IsHeapCorrupt) { const size_t kAllocSize = 100; BlockLayout block_layout = {}; EXPECT_TRUE(BlockPlanLayout(kShadowRatio, kShadowRatio, kAllocSize, 0, 0, &block_layout)); const size_t kNumberOfBlocks = 4; size_t total_alloc_size = block_layout.block_size * kNumberOfBlocks; uint8_t* global_alloc = reinterpret_cast<uint8_t*>(::malloc(total_alloc_size)); uint8_t* blocks[kNumberOfBlocks]; BlockHeader* block_headers[kNumberOfBlocks]; for (size_t i = 0; i < kNumberOfBlocks; ++i) { blocks[i] = global_alloc + i * block_layout.block_size; BlockInfo block_info = {}; BlockInitialize(block_layout, blocks[i], &block_info); runtime_->shadow()->PoisonAllocatedBlock(block_info); BlockSetChecksum(block_info); block_headers[i] = block_info.header; EXPECT_EQ(block_headers[i], reinterpret_cast<BlockHeader*>(blocks[i])); } HeapChecker heap_checker(runtime_->shadow()); HeapChecker::CorruptRangesVector corrupt_ranges; EXPECT_FALSE(heap_checker.IsHeapCorrupt(&corrupt_ranges)); // Corrupt the header of the first two blocks and of the last one. block_headers[0]->magic++; block_headers[1]->magic++; block_headers[kNumberOfBlocks - 1]->magic++; EXPECT_TRUE(heap_checker.IsHeapCorrupt(&corrupt_ranges)); // We expect the heap to contain 2 ranges of corrupt blocks, the first one // containing the 2 first blocks and the second one containing the last block. EXPECT_EQ(2, corrupt_ranges.size()); BlockInfo block_info = {}; ShadowWalker shadow_walker_1( runtime_->shadow(), reinterpret_cast<const uint8_t*>(corrupt_ranges[0].address), reinterpret_cast<const uint8_t*>(corrupt_ranges[0].address) + corrupt_ranges[0].length); EXPECT_TRUE(shadow_walker_1.Next(&block_info)); EXPECT_EQ(reinterpret_cast<const BlockHeader*>(block_info.header), block_headers[0]); EXPECT_TRUE(shadow_walker_1.Next(&block_info)); EXPECT_EQ(reinterpret_cast<const BlockHeader*>(block_info.header), block_headers[1]); EXPECT_FALSE(shadow_walker_1.Next(&block_info)); ShadowWalker shadow_walker_2( runtime_->shadow(), reinterpret_cast<const uint8_t*>(corrupt_ranges[1].address), reinterpret_cast<const uint8_t*>(corrupt_ranges[1].address) + corrupt_ranges[1].length); EXPECT_TRUE(shadow_walker_2.Next(&block_info)); EXPECT_EQ(reinterpret_cast<const BlockHeader*>(block_info.header), block_headers[kNumberOfBlocks - 1]); EXPECT_FALSE(shadow_walker_2.Next(&block_info)); // Restore the checksum of the blocks. block_headers[0]->magic--; block_headers[1]->magic--; block_headers[kNumberOfBlocks - 1]->magic--; runtime_->shadow()->Unpoison(global_alloc, total_alloc_size); ::free(global_alloc); } } // namespace asan } // namespace agent
google/syzygy
syzygy/agent/asan/heap_checker_unittest.cc
C++
apache-2.0
8,088
package jadx.gui; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class TestI18n { private static Path guiJavaPath; private static Path i18nPath; private List<String> reference; private String referenceName; @BeforeAll public static void init() { i18nPath = Paths.get("src/main/resources/i18n"); assertTrue(Files.exists(i18nPath)); guiJavaPath = Paths.get("src/main/java"); assertTrue(Files.exists(guiJavaPath)); } @Test public void filesExactlyMatch() throws IOException { Files.list(i18nPath).forEach(p -> { List<String> lines; try { lines = Files.readAllLines(p); if (reference == null) { reference = lines; referenceName = p.getFileName().toString(); } else { compareToReference(p); } } catch (IOException e) { Assertions.fail("Error " + e.getMessage()); } }); } private void compareToReference(Path path) throws IOException { List<String> lines = Files.readAllLines(path); for (int i = 0; i < reference.size(); i++) { String line = trimComment(reference.get(i)); int p0 = line.indexOf('='); if (p0 != -1) { String prefix = line.substring(0, p0 + 1); if (i >= lines.size() || !trimComment(lines.get(i)).startsWith(prefix)) { failLine(path, i + 1); } } } if (lines.size() != reference.size()) { failLine(path, reference.size()); } } private static String trimComment(String string) { return string.startsWith("#") ? string.substring(1) : string; } private void failLine(Path path, int line) { fail("I18n files " + path.getFileName() + " and " + referenceName + " differ in line " + line); } @Test public void keyIsUsed() throws IOException { Properties properties = new Properties(); try (Reader reader = Files.newBufferedReader(i18nPath.resolve("Messages_en_US.properties"))) { properties.load(reader); } Set<String> keys = new HashSet<>(); for (Object key : properties.keySet()) { keys.add("\"" + key + '"'); } Files.walk(guiJavaPath).filter(p -> Files.isRegularFile(p)).forEach(p -> { try { List<String> lines = Files.readAllLines(p); for (String line : lines) { for (Iterator<String> it = keys.iterator(); it.hasNext();) { if (line.contains(it.next())) { it.remove(); } } } } catch (IOException e) { throw new RuntimeException(e); } }); assertThat("keys not used", keys, empty()); } }
skylot/jadx
jadx-gui/src/test/java/jadx/gui/TestI18n.java
Java
apache-2.0
2,953
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2017 the original author or authors. */ package org.assertj.core.internal.shortarrays; import static org.assertj.core.error.ShouldBeEmpty.shouldBeEmpty; import static org.assertj.core.test.ShortArrays.emptyArray; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.mockito.Mockito.verify; import org.assertj.core.api.AssertionInfo; import org.assertj.core.internal.ShortArrays; import org.assertj.core.internal.ShortArraysBaseTest; import org.junit.Test; /** * Tests for <code>{@link ShortArrays#assertEmpty(AssertionInfo, short[])}</code>. * * @author Alex Ruiz */ public class ShortArrays_assertEmpty_Test extends ShortArraysBaseTest { @Test public void should_fail_if_actual_is_null() { thrown.expectAssertionError(actualIsNull()); arrays.assertEmpty(someInfo(), null); } @Test public void should_fail_if_actual_is_not_empty() { AssertionInfo info = someInfo(); short[] actual = { 6, 8 }; try { arrays.assertEmpty(info, actual); } catch (AssertionError e) { verify(failures).failure(info, shouldBeEmpty(actual)); return; } failBecauseExpectedAssertionErrorWasNotThrown(); } @Test public void should_pass_if_actual_is_empty() { arrays.assertEmpty(someInfo(), emptyArray()); } }
ChrisA89/assertj-core
src/test/java/org/assertj/core/internal/shortarrays/ShortArrays_assertEmpty_Test.java
Java
apache-2.0
2,017
--- layout: "docs_api" version: "1.0.0-beta.7" versionHref: "/docs" path: "api/service/$ionicNavBarDelegate/" title: "$ionicNavBarDelegate" header_sub_title: "Service in module ionic" doc: "$ionicNavBarDelegate" docType: "service" --- <div class="improve-docs"> <a href='http://github.com/driftyco/ionic/tree/master/js/angular/service/navBarDelegate.js#L2'> View Source </a> &nbsp; <a href='http://github.com/driftyco/ionic/edit/master/js/angular/service/navBarDelegate.js#L2'> Improve this doc </a> </div> <h1 class="api-title"> $ionicNavBarDelegate </h1> Delegate for controlling the <a href="/docs/api/directive/ionNavBar/"><code>ionNavBar</code></a> directive. ## Usage ```html <body ng-controller="MyCtrl"> <ion-nav-bar> <button ng-click="setNavTitle('banana')"> Set title to banana! </button> </ion-nav-bar> </body> ``` ```js function MyCtrl($scope, $ionicNavBarDelegate) { $scope.setNavTitle = function(title) { $ionicNavBarDelegate.setTitle(title); } } ``` ## Methods <div id="back"></div> <h2> <code>back([event])</code> </h2> Goes back in the view history. <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> event <div><em>(optional)</em></div> </td> <td> <code>DOMEvent</code> </td> <td> <p>The event object (eg from a tap event)</p> </td> </tr> </tbody> </table> <div id="align"></div> <h2> <code>align([direction])</code> </h2> Aligns the title with the buttons in a given direction. <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> direction <div><em>(optional)</em></div> </td> <td> <code>string</code> </td> <td> <p>The direction to the align the title text towards. Available: &#39;left&#39;, &#39;right&#39;, &#39;center&#39;. Default: &#39;center&#39;.</p> </td> </tr> </tbody> </table> <div id="showBackButton"></div> <h2> <code>showBackButton([show])</code> </h2> Set/get whether the <a href="/docs/api/directive/ionNavBackButton/"><code>ionNavBackButton</code></a> is shown (if it exists). <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> show <div><em>(optional)</em></div> </td> <td> <code>boolean</code> </td> <td> <p>Whether to show the back button.</p> </td> </tr> </tbody> </table> * Returns: <code>boolean</code> Whether the back button is shown. <div id="showBar"></div> <h2> <code>showBar(show)</code> </h2> Set/get whether the <a href="/docs/api/directive/ionNavBar/"><code>ionNavBar</code></a> is shown. <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> show </td> <td> <code>boolean</code> </td> <td> <p>Whether to show the bar.</p> </td> </tr> </tbody> </table> * Returns: <code>boolean</code> Whether the bar is shown. <div id="setTitle"></div> <h2> <code>setTitle(title)</code> </h2> Set the title for the <a href="/docs/api/directive/ionNavBar/"><code>ionNavBar</code></a>. <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> title </td> <td> <code>string</code> </td> <td> <p>The new title to show.</p> </td> </tr> </tbody> </table> <div id="changeTitle"></div> <h2> <code>changeTitle(title, direction)</code> </h2> Change the title, transitioning the new title in and the old one out in a given direction. <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> title </td> <td> <code>string</code> </td> <td> <p>The new title to show.</p> </td> </tr> <tr> <td> direction </td> <td> <code>string</code> </td> <td> <p>The direction to transition the new title in. Available: &#39;forward&#39;, &#39;back&#39;.</p> </td> </tr> </tbody> </table> <div id="getTitle"></div> <h2> <code>getTitle()</code> </h2> * Returns: <code>string</code> The current title of the navbar. <div id="getPreviousTitle"></div> <h2> <code>getPreviousTitle()</code> </h2> * Returns: <code>string</code> The previous title of the navbar. <div id="$getByHandle"></div> <h2> <code>$getByHandle(handle)</code> </h2> <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> handle </td> <td> <code>string</code> </td> <td> </td> </tr> </tbody> </table> * Returns: `delegateInstance` A delegate instance that controls only the navBars with delegate-handle matching the given handle. Example: `$ionicNavBarDelegate.$getByHandle('myHandle').setTitle('newTitle')`
auth0/ionic-site
docs/1.0.0-beta.7/api/service/$ionicNavBarDelegate/index.md
Markdown
apache-2.0
5,984
package com.google.api.ads.dfp.jaxws.v201508; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Company.Type. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="Company.Type"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="HOUSE_ADVERTISER"/> * &lt;enumeration value="HOUSE_AGENCY"/> * &lt;enumeration value="ADVERTISER"/> * &lt;enumeration value="AGENCY"/> * &lt;enumeration value="AD_NETWORK"/> * &lt;enumeration value="AFFILIATE_DISTRIBUTION_PARTNER"/> * &lt;enumeration value="CONTENT_PARTNER"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "Company.Type") @XmlEnum public enum CompanyType { /** * * The publisher's own advertiser. When no outside advertiser buys its * inventory, the publisher may run its own advertising campaigns. * * */ HOUSE_ADVERTISER, /** * * The publisher's own agency. * * */ HOUSE_AGENCY, /** * * A business entity that buys publisher inventory to run advertising * campaigns. An advertiser is optionally associated with one or more * agencies. * * */ ADVERTISER, /** * * A business entity that offers services, such as advertising creation, * placement, and management, to advertisers. * * */ AGENCY, /** * * A company representing multiple advertisers and agencies. * * */ AD_NETWORK, /** * * A company representing a content owner's affiliate/distribution partner. * * */ AFFILIATE_DISTRIBUTION_PARTNER, /** * * A company representing a distributor's content partner. * * */ CONTENT_PARTNER, /** * * The value returned if the actual value is not exposed by the requested API * version. * * */ UNKNOWN; public String value() { return name(); } public static CompanyType fromValue(String v) { return valueOf(v); } }
raja15792/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201508/CompanyType.java
Java
apache-2.0
2,633
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.broker.loadbalance.impl; import java.util.Set; import com.google.common.collect.Sets; import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; import org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet; import org.testng.Assert; import org.testng.annotations.Test; @Test(groups = "broker") public class LoadManagerSharedTest { @Test public void testRemoveMostServicingBrokersForNamespace() { String namespace = "tenant1/ns1"; String assignedBundle = namespace + "/0x00000000_0x40000000"; Set<String> candidates = Sets.newHashSet(); ConcurrentOpenHashMap<String, ConcurrentOpenHashMap<String, ConcurrentOpenHashSet<String>>> map = new ConcurrentOpenHashMap<>(); LoadManagerShared.removeMostServicingBrokersForNamespace(assignedBundle, candidates, map); Assert.assertEquals(candidates.size(), 0); candidates = Sets.newHashSet("broker1"); LoadManagerShared.removeMostServicingBrokersForNamespace(assignedBundle, candidates, map); Assert.assertEquals(candidates.size(), 1); Assert.assertTrue(candidates.contains("broker1")); candidates = Sets.newHashSet("broker1"); fillBrokerToNamespaceToBundleMap(map, "broker1", namespace, "0x40000000_0x80000000"); LoadManagerShared.removeMostServicingBrokersForNamespace(assignedBundle, candidates, map); Assert.assertEquals(candidates.size(), 1); Assert.assertTrue(candidates.contains("broker1")); candidates = Sets.newHashSet("broker1", "broker2"); LoadManagerShared.removeMostServicingBrokersForNamespace(assignedBundle, candidates, map); Assert.assertEquals(candidates.size(), 1); Assert.assertTrue(candidates.contains("broker2")); candidates = Sets.newHashSet("broker1", "broker2"); fillBrokerToNamespaceToBundleMap(map, "broker2", namespace, "0x80000000_0xc0000000"); LoadManagerShared.removeMostServicingBrokersForNamespace(assignedBundle, candidates, map); Assert.assertEquals(candidates.size(), 2); Assert.assertTrue(candidates.contains("broker1")); Assert.assertTrue(candidates.contains("broker2")); candidates = Sets.newHashSet("broker1", "broker2"); fillBrokerToNamespaceToBundleMap(map, "broker2", namespace, "0xc0000000_0xd0000000"); LoadManagerShared.removeMostServicingBrokersForNamespace(assignedBundle, candidates, map); Assert.assertEquals(candidates.size(), 1); Assert.assertTrue(candidates.contains("broker1")); candidates = Sets.newHashSet("broker1", "broker2", "broker3"); fillBrokerToNamespaceToBundleMap(map, "broker3", namespace, "0xd0000000_0xffffffff"); LoadManagerShared.removeMostServicingBrokersForNamespace(assignedBundle, candidates, map); Assert.assertEquals(candidates.size(), 2); Assert.assertTrue(candidates.contains("broker1")); Assert.assertTrue(candidates.contains("broker3")); } private static void fillBrokerToNamespaceToBundleMap( ConcurrentOpenHashMap<String, ConcurrentOpenHashMap<String, ConcurrentOpenHashSet<String>>> map, String broker, String namespace, String bundle) { map.computeIfAbsent(broker, k -> new ConcurrentOpenHashMap<>()) .computeIfAbsent(namespace, k -> new ConcurrentOpenHashSet<>()).add(bundle); } }
massakam/pulsar
pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/impl/LoadManagerSharedTest.java
Java
apache-2.0
4,232
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.andes.internal; import com.hazelcast.core.HazelcastInstance; import org.apache.axis2.clustering.ClusteringAgent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; import org.wso2.andes.configuration.AndesConfigurationManager; import org.wso2.andes.configuration.enums.AndesConfiguration; import org.wso2.andes.kernel.AndesContext; import org.wso2.andes.kernel.AndesException; import org.wso2.andes.kernel.AndesKernelBoot; import org.wso2.andes.server.BrokerOptions; import org.wso2.andes.server.Main; import org.wso2.andes.server.cluster.coordination.hazelcast.HazelcastAgent; import org.wso2.andes.server.registry.ApplicationRegistry; import org.wso2.andes.wso2.service.QpidNotificationService; import org.wso2.carbon.andes.authentication.service.AuthenticationService; import org.wso2.carbon.andes.event.core.EventBundleNotificationService; import org.wso2.carbon.andes.event.core.qpid.QpidServerDetails; import org.wso2.carbon.andes.listeners.BrokerLifecycleListener; import org.wso2.carbon.andes.listeners.MessageBrokerTenantManagementListener; import org.wso2.carbon.andes.service.QpidService; import org.wso2.carbon.andes.service.QpidServiceImpl; import org.wso2.carbon.andes.service.exception.ConfigurationException; import org.wso2.carbon.andes.utils.MessageBrokerDBUtil; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.base.api.ServerConfigurationService; import org.wso2.carbon.core.ServerRestartHandler; import org.wso2.carbon.core.ServerShutdownHandler; import org.wso2.carbon.server.admin.common.IServerAdmin; import org.wso2.carbon.stratos.common.listeners.TenantMgtListener; import org.wso2.carbon.utils.ConfigurationContextService; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.Socket; import java.util.Set; import java.util.Stack; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; /** * @scr.component name="org.wso2.carbon.andes.internal.QpidServiceComponent" * immediate="true" * @scr.reference name="org.wso2.carbon.andes.authentication.service.AuthenticationService" * interface="org.wso2.carbon.andes.authentication.service.AuthenticationService" * cardinality="1..1" * policy="dynamic" * bind="setAccessKey" * unbind="unsetAccessKey" * @scr.reference name="org.wso2.andes.wso2.service.QpidNotificationService" * interface="org.wso2.andes.wso2.service.QpidNotificationService" * cardinality="1..1" * policy="dynamic" * bind="setQpidNotificationService" * unbind="unsetQpidNotificationService" * @scr.reference name="server.configuration" * interface="org.wso2.carbon.base.api.ServerConfigurationService" * cardinality="1..1" * policy="dynamic" * bind="setServerConfiguration" * unbind="unsetServerConfiguration" * @scr.reference name="event.broker" * interface="org.wso2.carbon.andes.event.core.EventBundleNotificationService" * cardinality="1..1" * policy="dynamic" * bind="setEventBundleNotificationService" * unbind="unsetEventBundleNotificationService" * @scr.reference name="hazelcast.instance.service" * interface="com.hazelcast.core.HazelcastInstance" * cardinality="0..1" * policy="dynamic" * bind="setHazelcastInstance" * unbind="unsetHazelcastInstance" * @scr.reference name="config.context.service" * interface="org.wso2.carbon.utils.ConfigurationContextService" * cardinality="1..1" policy="dynamic" * bind="setConfigurationContextService" * unbind="unsetConfigurationContextService" * @scr.reference name="org.wso2.carbon.server.admin.common.IServerAdmin" * interface="org.wso2.carbon.server.admin.common.IServerAdmin" * cardinality="1..1" policy="dynamic" * bind="setIServerAdmin" * unbind="unsetIServerAdmin" */ public class QpidServiceComponent { private static final Log log = LogFactory.getLog(QpidServiceComponent.class); private static final String CARBON_CONFIG_PORT_OFFSET = "Ports.Offset"; private static final int CARBON_DEFAULT_PORT_OFFSET = 0; protected static final String MODE_STANDALONE = "standalone"; protected static final String MODE_DEFAULT = "default"; private static BundleContext bundleContext; private static Stack<ServiceRegistration> registrations = new Stack<ServiceRegistration>(); /** * This is used in the situations where the Hazelcast instance is not registered but the activate method of the * QpidServiceComponent is called when clustering is enabled. * This property is used to block the process of starting the broker until the hazelcast instance getting * registered. */ private boolean brokerShouldBeStarted = false; /** * This flag true if HazelcastInstance has been registered. */ private boolean registeredHazelcast = false; /** * This holds the configuration values */ private QpidServiceImpl qpidServiceImpl; protected void activate(ComponentContext context) throws AndesException { try { //Initialize AndesConfigurationManager AndesConfigurationManager.initialize(readPortOffset()); //Load qpid specific configurations qpidServiceImpl = new QpidServiceImpl(QpidServiceDataHolder.getInstance().getAccessKey()); qpidServiceImpl.loadConfigurations(); // Register tenant management listener for Message Broker bundleContext = context.getBundleContext(); MessageBrokerTenantManagementListener tenantManagementListener = new MessageBrokerTenantManagementListener(); registrations.push(bundleContext.registerService(TenantMgtListener.class.getName(), tenantManagementListener, null)); // set message store and andes context store related configurations AndesContext.getInstance().constructStoreConfiguration(); // Read deployment mode String mode = AndesConfigurationManager.readValue(AndesConfiguration.DEPLOYMENT_MODE); // Start broker in standalone mode if (mode.equalsIgnoreCase(MODE_STANDALONE)) { // set clustering enabled to false because even though clustering enabled in axis2.xml, we are not // going to consider it in standalone mode AndesContext.getInstance().setClusteringEnabled(false); this.startAndesBroker(); } else if (mode.equalsIgnoreCase(MODE_DEFAULT)) { // Start broker in HA mode if (!AndesContext.getInstance().isClusteringEnabled()) { // If clustering is disabled, broker starts without waiting for hazelcastInstance this.startAndesBroker(); } else { // Start broker in distributed mode if (registeredHazelcast) { // When clustering is enabled, starts broker only if the hazelcastInstance has also been // registered. this.startAndesBroker(); } else { // If hazelcastInstance has not been registered yet, turn the brokerShouldBeStarted flag to // true and wait for hazelcastInstance to be registered. this.brokerShouldBeStarted = true; } } } else { throw new ConfigurationException("Invalid value " + mode + " for deployment/mode in broker.xml"); } MBShutdownHandler mbShutdownHandler = new MBShutdownHandler(); registrations.push(bundleContext.registerService( ServerShutdownHandler.class.getName(), mbShutdownHandler, null)); registrations.push(bundleContext.registerService( ServerRestartHandler.class.getName(), mbShutdownHandler, null)); } catch (ConfigurationException e) { log.error("Invalid configuration found in a configuration file", e); this.shutdown(); } } protected void deactivate(ComponentContext ctx) { // By this time, through the AndesServerShutDownListener, All other services/ workers including this service, // have been closed. // Unregister services while (!registrations.empty()) { registrations.pop().unregister(); } bundleContext = null; } protected void setAccessKey(AuthenticationService authenticationService) { QpidServiceDataHolder.getInstance().setAccessKey(authenticationService.getAccessKey()); } protected void unsetAccessKey(AuthenticationService authenticationService) { QpidServiceDataHolder.getInstance().setAccessKey(null); } protected void setQpidNotificationService(QpidNotificationService qpidNotificationService) { // Qpid broker should not start until Qpid bundle is activated. // QpidNotificationService informs that the Qpid bundle has started. } protected void unsetQpidNotificationService(QpidNotificationService qpidNotificationService) { } protected void setServerConfiguration(ServerConfigurationService serverConfiguration) { QpidServiceDataHolder.getInstance().setCarbonConfiguration(serverConfiguration); } protected void unsetServerConfiguration(ServerConfigurationService serverConfiguration) { QpidServiceDataHolder.getInstance().setCarbonConfiguration(null); } protected void setEventBundleNotificationService(EventBundleNotificationService eventBundleNotificationService) { QpidServiceDataHolder.getInstance().registerEventBundleNotificationService(eventBundleNotificationService); } protected void unsetEventBundleNotificationService(EventBundleNotificationService eventBundleNotificationService) { // unsetting } /** * Access Hazelcast Instance, which is exposed as an OSGI service. * * @param hazelcastInstance hazelcastInstance found from the OSGI service */ protected void setHazelcastInstance(HazelcastInstance hazelcastInstance) throws AndesException { HazelcastAgent.getInstance().init(hazelcastInstance); registeredHazelcast = true; if (brokerShouldBeStarted) { //Start the broker if the activate method of QpidServiceComponent is blocked until hazelcastInstance // getting registered try { this.startAndesBroker(); } catch (ConfigurationException e) { log.error("Invalid configuration found in a configuration file", e); this.shutdown(); } } } protected void unsetHazelcastInstance(HazelcastInstance hazelcastInstance) { } /** * Access ConfigurationContextService, which is exposed as an OSGI service, to read cluster configuration. * * @param configurationContextService ConfigurationContextService from the OSGI service */ protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { ClusteringAgent agent = configurationContextService.getServerConfigContext().getAxisConfiguration() .getClusteringAgent(); AndesContext.getInstance().setClusteringEnabled(agent != null); } protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { // Do nothing } /** * Access IServerAdmin, which is exposed as an OSGi service, to call the graceful shutdown method in the carbon * kernel. */ protected void setIServerAdmin(IServerAdmin iServerAdmin) { QpidServiceDataHolder.getInstance().setService(iServerAdmin); } /** * Unset IServerAdmin OSGi service */ protected void unsetIServerAdmin(IServerAdmin iServerAdmin) { QpidServiceDataHolder.getInstance().setService(null); } /** * Shutdown from the carbon kernel level. */ private void shutdown() throws AndesException { //Calling carbon kernel shutdown method, inside the ServerAdmin component try { QpidServiceDataHolder.getInstance().getService().shutdownGracefully(); } catch (Exception e) { log.error("Error occurred while shutting down", e); throw new AndesException("Error occurred while shutting down", e); } } /** * Check if the broker is up and running * * @return true if the broker is running or false otherwise */ private boolean isBrokerRunning() { boolean response = false; try { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); Set<ObjectName> set = mBeanServer.queryNames( new ObjectName("org.wso2.andes:type=VirtualHost.VirtualHostManager,*"), null); if (set.size() > 0) { // Virtual hosts created, hence broker running. response = true; } } catch (MalformedObjectNameException e) { log.error("Error checking if broker is running.", e); } return response; } private int readPortOffset() { ServerConfiguration carbonConfig = ServerConfiguration.getInstance(); String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(CARBON_CONFIG_PORT_OFFSET)); try { return ((portOffset != null) ? Integer.parseInt(portOffset.trim()) : CARBON_DEFAULT_PORT_OFFSET); } catch (NumberFormatException e) { return CARBON_DEFAULT_PORT_OFFSET; } } /*** * This applies the bindAddress from broker.xml instead of the hostname from carbon.xml within MB. * @return host name as derived from broker.xml */ private String getTransportBindAddress() { return AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_BIND_ADDRESS); } /*** * This applies the MQTTbindAddress from broker.xml instead of the hostname from carbon.xml within MB. * @return host name as derived from broker.xml */ private String getMQTTTransportBindAddress() { return AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_MQTT_BIND_ADDRESS); } /*** * This applies the AMQPbindAddress from broker.xml instead of the hostname from carbon.xml within MB. * @return host name as derived from broker.xml */ private String getAMQPTransportBindAddress() { return AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_AMQP_BIND_ADDRESS); } /** * Start Andes Broker and related components with given configurations. * * @throws ConfigurationException * @throws AndesException */ private void startAndesBroker() throws ConfigurationException, AndesException { brokerShouldBeStarted = false; String dSetupValue = System.getProperty("setup"); if (dSetupValue != null) { // Source MB rdbms database if data source configurations and supported sql exist MessageBrokerDBUtil messageBrokerDBUtil = new MessageBrokerDBUtil(); messageBrokerDBUtil.initialize(); } // Start andes broker log.info("Activating Andes Message Broker Engine..."); System.setProperty(BrokerOptions.ANDES_HOME, qpidServiceImpl.getQpidHome()); String[] args = {"-p" + qpidServiceImpl.getAMQPPort(), "-s" + qpidServiceImpl.getAMQPSSLPort(), "-q" + qpidServiceImpl.getMqttPort()}; //TODO: Change the functionality in andes main method to an API //Main.setStandaloneMode(false); Main.main(args); // Remove Qpid shutdown hook so that I have control over shutting the broker down Runtime.getRuntime().removeShutdownHook(ApplicationRegistry.getShutdownHook()); // Wait until the broker has started while (!isBrokerRunning()) { try { Thread.sleep(500); } catch (InterruptedException ignore) { //ignore } } // TODO: Have to re-structure how andes broker getting started. // there should be a separate andes-core component to initialize Andes Broker. Within // that component both Qpid and MQTT components should initialized. // Start AMQP server with given configurations startAMQPServer(); // Start MQTT Server with given configurations startMQTTServer(); // Message broker is started with both AMQP and MQTT log.info("WSO2 Message Broker is started."); // Publish Qpid properties registrations.push(bundleContext.registerService( QpidService.class.getName(), qpidServiceImpl, null)); Integer brokerPort; if (qpidServiceImpl.getIfSSLOnly()) { brokerPort = qpidServiceImpl.getAMQPSSLPort(); } else { brokerPort = qpidServiceImpl.getAMQPPort(); } QpidServerDetails qpidServerDetails = new QpidServerDetails(qpidServiceImpl.getAccessKey(), qpidServiceImpl.getClientID(), qpidServiceImpl.getVirtualHostName(), qpidServiceImpl.getHostname(), brokerPort.toString(), qpidServiceImpl.getIfSSLOnly()); QpidServiceDataHolder.getInstance().getEventBundleNotificationService().notifyStart(qpidServerDetails); } /** * check whether the tcp port has started. some times the server started thread may return * before Qpid server actually bind to the tcp port. in that case there are some connection * time out issues. * * @throws ConfigurationException */ private void startAMQPServer() throws ConfigurationException { boolean isServerStarted = false; int port; if (qpidServiceImpl.getIfSSLOnly()) { port = qpidServiceImpl.getAMQPSSLPort(); } else { port = qpidServiceImpl.getAMQPPort(); } if (AndesConfigurationManager.<Boolean>readValue(AndesConfiguration.TRANSPORTS_AMQP_ENABLED)) { while (!isServerStarted) { Socket socket = null; try { InetAddress address = InetAddress.getByName(getAMQPTransportBindAddress()); socket = new Socket(address, port); log.info("AMQP Host Address : " + address.getHostAddress() + " Port : " + port); isServerStarted = socket.isConnected(); if (isServerStarted) { log.info("Successfully connected to AMQP server " + "on port " + port); } } catch (IOException e) { log.error("Wait until Qpid server starts on port " + port, e); try { Thread.sleep(500); } catch (InterruptedException ignore) { // Ignore } } finally { try { if ((socket != null) && (socket.isConnected())) { socket.close(); } } catch (IOException e) { log.error("Can not close the socket which is used to check the server " + "status ", e); } } } } else { log.warn("AMQP Transport is disabled as per configuration."); } } /** * check whether the tcp port has started. some times the server started thread may return * before MQTT server actually bind to the tcp port. in that case there are some connection * time out issues. * * @throws ConfigurationException */ private void startMQTTServer() throws ConfigurationException { boolean isServerStarted = false; int port; if (qpidServiceImpl.getMQTTSSLOnly()) { port = qpidServiceImpl.getMqttSSLPort(); } else { port = qpidServiceImpl.getMqttPort(); } if (AndesConfigurationManager.<Boolean>readValue(AndesConfiguration.TRANSPORTS_MQTT_ENABLED)) { while (!isServerStarted) { Socket socket = null; try { InetAddress address = InetAddress.getByName(getMQTTTransportBindAddress()); socket = new Socket(address, port); log.info("MQTT Host Address : " + address.getHostAddress() + " Port : " + port); isServerStarted = socket.isConnected(); if (isServerStarted) { log.info("Successfully connected to MQTT server on port " + port); } } catch (IOException e) { log.error("Wait until server starts on port " + port, e); try { Thread.sleep(500); } catch (InterruptedException ignore) { // Ignore } } finally { try { if ((socket != null) && (socket.isConnected())) { socket.close(); } } catch (IOException e) { log.error("Can not close the socket which is used to check the server " + "status ", e); } } } } else { log.warn("MQTT Transport is disabled as per configuration."); } } /** * Private class containing the tasks that need to be done at server shut down */ private static class MBShutdownHandler implements ServerShutdownHandler, ServerRestartHandler { @Override public void invoke() { try { //executing pre-shutdown work for registered listeners before shutting down the andes server for(BrokerLifecycleListener listener: QpidServiceDataHolder.getInstance() .getBrokerLifecycleListeners()){ listener.onShuttingdown(); } AndesKernelBoot.shutDownAndesKernel(); //executing post-shutdown work for registered listeners after shutting down the andes server for(BrokerLifecycleListener listener: QpidServiceDataHolder.getInstance() .getBrokerLifecycleListeners()){ listener.onShutdown(); } } catch (AndesException e) { log.error("Error while shutting down Andes kernel. ", e); } } } }
hastef88/carbon-business-messaging
components/andes/org.wso2.carbon.andes/src/main/java/org/wso2/carbon/andes/internal/QpidServiceComponent.java
Java
apache-2.0
24,553
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.dataset; import java.util.LinkedList; import java.util.List; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.spi.Registry; import org.junit.Before; import org.junit.Test; public class ListDataSetConsumerTest extends ContextTestSupport { protected ListDataSet dataSet; final String resultUri = "mock://result"; final String dataSetName = "foo"; final String dataSetUri = "dataset://" + dataSetName; @Override protected Registry createRegistry() throws Exception { Registry answer = super.createRegistry(); answer.bind("foo", dataSet); return answer; } @Test public void testDefaultListDataSet() throws Exception { MockEndpoint result = getMockEndpoint(resultUri); result.expectedMinimumMessageCount((int)dataSet.getSize()); result.assertIsSatisfied(); } @Test public void testDefaultListDataSetWithSizeGreaterThanListSize() throws Exception { MockEndpoint result = getMockEndpoint(resultUri); dataSet.setSize(10); result.expectedMinimumMessageCount((int)dataSet.getSize()); result.assertIsSatisfied(); } @Override @Before public void setUp() throws Exception { List<Object> bodies = new LinkedList<>(); bodies.add("<hello>world!</hello>"); dataSet = new ListDataSet(bodies); super.setUp(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from(dataSetUri).to("mock://result"); } }; } }
DariusX/camel
core/camel-core/src/test/java/org/apache/camel/component/dataset/ListDataSetConsumerTest.java
Java
apache-2.0
2,600
<wicket:extend xmlns:wicket="http://wicket.apache.org"> This page demonstrates a simple RefreshingView. Notice that when you click refresh or make a selection the id of item object changes because it is regenerated unlike items in the OrderedRepeatingView. <br/><br/> <a href="#" wicket:id="refreshLink">refresh</a><br/><br/> <div> <table cellspacing="0" class="dataview"> <tr> <th>Item Id</th> <th>Actions</th> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Home Phone</th> <th>Cell Phone</th> </tr> <tr wicket:id="view"> <td><span wicket:id="itemid">[item id]</span></td> <td><span wicket:id="actions">[actions]</span></td> <td><span wicket:id="contactid">[contactid]</span> </td> <td><span wicket:id="firstname">[firstname]</span></td> <td><span wicket:id="lastname">[lastname]</span></td> <td><span wicket:id="homephone">[homephone]</span></td> <td><span wicket:id="cellphone">[cellphone]</span></td> </tr> </table> </div> </wicket:extend>
mosoft521/wicket
wicket-examples/src/main/java/org/apache/wicket/examples/repeater/RefreshingPage.html
HTML
apache-2.0
1,003
<script src="{{ASSET_DIR_PREFIX}}/assets/constants.js"></script> {% if MINIFICATION or not DEV_MODE %} <script src="{{ASSET_DIR_PREFIX}}/assets/hashes.js"></script> {% endif %} <!-- jquery.js, angular.js and jquery-ui.js are removed from bundled js because they need to be at the header. Including bundled js at the header will block rendering.--> <script src="/third_party/static/jquery-3.0.0/jquery.min.js"></script> <script src="/third_party/static/jqueryui-1.10.3/jquery-ui.min.js"></script> <script src="/third_party/static/angularjs-1.5.8/angular.min.js"></script> <script src="/third_party/static/jquery-ui-touch-punch-0.3.1/jquery.ui.touch-punch-improved.js"></script> <!-- See http://docs.mathjax.org/en/latest/start.html#mathjax-cdn --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ skipStartupTypeset: true, messageStyle: 'none', 'HTML-CSS': { linebreaks: { automatic: true, width: '500px' }, scale: 91, showMathMenu: false } }); MathJax.Hub.Configured(); </script> <script src="/third_party/static/MathJax-2.6.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
MAKOSCAFEE/oppia
core/templates/dev/head/pages/header_js_libs.html
HTML
apache-2.0
1,152
<html lang='kg'> <!-- ** ** Copyright 2006, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ --> <p>Bizingi bioso bisiwu ti batu bambutukanga mu kidedi ki buzitu ayi kibumswa. Bizingi-bene, batu, badi diela ayi tsi-ntima, bafwene kuzingila mbatzi-na-mbatzi-yandi mu mtima bukhomba.</p> </html>
googlei18n/noto-source
test/LGC/fontdiff-kg-Latn-AO_udhr.html
HTML
apache-2.0
841
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <net/configure.hpp> #include <net/interfaces.hpp> #include <info> #define MYINFO(X,...) INFO("Netconf",X,##__VA_ARGS__) //#define NETCONF_DEBUG 1 #ifdef NETCONF_DEBUG #define PRINT(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define PRINT(fmt, ...) /* fmt */ #endif namespace net { struct ipv4_res { ip4::Addr addr; ip4::Addr netmask; }; struct ipv6_res { ip6::Addr addr; uint8_t prefix; }; struct v4_config { ip4::Addr addr; ip4::Addr netmask; ip4::Addr gateway; ip4::Addr dns; }; struct v6_config { std::vector<ipv6_res> addr; std::vector<ip6::Addr> gateway; std::vector<ip6::Addr> dns; void clear() { addr.clear(); gateway.clear(); dns.clear(); } }; inline bool is_v6(const std::string& str) { Expects(not str.empty() && "Address string can't be empty"); return str.find(':') != std::string::npos; } inline ipv4_res parse_addr4(const std::string& str) { if(auto n = str.rfind('/'); n != std::string::npos) { uint8_t bits = std::stoi(str.substr(n+1)); ip4::Addr netmask{ntohl(0xFFFFFFFF << (32ul-bits))}; //PRINT("Bits %u Netmask %s\n", bits, netmask.to_string().c_str()); return {str.substr(0, n), netmask}; } else { return {str, 0}; } } inline ipv6_res parse_addr6(const std::string& str) { if(auto n = str.rfind('/'); n != std::string::npos) { uint8_t prefix = std::stoi(str.substr(n+1)); return {str.substr(0, n), prefix}; } else { return {str, 0}; } } inline void parse_addr(v4_config& cfg4, v6_config& cfg6, std::string str) { if(is_v6(str)) { cfg6.addr.push_back(parse_addr6(str)); PRINT("v6 Addr: %s Prefix: %u\n", cfg6.addr.back().addr.to_string().c_str(), cfg6.addr.back().prefix); } else { if(cfg4.addr != 0) { MYINFO("WARN: Multiple v4 addresses not supported: skipping %s", str.c_str()); return; } auto [addr, netmask] = parse_addr4(str); cfg4.addr = addr; cfg4.netmask = netmask; PRINT("v4 Addr: %s Netmask: %s\n", cfg4.addr.to_string().c_str(), cfg4.netmask.to_string().c_str()); } } inline void parse_gateway(v4_config& cfg4, v6_config& cfg6, std::string str) { if(is_v6(str)) { cfg6.gateway.push_back(parse_addr6(str).addr); PRINT("v6 Gateway: %s\n", cfg6.gateway.back().to_string().c_str()); } else { if(cfg4.gateway != 0) { MYINFO("WARN: Multiple v4 gateways not supported: skipping %s", str.c_str()); return; } cfg4.gateway = parse_addr4(str).addr; PRINT("v4 Gateway: %s\n", cfg4.gateway.to_string().c_str()); } } inline void parse_dns(v4_config& cfg4, v6_config& cfg6, std::string str) { if(is_v6(str)) { cfg6.dns.push_back(parse_addr6(str).addr); PRINT("v6 DNS: %s\n", cfg6.dns.back().to_string().c_str()); } else { if(cfg4.dns != 0) { MYINFO("WARN: Multiple v4 DNS not supported: skipping %s", str.c_str()); return; } cfg4.dns = parse_addr4(str).addr; PRINT("v4 DNS: %s\n", cfg4.dns.to_string().c_str()); } } inline void config4(Inet& stack, const v4_config& cfg) { Expects(cfg.addr != 0 && "Missing address (v4)"); Expects(cfg.netmask != 0 && "Missing netmask"); stack.network_config(cfg.addr, cfg.netmask, cfg.gateway, cfg.dns); } inline void config6(Inet& stack, const v6_config& cfg) { // add address for(const auto& [addr, prefix] : cfg.addr) (prefix) ? stack.add_addr(addr, prefix) : stack.add_addr(addr); // add routers for(const auto& addr : cfg.gateway) stack.ndp().add_router(addr, 0xFFFF); // waiting for API to change // add dns for(const auto& addr : cfg.dns) { stack.set_dns_server6(addr); break; // currently only support one } } template <typename Val, typename Func> inline void parse(const Val& val, v4_config& cfg4, v6_config& cfg6, Func func) { if(val.IsArray()) { PRINT("Member is array\n"); for(auto& addrstr : val.GetArray()) { func(cfg4, cfg6, addrstr.GetString()); } } else { func(cfg4, cfg6, val.GetString()); } } void configure(const rapidjson::Value& net) { MYINFO("Configuring network"); Expects(net.IsArray() && "Member net is not an array"); auto configs = net.GetArray(); if(configs.Size() > Interfaces::get().size()) MYINFO("WARN: Found more configs than there are interfaces"); // Iterate all interfaces in config for(auto& val : configs) { Expects(val.HasMember("iface") && "Missing member iface - don't know which interface to configure"); auto N = val["iface"].GetInt(); auto& stack = Interfaces::get(N); // if config is not set, just ignore if(not val.HasMember("config")) { MYINFO("WARN: Config method not set, ignoring"); continue; } v4_config v4cfg; v6_config v6cfg; // "address" if(val.HasMember("address")) { parse(val["address"], v4cfg, v6cfg, &parse_addr); } // "netmask" (ipv4 only) if(v4cfg.netmask == 0 and val.HasMember("netmask")) v4cfg.netmask = {val["netmask"].GetString()}; // "gateway" if(val.HasMember("gateway")) { parse(val["gateway"], v4cfg, v6cfg, &parse_gateway); } // "dns" if(val.HasMember("dns")) { parse(val["dns"], v4cfg, v6cfg, &parse_dns); } std::vector<std::string> methods; const auto& config = val["config"]; // parse all the config methods if(config.IsArray()) { for(const auto& method : val["config"].GetArray()) methods.push_back(method.GetString()); } else { methods.push_back(val["config"].GetString()); } for(const auto& method : methods) { const double timeout = (val.HasMember("timeout")) ? val["timeout"].GetDouble() : 10.0; if(method == "dhcp") { stack.negotiate_dhcp(timeout); // do DHCPv6 } else if(method == "dhcp4") { stack.negotiate_dhcp(timeout); } else if(method == "dhcp6") { MYINFO("WARN: DHCPv6 not supported"); } else if(method == "static") { config4(stack, v4cfg); config6(stack, v6cfg); v6cfg.clear(); } else if(method == "static4") { config4(stack, v4cfg); } else if(method == "static6") { config6(stack, v6cfg); v6cfg.clear(); } else if(method == "slaac") { stack.autoconf_v6(); } else if(method == "dhcp-with-fallback") // TBD... { auto static_cfg = [v4cfg, &stack] (bool timedout) { if(timedout) { MYINFO("DHCP timeout (%s) - falling back to static configuration", stack.ifname().c_str()); config4(stack, v4cfg); } }; stack.negotiate_dhcp(timeout, static_cfg); } else { MYINFO("WARN: Unrecognized config method \"%s\"", method.c_str()); } } } MYINFO("Configuration complete"); } }
AnnikaH/IncludeOS
src/net/configure.cpp
C++
apache-2.0
7,663
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package groovy.json; import groovy.lang.Closure; import groovy.lang.GroovyObjectSupport; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Utility class used as delegate of closures representing JSON objects. * * @since 1.8.0 */ public class JsonDelegate extends GroovyObjectSupport { private final Map<String, Object> content = new LinkedHashMap<String, Object>(); /** * Intercepts calls for setting a key and value for a JSON object * * @param name the key name * @param args the value associated with the key */ @Override public Object invokeMethod(String name, Object args) { Object val = null; if (args != null && Object[].class.isAssignableFrom(args.getClass())) { Object[] arr = (Object[]) args; if (arr.length == 1) { val = arr[0]; } else if (isIterableOrArrayAndClosure(arr)) { Closure<?> closure = (Closure<?>) arr[1]; Iterator<?> iterator = (arr[0] instanceof Iterable) ? ((Iterable) arr[0]).iterator() : Arrays.asList((Object[])arr[0]).iterator(); List<Object> list = new ArrayList<Object>(); while (iterator.hasNext()) { list.add(curryDelegateAndGetContent(closure, iterator.next())); } val = list; } else { val = Arrays.asList(arr); } } content.put(name, val); return val; } private static boolean isIterableOrArrayAndClosure(Object[] args) { if (args.length != 2 || !(args[1] instanceof Closure)) { return false; } return ((args[0] instanceof Iterable) || (args[0] != null && args[0].getClass().isArray())); } /** * Factory method for creating <code>JsonDelegate</code>s from closures. * * @param c closure representing JSON objects * @return an instance of <code>JsonDelegate</code> */ public static Map<String, Object> cloneDelegateAndGetContent(Closure<?> c) { JsonDelegate delegate = new JsonDelegate(); Closure<?> cloned = (Closure<?>) c.clone(); cloned.setDelegate(delegate); cloned.setResolveStrategy(Closure.DELEGATE_FIRST); cloned.call(); return delegate.getContent(); } /** * Factory method for creating <code>JsonDelegate</code>s from closures currying an object * argument. * * @param c closure representing JSON objects * @param o an object curried to the closure * @return an instance of <code>JsonDelegate</code> */ public static Map<String, Object> curryDelegateAndGetContent(Closure<?> c, Object o) { JsonDelegate delegate = new JsonDelegate(); Closure<?> curried = c.curry(o); curried.setDelegate(delegate); curried.setResolveStrategy(Closure.DELEGATE_FIRST); curried.call(); return delegate.getContent(); } public Map<String, Object> getContent() { return content; } }
apache/incubator-groovy
subprojects/groovy-json/src/main/java/groovy/json/JsonDelegate.java
Java
apache-2.0
4,013